// custom jquery scripts //



// base navigation script

  $(document).ready(function(){
	$('.topnavitem').mouseover(function(){
		$('.topnavitem').css({ 'background-color': '#F0F0F0', 'color':'gray'}); // clear all parent highlights
		$('.topnavitem > a').css({'color': 'gray'})
		$('.secondnavitem').css({  'text-decoration' :'none' }); // clear all children highlights
		$(this).css({ 'background-color': 'gray', 'color': 'white' }); // highlight current top level nav item
		$('a:visited', this).css({'color': 'white'}) // set the link color to white
		//console.log('hiding children')
		$('.secondnavitem').hide() // hide all children
		//console.log('hiding children done')
		//console.log('showing child')
		$('.'+$(this).attr('child')).fadeIn() // show the top level nav item's children
		//console.log('showing children done')
		if (this.id != 'hometoplevel'){
		$('#secondnavcontainer').css({ 'background-color': '#FAFAFA' }); // effectivly makes the second nav container visible
		} else{
			$('#secondnavcontainer').css({ 'background-color': 'white' }); // effectively hides the second nav container, cuz it's the home button
			}
	$('.secondnavitem').mouseover(function(){
		$('.secondnavitem').css({ 'text-decoration' :'none' }); // clear all children highlights
		$(this).css({ 'text-decoration' :'underline' }) //highlight the child
	});		
	
	$('#navigation').mouseleave(function(){
		$('.secondnavitem').hide() // hide all children
		$('.topnavitem').css({ 'background-color': '#F0F0F0', 'color':'gray' }); // clear all top highlights
		$('.topnavitem > a:visited').css({'color': 'gray'})
		$('#secondnavcontainer').css({ 'background-color': 'white' }); // effectivly hides the second nav container
	});
	
 });
  });
 


// this script load the collection icons after document.ready so that they don't slow down loading of visible parts. custom attribute has the actual src, and is then swapped
$(document).ready(function(){
	$('.collectionicon').each(function(){
		var image = $(this).attr('image')
		$(this).attr('src', image)
	});
})

$(document).ready(function(){
	$('.buttonholder').click(function(){
		if ( this.id == 'detailbutton' ) {
			if ( $(this).attr('active') == 'no') {
				detailstart()
			} else {
				detailend()
			}
		} else if (this.id == 'zoombutton'){
			zoomstart()
			/* zoom (full size) doesn't need to be turned on/off
			if ( $(this).attr('active') == 'no') {
				zoomstart()
			} else {
				zoomend()
			}
			*/
		} else if (this.id == 'collectbutton'){
			if ( $(this).attr('active') == 'no') {
				collectstart()
			} else {
				collectend()
			}
		} else if (this.id == 'sharebutton'){
			if ( $(this).attr('active') == 'no') {
				sharestart()
			} else {
				shareend()
			}
		} else if (this.id == 'favoritebutton') {
			if ( $(this).attr('active') == 'no') {
				favoritestart()
			} else {
				favoriteend()
			}
		}
	}).mouseenter(function(){
		$('.buttontext', this).css({'text-decoration':'underline'})
	}).mouseleave(function(){
		$('.buttontext', this).css({'text-decoration':'none'})
	});
});



function detailstart(){
	$('#detailbutton').attr('active', 'yes')
	$('#detailbuttonicon').css({'background-position': '-0px -25px'})
	$('#detailbutton > .inactivetext').hide()
	$('#detailbutton > .activetext').show()
	zoomend()
	collectend()
	shareend()
	add_detail()
	//add_detail() // kick off the add detail function
}

function detailend(){
	$('#detailbutton').attr('active', 'no')
	$('#detailbuttonicon').css({'background-position': '-0px -0px'})
	$('#detailbutton > .inactivetext').show()
	$('#detailbutton > .activetext').hide()
	add_detail_done()
}

function zoomstart(){
	/*
	$('#zoombutton').attr('active', 'yes')
	$('#zoombuttonicon').css({'background-position': '-0px -79px'})
	$('#zoombutton > .inactivetext').hide()
	$('#zoombutton > .activetext').show()
	*/
	detailend()
	shareend()
	collectend()
	// actual function:
	start_zoom()
	
}

