var reportRecipeCommentId = 0;
//var topRatedPage = 0;
$(document).ready(function(){
	
	try{
		equalRecipesCatAndSearch();
	}catch(e){
		
	}
	
	$('.lightbox').lightBox();
	$('#equalize').equalHeights();
	$('a.recipe-file-help').click(function(){
		$('.popup-recipe-file-help').show();
		return false;
	})
	$('.popup-file-help-hide').click(function(){
		$('.popup-recipe-file-help').hide();
		return false;
	})
	
	$('#search-recipe-input').focus(function(){
		if( this.value == "enter text" ) this.value = "";
	})
	$('#search-recipe-input').blur(function(){
		if( this.value == "" ) this.value = "enter text";
	})
	
	$('.submit-search-recipe-form').one('click', function(){
		$('#search-recipe').submit();
		return false;
	})
	
//	var inProgress = 0;
	function nextTopRated() {
		if( !$('ul.recipe-list li.page'+(topRatedPage+1)).get(0) ) return false;
		$('.next-page-top-rated').unbind('click');
		$('.next-page-top-rated').bind('click', noop);
		var tmpInd =  topRatedPage;
		try {
			var all = parseInt($('#allrec').text());
			var curr = parseInt( $('#srec').text() );
			var end = parseInt( $('#erec').text() );
			end = end + 3;
			if( end > all ) end = all;
			curr = curr + 3;
			$('#srec').text(curr);
			$('#erec').text(end);
		}catch(e){
//			console.log(e);
		}
		$('ul.recipe-list li.page'+topRatedPage).fadeOut('slow', function(){ 			 
			$('ul.recipe-list li.page'+(tmpInd+1)).fadeIn('slow');
			$('.next-page-top-rated').unbind('click');
			$('.next-page-top-rated').bind('click', nextTopRated);
			
		});
		topRatedPage++;
		return false;
	}
	function prevTopRated() {
		if( !$('ul.recipe-list li.page'+(topRatedPage-1)).get(0) ) return false;
		$('.prev-page-top-rated').unbind('click');
		$('.prev-page-top-rated').bind('click', noop);
		var tmpInd =  topRatedPage;
		try {
			var all = parseInt($('#allrec').text());
			var curr = parseInt( $('#srec').text() );
			console.log(curr);
			var end = parseInt( $('#erec').text() );
			curr = curr - 3;
			if(curr < 1) curr = 1;
			end = curr + 2;
			if( end > all ) end = all;
			$('#srec').text(curr);
			$('#erec').text(end);
		}catch(e){
			console.log(e);
		}
		$('ul.recipe-list li.page'+topRatedPage).fadeOut('slow', function(){
			$('ul.recipe-list li.page'+(tmpInd-1)).fadeIn('slow');
			$('.prev-page-top-rated').unbind('click');
			$('.prev-page-top-rated').bind('click', prevTopRated); 
		});
		topRatedPage--;
		return false;	
	}
	function noop() {
		return false;
	}
	$('.next-page-top-rated').bind('click', nextTopRated);
	$('.prev-page-top-rated').bind('click', prevTopRated);
	
//	$('.next-page-top-rated').click(function(){
//		$('.next-page-top-rated').unbind('click');
//		
//	})
//	$('.prev-page-top-rated').click(function(){
//
//	})
	
	$('.recipes-tags-box-show-all').click(function(){
		var tmpS, tmpE;
		tmpS = $('div.right p.list').height();
//		console.log(tmpS);
		$('.all-tags').removeClass('hidden');
		$('.recipes-tags-box-show-all').addClass('hidden');
		$('.recipes-tags-box-hide-all').removeClass('hidden');
		
		tmpE = $('div.right p.list').height();
		return false;
		if( !$.browser.safari ) return false;
//		tmpS = tmpS + 20;
		try{
			$('div.right').height( $('div.right').height() + ( tmpE - tmpS ) );
		} catch(e){
			console.log(e);
		}
		return false;
	})
	$('.recipes-tags-box-hide-all').click(function(){
		var tmpS, tmpE;
		tmpS = $('div.right p.list').height();
		
		$('.all-tags').addClass('hidden');
		$('.recipes-tags-box-hide-all').addClass('hidden');
		$('.recipes-tags-box-show-all').removeClass('hidden');
		
		tmpE = $('div.right p.list').height();
		
		return false;
		if( !$.browser.safari ) return false;
//		tmpS = tmpS - 20;
		try{
			$('div.right').height( $('div.right').height() - ( tmpS - tmpE ) );
		} catch(e){
			console.log(e);
		}
		return false;
	})
	$('.contributors-box-show-all').click(function(){
		$('.all-contributors').removeClass('hidden');
		$('.contributors-box-show-all').addClass('hidden');
		$('.contributors-box-hide-all').removeClass('hidden');
		return false;
	})
	$('.contributors-box-hide-all').click(function(){
		$('.all-contributors').addClass('hidden');
		$('.contributors-box-hide-all').addClass('hidden');
		$('.contributors-box-show-all').removeClass('hidden');
		return false;
	})
	
	$('.submit-post-edit-comment').click(function(){
		var id = $(this).parents('div:first').get(0).className.replace(/\D*/, '');
//		console.log(id);
		var commentT = $('.u-comment', $(this).parents('div:first'));
//		console.log( commentT.val() );
//		console.log($('div#recipe-comment-'+id+' p span:last').text());
//		return false;
		$.ajax({
			type: "POST",
			url: ajUrl,
			dataType: "json",
			data: {"recipe_id": recipeId, "comment": commentT.val(), 'action': "client_ucomment", 'comment_id': id},
			success: function(data){
//				console.log( data[0]["status"] );
				if( data[0]["status"] == 'error' ) {
					alert(data[0]["error"]);
					return;
				}
				$('div#recipe-comment-'+data[0]['comment_id']+' p span:last').html(data[0]['comment']);
				$('.edit-comment-div.commentnum'+data[0]['comment_id']).addClass('hidden');
				$('.view-comment-div.commentnum'+data[0]['comment_id']).removeClass('hidden');
			}
		});
		return false;
	})
	
	$('.submit-recipe-comment-form').click(function(){
		var frm = $(this).parents('form.recipe-comment-form:first');
		var commentT = $('#information', frm);
		if( commentT.val().length > 3 ) {
			$('.submit-recipe-comment-form').unbind('click');
			frm.submit();
			return false;
		} else {
			commentT.addClass('error');
			return false;	
		}
//		$('.submit-recipe-comment-form').unbind('click');
//		console.log(commentT.val());
		$.ajax({
			type: "POST",
			url: ajUrl,
			dataType: "json",
			data: {"recipe_id": recipeId, "comment": commentT.val(), 'action': "client_comment"},
			success: function(data){
				commentT.val("");
				var div = $('.recipe-all-comments');
				if( data[0]["status"] == 'error' ) {
					alert(data[0]["error"]);
					return;
				}
				var div1 = $.DIV({Class: "recipe-author-box", id: "recipe-comment-"+data[0].comment_id });
				var div2 = $.DIV();
				div.append(div2);
				$(div2).append(div1);
				var span1 = $.SPAN({Class: "recipe-author-info"},
								$.SPAN({Class: "recipe-author-image"},
									$.IMG({src: data[0]["member"].picture})
								),
								$.A({href: "/users/"+data[0]["member"].username, title: data[0]["member"].name}, data[0]["member"].name),
								data[0]["posted_at"]
				);
				$(div1).append(span1);
				var p1 = $.P({},
					$.SPAN({Class: 'actions' }," helpful " ,
						$.IMG({src: "/share/images/site/report-x.gif", alt: "", Class: "rate-minus"})," ",
						$.IMG({src: "/share/images/site/report-check.gif", alt: "", Class: "rate-plus"}),
						" | ",
						$.A({href: "#", title: "report", Class: "invert report" }, " report ")
					),
					$.IMG({src: "/share/images/site/ratings/sm-rating-0-0.gif", Class: 'rating raging-stars small-stars'}),
					$.IMG({src: "/share/images/site/ratings/sm-rating-0-0.gif", Class: 'rating raging-stars small-stars-tmp hidden'}),					
					$.BR(),
					$.BR(),
					data[0].comment
				);
				$(div1).append(p1);
				$('.rate-minus, .rate-plus').css('cursor', 'pointer');
				if( isLoggedIn ) {
					$('img.rating.raging-stars.small-stars', $(div1)).bind("mouseover", Ratings.mouseOverOnSmallStandartStars);
					$('img.rating.raging-stars.small-stars-tmp', $(div1)).bind("mouseout", Ratings.mouseOutOnSmallTmpStars);
					$('img.rating.raging-stars.small-stars-tmp', $(div1)).bind("mousemove", Ratings.mouseMoveOnSmallTmpStars);
					$('img.rating.raging-stars.small-stars-tmp', $(div1)).bind("click", Ratings.mouseClickOnSmallTmpStars);
				}
				
				$('.rate-minus').click(function(){
					rateComment(this, 1);
					return false;
				})
				$('.rate-plus').click(function(){
					rateComment(this, 5);
					return false;
				})
			}	
		});
		return false; 
	})
//	$('img.rating.raging-stars.big-stars').bind("mouseover", Ratings.mouseOverOnBigStandartStars);
//	$('img.rating.raging-stars.big-stars-tmp').bind("mouseout", Ratings.mouseOutOnBigTmpStars);
//	$('img.rating.raging-stars.big-stars-tmp').bind("mousemove", Ratings.mouseMoveOnBigTmpStars);
//	$('img.rating.raging-stars.big-stars-tmp').bind("click", Ratings.mouseClickOnBigTmpStars);
	if( isLoggedIn ) {
		$('a.rating.raging-stars.big-stars').bind("mouseover", Ratings.mouseOverOnBigStandartStars);
		$('a.rating.raging-stars.big-stars').bind("mouseout", Ratings.mouseOutOnBigTmpStars);
		$('a.rating.raging-stars.big-stars').bind("mousemove", Ratings.mouseMoveOnBigTmpStars);
		$('a.rating.raging-stars.big-stars').bind("click", Ratings.mouseClickOnBigTmpStars);
		
//		$('img.rating.raging-stars.small-stars').bind("mouseover", Ratings.mouseOverOnSmallStandartStars);
//		$('img.rating.raging-stars.small-stars-tmp').bind("mouseout", Ratings.mouseOutOnSmallTmpStars);
//		$('img.rating.raging-stars.small-stars-tmp').bind("mousemove", Ratings.mouseMoveOnSmallTmpStars);
//		$('img.rating.raging-stars.small-stars-tmp').bind("click", Ratings.mouseClickOnSmallTmpStars);
	}
	$('.rate-minus').click(function(){
		rateComment(this, 1);
//		var id = $(this).parents('.recipe-author-box:first').get(0).id.replace('recipe-comment-', '');
//		console.log(id);
		return false;
	})
	$('.rate-plus').click(function(){
		rateComment(this, 2);
		return false;
	})
	
	$('.submit-recipe-form').click(function(){
		if( $(this).get(0).className.indexOf('savedraft') >= 0 ) $('input#member_status').val('draft');
		else $('input#member_status').val('publishedd');
		
		var ret = true;
		if( $('#new-recipe input#r-title').get(0).value == "" || $('#new-recipe input#r-title').get(0).value == null ) {
			 ret = false;
			 $('#new-recipe input#r-title').addClass('error');
		} else {
			$('#new-recipe input#r-title').removeClass('error');
		}
		if( ret ) {
			
//			doSubmit();
			try {
				if( $('#txtFileName').get(0).value != "" ) {
					ieHackPositionPopups();
					$('#progress-upload').removeClass('hidden');
					$('.background-darken').show();
					$('.progress-profile').show();
					swfu.startUpload();
				} else {
					$('form#new-recipe').submit();
				}
			} catch (ex) {
//				alert('error');
			}
//			$('form#new-recipe').submit();
			
//			setTimeout("getProgressUpload()", 100);
			return false;	
		}
		
		return ret;
	})

	
	
	
	$('.add-new-tag').click(function(){
		var modeId = $('.add_new_tag_name').attr('tmp_id');
		var modeName = $('.add_new_tag_name').get(0).value;
		if( modeName.length <= 0 ) return false;
		if( modeId == 0 ) {
			$.post(webroot + 'recipes', { title: modeName, slug: slugify(modeName), desc: " ", status: "active", action: "insert_tag" }, function(data){
//				console.log(parseInt);
				appendTags(parseInt(data), modeName);
			});
			return false;
		} else {
			appendTags(modeId, modeName);
			return false;
		}
		
		
	})
	
	$('.remove-recipe-tag').click(function(){
		$(this).parents('span:first').remove();
	})
	
	$('.edit-comment').click(function(){
		var id = $(this).get(0).className.replace(/\D*/, '');
		
		$('.edit-comment-div.commentnum'+id).removeClass('hidden');
		$('.view-comment-div.commentnum'+id).addClass('hidden');
		return false;
	})
	$('.submit-post-edit-comment-hide').click(function(){
		var id = $(this).get(0).className.replace(/\D*/, '');
		
		$('.edit-comment-div.commentnum'+id).addClass('hidden');
		$('.view-comment-div.commentnum'+id).removeClass('hidden');
		return false;
	})
	
	
	
	
})