function zoomend(){
	$('#zoombutton').attr('active', 'no')
	$('#zoombuttonicon').css({'background-position': '-0px -54px'})
	$('#zoombutton > .inactivetext').show()
	$('#zoombutton > .activetext').hide()
	end_zoom()
}

function collectstart(){
	$('#collectbutton').attr('active', 'yes')
	$('#collectbuttonicon').css({'background-position': '-0px -132px'})
	$('#collectbutton > .inactivetext').hide()
	$('#collectbutton > .activetext').show()
	zoomend()
	shareend()
	detailend()
	$('#collectpanel').show('slow');
}

function collectend(){
	$('#collectbutton').attr('active', 'no')
	$('#collectbuttonicon').css({'background-position': '-0px -107px'})
	$('#collectbutton > .inactivetext').show()
	$('#collectbutton > .activetext').hide()
	//actual function:
	$('#collectpanel').hide('slow');
}

function sharestart(){
	$('#sharebutton').attr('active', 'yes')
	$('#sharebuttonicon').css({'background-position': '-0px -187px'})
	$('#sharebutton > .inactivetext').hide()
	$('#sharebutton > .activetext').show()
	collectend()
	detailend()
	zoomend()
	$('#sharepanel').show('fast');
}

function shareend(){
	$('#sharebutton').attr('active', 'no')
	$('#sharebuttonicon').css({'background-position': '-0px -162px'})
	$('#sharebutton > .inactivetext').show()
	$('#sharebutton > .activetext').hide()
	$('#sharepanel').hide('fast');
}

function favoritestart(){
	$('#favoritebutton').attr('active', 'yes')
	$('#favoritebuttonicon').css({'background-position': '-0px -240px'})
	$('#favoritebutton > .inactivetext').hide()
	$('#favoritebutton > .activetext').show()
	favorites_click()
};

function favoriteend(){
	$('#favoritebutton').attr('active', 'no')
	$('#favoritebuttonicon').css({'background-position': '-0px -214px'})
	$('#favoritebutton > .inactivetext').show()
	$('#favoritebutton > .activetext').hide()
	favorites_click()
};


// add or remove from favorites, called each time user click on heart

function favorites_click(){
		id = $('#favoritebutton').attr('number')
		type = $('#favoritebutton').attr('category')
		$.post('/en/favorite/', {
			type: type, 
			id: id
			}, function(data){
			}, 'json');
		};

// initial check to see if art is already a favorite, if so, sets up the button accordingly		

$(document).ready(function(){
	if ( $('#favoritebutton').attr('active') == 'yes' ){
	$('#favoritebuttonicon').css({ 'background-position': '-0px -240px'})
	$('#favoritebutton > .inactivetext').hide()
	$('#favoritebutton > .activetext').show()
	} else{
	}
	if ( $('#viewchoicebutton').attr('wall') == 'yes' ){
	$('#viewchoiceicon').css({ 'background-position': '-0px -300px'})
	$('#viewchoicebutton > .inactivetext').hide()
	$('#viewchoicebutton > .activetext').show()
	} else{
	}
})

// add tag functionality //

$(document).ready(function(){
	$('#submittag').click(function(){
		tag = $('#addtaginput').val()
		language_code =  $('#infodiv').attr('lc')
		artid = $('#infodiv').attr('artid')
		$.post('/'+language_code+'/addtag/', {
			art_id :artid ,
			tag : tag
		},
		function(data){
			//alert(data.tags)
			for (tag in data.tags)
			{
			//alert(data.tags[tag])
			new_html = "<div class='singletag'>"+data.tags[tag]+"</div>"
			//alert (new_html)
			$('#tagitems').append(new_html)
			}
			$('#addtaginput').val('');
		}, 'json');
	});
});


// invite beta user //

$(document).ready(function(){
	$('#invite').click(function(){
		invitee = $('#id_email').val()
		language_code =  $('#infodiv').attr('lc')
		$.post('/'+language_code+'/accounts/invite/', {
			email_id: invitee
		}, function(data){
			 $('#id_email').val('')
		}, 'json');
	})
});

///////////////////////////
// collect this function //
///////////////////////////

$(document).ready(function(){
	$('.collectiontitle').live("click",
	function(){
		status = $(this).attr('status')
		kid = $(this).attr('kid')
		items = $(this).attr('items')
		collectionnumber = $(this).attr('collectionnumber')
		offen = $('.openclosed'+collectionnumber).attr('open')
		collapsed = $('.openclosed'+collectionnumber).attr('collapsed')
		if( status == 'closed' ) {
		$('.'+kid).show('fast')
		$('.'+items).each(function(){
			bild = $(this).attr('image')
			$(this).attr({'src': bild})
		});
		$(this).attr({'status': 'open-loaded'})
		$('.openclosed'+collectionnumber).attr({'src': offen })
		}
		else if(status == 'open-loaded'){
		$(this).attr({'status': 'closed-loaded'})
		$('.'+kid).hide('fast')
		$('.openclosed'+collectionnumber).attr({'src': collapsed })
		}
		else if(status =='closed-loaded'){
		$('.'+kid).show('fast')
		$(this).attr({'status': 'open-loaded'})
		$('.openclosed'+collectionnumber).attr({'src': offen })
		}
	});
});

$(document).ready(function(){
	$('.addtocollection').click(function(){
		coll_id = $(this).attr('uc_id')
		art_id = $('#infodiv').attr('artid')
		command = $(this).attr('command')
		$.post("/en/collect/", {coll_id: coll_id, art_id: art_id, command: command }, function(data)
		{ 
		console.log(data.imageurl)
		if (command == 'add'){
		new_html = "<img class='items"+coll_id+"' id='item"+art_id+"' style='padding:0px; float:left;' width='50px' height='50px' src='"+data.imageurl+"' />"
		$('.collection'+coll_id).prepend(new_html)
		$('#addremove'+coll_id).html('remove').attr({'command': 'remove'})
		}
		else{
		rem = $('.collection'+coll_id).find('#item'+art_id)
		$(rem).hide()
		$('#addremove'+coll_id).html('add').attr({'command': 'add'})
		}
		
		}, 'json');
	});
});

////////////////////
// zoom function ///
////////////////////

function start_zoom(){	// zoom kickoff
	full_image = $('#infodiv').attr('full_image')
	caption = $('#infodiv').attr('image_caption')
	$.slimbox(full_image, caption);
};

function end_zoom(){
	$("#navArea").hide();
	$('#imagediv').show();
};


/////////////////////
// mouse over image// 
/////////////////////


// show detail borders and brings up the absolute divs for mouseovers

$(document).ready(function(){ 
    $("#image").mouseenter(function(){
      $('.absolutediv').show();
	  $('div.absolutediv').css({'border-width':'1px'})
    });
});

 

// this function controls what happens when a user mouses over an absolutly positioned div (the placeholder divs that represent a tagged area)
// it get's the coordinates from custom attributes of the div itself, send creates an img area selection
$(document).ready(function(){
	$('div.absolutediv').live("mouseover",function(){
		x1 = $(this).attr('x1') 
		x2 = parseInt($(this).attr('x2'))  +2 // to take into account that the border has increased the width by 2
		y1 = parseInt($(this).attr('y1')) 
		y2 = parseInt($(this).attr('y2')) + 2 //as above
		thenumber = $(this).attr('number')
		$('#image').imgAreaSelect({ x1: x1, x2: x2, y1: y1, y2: y2,  resizable: false, movable:false, handles:false, fadeSpeed:150, instance: true  });
		$('div.absolutediv').css({'border-width':'0px'});
		boxpositionx = parseInt(x2) +10 +'px'
		boxpositiony = parseInt(y1) +'px'
		$('#infobox').css({'left':boxpositionx, 'top': boxpositiony }).show() // makes the infobox visible 
		thenumber = $(this).attr('number')
		theclass = 'detailtitle'+thenumber
		theotherclass = 'detaildescription'+thenumber
		title = $('.detailtitle'+thenumber).html()
		beschreibung =  $('.detaildescription'+thenumber).text()
		//descobj = $('.'+theotherclass)
		//description = $('.detaildescription322').text()
		//description = $('.'+theotherclass).html()
		$('#infobox').children('h2').html(title)
		$('#infobox').children('p').html(beschreibung)		
		
		$('.imageareaselect-selection').live("mouseover", function(){
			$(this).css("cursor","pointer")
			});	
		
	});
// this function controls what happens when the mouse leaves the img area selection (by listening to outer-area mouseover)
	$(".imgareaselect-outer").live("mouseover", function(){
		if ( $('#detailbutton').attr('active') == 'yes'){
		// don't hide the selection area and don't set borders if user is in the process of adding a detail
		}
		else{
		$('#image').imgAreaSelect({ hide: true }); 
		$('div.absolutediv').css({'border-width':'1px'});
		$('.detailcontent').css({'background-color': 'white'})
		$('#infobox').hide()
		}
	});
	// there the borders are hidden when the mouse leaves the image altogether
	$('#image').mouseleave(function(){
		$('div.absolutediv').css({'border-width':'0px'})//alert('out of image')
	});
});