function appendTags(modeId, modeName){

	var dd = $('span.current_tags span:first');

	var span = $.SPAN({id: ("rcat-tag-"+modeId) }, 
			$.SPAN({}, modeName),
			$.IMG({ Class: 'remove-recipe-tag', "src": '/share/images/site/deltags.gif'}),
			$.INPUT({ "type": "hidden", "name": "sel_cats[]", "value": modeId})
	);  

	dd.append(span);

	$(span).css('font-size', '14px');

	$(span).css('margin', '0px 10px 0px 0px');

	$(span).css('display', 'block');

	$(span).css('float', 'left');

	$('span', span).css('float', 'left');

	$('img', span).css('float', 'left');

	$('img', span).css('margin', '4px 8px 0px 3px');

	$('img', span).css('cursor', 'pointer');

	
	$('img', span).click(function(){
		$(this).parents('span:first').remove();
	})

	$('.add_new_tag_name').val("");

	$('.add_new_tag_name').attr("tmp_id", "0");

	return true;
}


function formatItemRe(row) {
	
	var parts = row[0].split('{|}');
//	return parts[0] + " (id: " + parts[1] + ")";
	return parts[0];
}


function selectItemRe(li) {
//	console.log(li);
//	console.log('select');
	findValue(li);
}


function findValueRe(li) {
//	console.log("find value");
//	if( li == null ) return alert("No match!");
//	if( li == null ) $('.add_new_tag_but').show();
//	else $('.add_new_tag_but').hide();
	
	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;
	
//	alert("The value you selected was: " + sValue);
}