///////////////////
// add new detail//
///////////////////

function add_detail(){ // called from detailstart, which is called when inactive 'add detail' button is clicked
	//$('#taginfo').show('fast'); // show a little info box to explain the user what to do
	$('.absolutediv').css({'z-index':'-1'}); // push absolute divs beneath the image, otherwise their mouseover events will interfere with new selection
	$('img#image').imgAreaSelect({ disable: false, hide: false, resizable: true, movable:true, onSelectEnd: ending, onSelectStart: clear}); // create new img area selection instance
	$('#image').css("cursor","crosshair"); // turn mouse pointer into crosshair
	};


function ending(img,selection){ // on selection end, shows and positions the detail from pop-up, and records the coordinates
	if (selection.x2 - selection.x1 + selection.y2 - selection.y1>10){ // condition not to show pop-up on minimal/accidental selections
	$('#holder').css({'left':selection.x2+25+'px', 'top': (selection.height/2) + selection.y1 - 100 +'px', 'z-index': '5'}).fadeIn() //testing z index for IE
	$('#detailtitle').focus();
	//$('#detailtitle').val('')
	//$('#detaildesc').val('') // could make this more generic http://www.electrictoolbox.com/jquery-clear-form/
	}else{
	// if selection is too small, do nothing except to hide the existing pop-up
	$('#holder').hide()
	}
	finished_selection = { x1: selection.x1, y1: selection.y1, x2: selection.x2, y2: selection.y2, width: selection.width, height: selection.height }; // assign coordinates to finished_selection object
 }
 
 
// hides the add-detail pop-up, called each time a new selection is started
 function clear(img,selection)
{
$('#holder').hide()
}


	
// save detail
// evalutates the pop-up form, post the info along with the coordinates to /detailpost/, and add some newly created html to the sidebar
$(document).ready(function(){
	$('#savebutton').click(function(){
		$('#savebutton').attr("disabled", "true");
		$('#detailloader').css({'display': 'block'});
		$("#detailtitle").val()
		lc =  $('#infodiv').attr('lc')
		artid = $('#infodiv').attr('artid')
		$.post("/"+lc+"/detailpost/", {
			x1: finished_selection.x1,
			x2: finished_selection.x2,
			y1: finished_selection.y1,
			y2: finished_selection.y2,
			h: finished_selection.height,
			w: finished_selection.width,
			title: $("#detailtitle").val(),
			desc: $("#detaildesc").val(),
			width: $('#image').attr('width'),
			height: $('#image').attr('height'),
			art_id:  artid,
			language: lc 
		}, function(data){
		//console.log(data)
		$('#detailtitle').val('')
		$('#detaildesc').val('') 
		$('#holder').hide('fast')
		new_html = 	"<div class='detailitem' style='display: none;' x1='"+data.x1+"' x2='"+data.x2+"' y1='"+data.y1+"' y2='" +data.y2+"'>"+
		"<div class='detailcontent'>"+
				"<span class='bold12 detailtitle"+data.id+"'>"+data.title+"</span><br>"+
			"<div class='detailthumbholder'> "+
				"<div class='detailthumb'> "+
					'<img src="/static/'+data.thumb+'">'+
				"</div>"+
			"</div>"+
			"<span class='normal12 detaildescription"+data.id+"'>"+data.description+"</span>"+
			"</div>"+
			"<div class='detailvoteholder'>"+
				"<img src='/static/helpers/vote-arrow-up-inactive.png' title='you cannot vote for your own detail' />"+
					"<div class='detailscore' id='detailscore"+data.id+"'>0</div>"+
				"<img src='/static/helpers/vote-arrow-down-inactive.png' title='you cannot vote for your own detail' />"+
			"</div>"+
			"<div class='cleardiv'>&nbsp</div>"+
		"</div>"	
		abshtml = "<div class='absolutediv' id='detaildiv"+data.title+"' style='position: absolute; left: "+data.x1 +"px; top: "+data.y1+"px; display:block; height:"+data.h+"px; width:"+data.w+"px; border-width: 1px; border-style:dashed; border-color: #000000; z-index=2;'  number='"+data.id+"' x1='"+data.x1+"' x2='"+data.x2+"' y1='"+data.y1+"' y2='" +data.y2+"' >&nbsp;</div>"
		$('#detailscontent').prepend(new_html)
		$('#imagediv').append(abshtml)
		$('#nodetails').fadeOut('fast')
		$('.detailitem').fadeIn('fast')
		$('#savebutton').removeAttr('disabled')
		detailend() // turn off button, guess what, programatically!
		
		fbdetail = $('#fbdetailpublish').attr('checked')
		//alert(fbpost)
		if (fbdetail == true){
			//thumb = $('#infodiv').attr('fbthumb');
			// comment = comment
			//this_url = $('#infodiv').attr('this_url');
			this_url = window.location.href
			caption = $('#infodiv').attr('image_caption');
			user_message = 'added a new detail on friends-of-art.net'
			action_links = null;
			user_message_prompt = null; 
			auto_publish = true;
			actor_id = null;
			target_id =null;
			attachment = {
			'name': caption, 
			'href': this_url,
			'caption': data.title,
			'description': data.description,
			'media': [{ 'type': 'image', 'src': 'http://'+ window.location.host + '/static/'+ data.thumb, 'href': this_url}]
				};
			//console.log(attachment)
			publish_to_facebook(user_message, attachment)
			} else {
				void(0)
			}
		}, "json");
	});
 });
 
 // cancel new detail
 
 $(document).ready(function(){
	$('#cancelbutton').click(function(){
		$('#holder').fadeOut()
		$('#detailtitle').val('')
		$('#detaildesc').val('') 
		$('img#image').imgAreaSelect({ disable: false, hide: true })
	});
});

// done adding detail //

function add_detail_done(){ // done tagging
	$('#taginfo').hide('fast');
	$('#image').css("cursor","default");
	$('img#image').imgAreaSelect({disable: true, hide: true});
	$('.absolutediv').css({'z-index':'auto'}); // bring detail divs back out
	$('#holder').hide()
};



// highlight detail//

$(document).ready(function(){
	$('.detailitem').live("click",function(){
		$('#image').imgAreaSelect({ hide: true })
		x1 = $(this).attr('x1')
		x2 = $(this).attr('x2')
		y1 = $(this).attr('y1')
		y2 = $(this).attr('y2')
		active = $(this).attr('active')
		if (active == 'yes'){
			//alert('used to be active')
			$(this).attr({'active': 'no'})
			$('.detailcontent').css({'background-color':'white'});
			//alert('but no longer')
		}
		else {
		//alert('not active yet')
		// also set active to no for all others
		$('.detailitem').attr('active','no')
		$(this).attr('active','yes')
		//alert('now set to active')
		ias = $('#image').imgAreaSelect({ x1: 1, x2: 2, y1: 1, y2: 2,  resizable: false, movable:false, fadeSpeed:250, instance: true  });
		ias.setSelection(x1, y1, x2, y2, true);
		ias.setOptions({hide:false});
		setTimeout("ias.update()",250); // delays the fading in of the new selection area
		$('.detailcontent').css({'background-color':'white'});
		$(this).find(".detailcontent").css({'background-color': '#A2FF77' });
		}
		
	});
		// clicking on outer area while tagging
		
		$(".imgareaselect-outer").live("click", function(){
			$('#image').imgAreaSelect({ hide: true });
			$('.detailcontent').css({'background-color':'white'});
		});
		
});


////////////////////////
// carousel functions //
////////////////////////

$(document).ready(function(){ // MAKE CAROUSELS
	$('.dynamiccarousel').each(function(){
		$(this).jcarousel({
			itemLoadCallback: itemLoadCallbackFunction,
			initCallback: initiate_carousel,
			carouselid: this.id, //important!
			visible: 3,
			scroll:2
		});
	});
});