function lookupLocalRe(){
	var oSuggest = $("input.add_new_tag_name")[0].autocompleter;

	oSuggest.findValue();

	return false;
}


function getProgressUpload(){
	$.get("/recipes/upload_stat/progress_key:"+$('#progress_key').get(0).value  ,function(percent){
		percent = parseInt(percent);
		$('#progress-upload').html(percent+" %");
		if( percent < 100 ) {
			setTimeout("getProgressUpload()", 100);
		}
	})
}

function rateComment(object, rate){
	
	var id = $(object).parents('.recipe-author-box:first').get(0)
			?$(object).parents('.recipe-author-box:first').get(0).id.replace('recipe-comment-', '')
			:"0";
	var type = $(object).parents('div:first').get(0).className == 'recipe'
				?'recipe':'comment';
			

	$.ajax({
			type: "POST",
			url: ajUrl,
			dataType: "json",
			data: {"recipe_id": recipeId, "comment_id": id, 'action': "rate", 'type': type, 'rate': rate},
			success: function(data){
				if( data["status"] == 'error' ) {
					alert(data["error"]);
					if( data["comment_id"] > 0 ) {
						
					} else {
						var img = $('a.rating.raging-stars.big-stars', $('div.video'));
						var tmp = $(img).get(0).title.split('-');
						img.css('background-position', '0px '+( 220 - ( tmp[0]*2 + parseInt(tmp[1]) )*20 )+'px');
					}
					return;
				}
				if( data["comment_id"] > 0 ) {
					switch( data['avgr'] ) {
						case "1":
//							console.log(1);
							$('img.rate-minus', $('#recipe-comment-'+data["comment_id"]) ).get(0).src = "/share/images/site/report-x-gr.gif";
							break;
						 case "2":
//						 	console.log(1);
						 	$('img.rate-plus', $('#recipe-comment-'+data["comment_id"]) ).get(0).src = "/share/images/site/report-check-gr.gif";
						 	break;
					}
//					console.log(data['avgr']);
//					var img = $('img.rating.raging-stars', $('#recipe-comment-'+data["comment_id"]));
//					img.get(0).src = "/share/images/site/ratings/sm-rating-"+data["calc_avg"]+".gif";
				} else {
					var img = $('a.rating.raging-stars.big-stars', $('div.video'));
					var tmp = data['calc_avg'].split('-');
					img.css('background-position', '0px '+( 220 - ( tmp[0]*2 + tmp[1]/5 )*20 )+'px');
//					img.get(0).src = "/share/images/site/ratings/b-rating-"+data["calc_avg"]+".gif";
				}
			}
	});
	

	
}