function itemLoadCallbackFunction(carousel, state){
	if (state =='init'){
		kids = $('#'+ carousel.carouselid).find('img')
		var i = 0;
		for (i=0; i <=4; i++)
			{
			img = $(kids[i]).attr('image')
			$(kids[i]).attr({'src': img})
			}
		}	
	else if (state == 'next'){
		kid = $('#'+ carousel.carouselid).find('img')[carousel.last]
		img = $(kid).attr('image')
		$(kid).attr({'src': img})
		kid2 = $('#'+ carousel.carouselid).find('img')[carousel.last+1]
		img2 = $(kid2).attr('image')
		$(kid2).attr({'src': img2})
	}
}

function initiate_carousel(carousel,state){ // ON EACH INITIATION, ASSIGN AN ID TO THE CAROUSEL INSTANCE
carousel.carouselid = this.carouselid
};



///////////////////////////
// add art to collection //
///////////////////////////

$(document).ready(function(){
	$('#newcollectiondiv').click(function(){
		$('#createnewcollection').toggle('fast');
		$('#newcollectiontitle').focus();
	})
});


$(document).ready(function(){ // new collection post function
	$('#confirmnewcoll').click(function(){
		var title = $('#newcollectiontitle').val();
		lc =  $('#infodiv').attr('lc')
		artid = $('#infodiv').attr('artid')
		$.post('/'+lc+'/newcollection/', {
		art_id: artid,
		title: title
		},function(data){
		new_html = "<div class='collectionholder'>"+
		"<div class='collectiontitle' collectionnumber='"+data.id+"' status='closed' kid='collection"+data.id+"' items='items"+data.id+"'>"+
		"<img class='openclosed"+data.id+"' src='/static/helpers/closed.png' height='12px' collapsed='/static/helpers/closed.png' open='/static/helpers/open.png'> "+data.title+"</div>"+
		"<div class='collectionparent collection"+data.id+"'>"+
		"<div class='collectionitems'>"+
		"<img class='items"+data.id+"' id='item"+data.art_id+"' style='padding:0px; float:left;' width='50px' height='50px' src='"+data.image+"'>"+
		"</div>"
		$('#existingcollections').prepend(new_html)
		$('#newcollectiontitle').val('')
		$('#createnewcollection').hide('fast')
		},'json' )
	});
});

$(document).ready(function() { // add-remove to collection
	$('.userscollection').toggle(
	function(){
		var id = this.id
		var sliced = id.substring(4)
		lc =  $('#infodiv').attr('lc')
		artid = $('#infodiv').attr('artid')
		$.post("/"+lc+"/collect/", {coll_id: sliced, art_id: artid, command: 'add' }, function(data){ 
		new_html = "<img class='items"+sliced+"' style='padding:0px; float:left;' width='50px' height='50px' src='/static/helpers/no_art_picture.png'"
		// new_html = "<img class='addedicon' style='padding:0px; float:left; display:none;' width='50px' height='50px' src='/static/"+data.imageurl+"'>"
		$('.collection'+sliced).prepend(new_html)
		//$('#usercollectionnumber'+sliced).prepend(new_html)
		//$('.addedicon').fadeIn()
		}, 'json' )	
	},
	function(){
		var id = this.id
		var sliced = id.substring(4)
		lc =  $('#infodiv').attr('lc')
		artid = $('#infodiv').attr('artid')
		$(this).removeClass('ui-state-highlight'),
		$.post("/"+lc+"/collect/", {coll_id: sliced, art_id: artid, command: 'remove' })
	}	
	);
	$('.userscollection').mouseenter(function(){
		$(this).children(".iconholderdiv").children(".addbuttondiv").show()
	}).mouseleave(function(){
		$(this).children(".iconholderdiv").children(".addbuttondiv").hide()
		});
});

// show create coll and add buttons

$(document).ready(function() {
	$('.newuserscollection').mouseenter(function(){
		$(this).children(".iconholderdiv").children(".addbuttondiv").show()
	}).mouseleave(function(){
		$(this).children(".iconholderdiv").children(".addbuttondiv").hide()
		});
})


//////////////////
// comment tabs //
//////////////////

$(document).ready(function(){
	$('.commentstab').click(function(){
		$('.commentscontainer').slideUp() // hide();
		$('#'+$(this).attr('child')).slideDown() //show()
		$('.commentstab').css({'background-color':'#F3F3F3','color':'gray'})
		$(this).css({'background-color':'gray', 'color':'white'})
	});
});



/////////////////////
// submit comments //
/////////////////////


$(document).ready(function(){
	$('.commentsubmit').click(function(){
		$(this).attr("disabled", "true");
		var category = $(this).attr('category')
		var art = $(this).attr('art')
		var comment = $('#'+$(this).attr('category')).val()
		var lang = $(this).attr('lc')
		var destination = $(this).attr('destination')
		$.post('/'+lang+'/artcomment/', {
			comment: comment,
			category: category,
			art: art,
			lang: lang
		},
		function(data) {
			//console.log(data)
			new_comment = "<div id='comment"+data.commentid+"' class='commentsitem' style='background-color:#FFFFFF; display:none'><div class='commentscontent'><div class='profileimageholder' ><img class='profileimage' src='"+data.pic+"' /> </div> <span class='commentcontent'><b>"+data.username+":</b>"+data.comment+"</span></div>"+
				"<div class='commentsvote'>	<img src='/static/helpers/vote-arrow-up-inactive.png' title='you cannot vote for your own comment' />"+
				"<div class='commentscore' id='score{{comment.id}}'>0</div>"+
				"<img src='/static/helpers/vote-arrow-down-inactive.png' title='you cannot vote for your own comment' /></div></div>"
			$('.all'+destination).append(new_comment);
			$('#comment'+data.commentid).fadeIn('slow');
			$('#'+category).val('');
			$('.commentsubmit').removeAttr('disabled')
		// publish on facebook
		fbpost = $('#fbpublish').attr('checked')
		if (fbpost == true){
			caption = $('#infodiv').attr('image_caption');
			this_url = window.location.href;
			thumb = 'http://'+ window.location.host + $('#infodiv').attr('fbthumb');
			user_message = 'commented on friends-of-art.net'
			attachment = {
			'name': caption, 
			'href': this_url,
			'caption': '',
			'description': data.comment,
			'media': [{ 'type': 'image', 'src': thumb, 'href': this_url}]
				};
			publish_to_facebook(user_message, attachment)
		} else {
			void(0)
		}
		}, "json");
	});
});

function fbcallback (post_id, exception) {
	void(0)
	//alert('publish_stream exception: ' + exception)
}

function publish_to_facebook(user_message, attachment){
	//alert('checking permissions')
	umessage = user_message
	attachm = attachment
	FB.Facebook.apiClient.users_hasAppPermission("publish_stream",
		function(result, exception){
			if (result == 0){
				//alert('permissions have not yet been granted')
				FB.Connect.showPermissionDialog("publish_stream", function(perms){
				//alert('i asked for permissions and got:' + perms)
				if (perms === 'publish_stream'){
					//alert('got what i wanted')
					// post silently...
					FB.Connect.streamPublish(umessage, attachm, null, null, null, fbcallback, true, null)
					} else {
					//alert('the fucker did not grant it')
					//post with prompt
					FB.Connect.streamPublish(umessage, attachm, null, null, null, fbcallback, false, null)
					}
				});
				} else{
				//alert('permission already granted, publishing the hard way...')
				FB.Connect.streamPublish(umessage, attachm, null, null, null, fbcallback, true, null)
				}
				});
}

////////////////////
// comment voting //
////////////////////


$(document).ready(function(){
	$('.commentvote').click(function(){
		type = $(this).attr('votetype')
		commentid = $(this).attr('commentid')
		artid = $(this).attr('artid')
		lang = $(this).attr('lc')
		$.post('/'+lang+'/commentvote/', {
			commentid: commentid,
			type: type,
			artid: artid,
			lang: lang
		},
		function(data) {
			if (data.status == 'success'){
				$('#score'+data.commentid).html(data.new_score)
				// replace buttons
				$('.commentvote'+data.commentid).each(function() { $(this).attr('src', $(this).attr('src').replace('.png','-inactive.png')).attr('title', 'thanks for voting').unbind('click');  });
				}
			else{
				//old_score = $('#score'+data.commentid).html()
				//id = data.commentid
				//$('#score'+data.commentid).html(data.message) // make this a hidden div to allow for easy translation
				//setTimeout ("$('#score'+id).html(old_score)",1000)
			} // add a case for server error, add a case for voting on own comment
		}, "json");
	});
});



$(document).ready(function(){
	$('.detailvote').click(function(){
		type = $(this).attr('votetype') 
		detailid = $(this).attr('detailid')
		artid = $(this).attr('artid')
		lang = $(this).attr('lc')
		$.post('/'+lang+'/detailvote/', {
			detailid: detailid,
			type: type,
			artid: artid,
			lang: lang
		},
		function(data) {
			//console.log(data)
			if (data.status == 'success'){
				$('#detailscore'+data.detailid).html(data.new_score)
				//console.log(detailid)
				// replace arrows
				$('.detailvote'+data.detailid).each(function() { $(this).attr('src', $(this).attr('src').replace('.png','-inactive.png')).attr('title', 'thanks for voting').removeClass('detailvote').unbind('click');  });
				
			}
			else{
				//alert('no no..')
				//old_score = $('#detailscore'+data.detailid).html()
				//id = data.detailid
				//$('#detailscore'+data.detailid).html(data.message) // make this a hidden div to allow for easy translation
				//setTimeout ("$('#detailscore'+id).html(old_score)",1000)
			}
		}, 'json');
	});
});

// responsible for styling the movement timeline
$(document).ready(function(){
	$('.movementbar').each(function(){
		$(this).css({'background-color': '#0066CC'})
		var start = $(this).attr('start')
		var end = $(this).attr('end')
		var width = (end - start) * 0.6 
		var margin = (start - 1300) * 0.6
		$(this).css({'width': width+'px'})
		$(this).css({'margin-left': margin+'px'})
	});
  });
  
 // change profile picture
 
 
$(document).ready(function(){
	$('.defaultpic').click(function(){
		number = $(this).attr('number')
		src = $(this).attr('src')
		$('#placeholderimg').attr({ 'src': src, 'number':number })
		$('#placeholderimg').show()
		$('#currentimg').hide()
		$('#id_use_default_picture').val("True")
		$('#id_default_picture').val(number)
	});
	$('#facebookpic').click(function(){
		src = $(this).attr('src')
		$('#placeholderimg').attr({ 'src': src })
		$('#placeholderimg').show()
		$('#currentimg').hide()
		$('#id_use_default_picture').val("False")
	});
});

$(document).ready(function(){
	$('.profileimageitem').click(function(){
	$('.profileimageitem').css('border-color', 'white')
	$(this).css('border-color', 'rgb(195,214,155)')
	});
	//$('#savesuccess').fadeOut()
	setTimeout(function(){ $('#savesuccess').slideUp() }, 5000);
});

// edit profile information
$(document).ready(function(){
	$('#editbutton').click(function(){
		$('.staticfield').hide();
		$('.editfield').show();
		$(this).hide()
		$('.savecancelprofile').show();
		$('#defaultpictures').slideDown(100)
	});
	$('#cancelprofilebutton').click(function(){
		$('.profileimageitem').css('border-color', 'white')
		$('#editbutton').show()
		$('.staticfield').show();
		$('.editfield').hide();
		$('.savecancelprofile').hide();
		$('#defaultpictures').slideUp(100)
		$('#placeholderimg').hide()
		$('#currentimg').show()
		old = $('#currentimg').attr('number')
		$('#id_default_picture').val(old)
	});
});

// admins //

$(document).ready(function(){
	$('.killcomment').click(function(){
		var x=window.confirm("u sure?");
		//alert(x);
		if (x)
		//alert('ok then...')
			comment = $(this).attr('comment')
			alert(comment)
			$.post('/en/killcomment/', {
				comment: comment
				}, function(data){
					alert(data.status)
					}, 'json');
		//else
		//alert('fucker!')
	});
});

$(document).ready(function(){
	$('.killdetail').click(function(){
		var x=window.confirm("u sure?");
		//alert(x);
		if (x)
		//alert('ok then...')
			detail = $(this).attr('detail')
			//alert(detail)
			$.post('/en/killdetail/', {
				detail: detail
				}, function(data){
					alert(data.status)
					}, 'json');
		//else
		//alert('fucker!')
	});
});

