var	usedIngr = Array();
var receiptsOnPage = 10;
var currentPage=1;
var sstr, Ba;

function setCookie(vars) {
	today  = new Date();
	ddate = new Date(today.getTime() + 63072000000);
	document.cookie = vars + "; expires=" + ddate.toGMTString()+"; path=/";
}

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);
	}
}

function setStrict() {
	if ($('#strictSearch').attr('checked')) {
		$("#macros").hide();
		$.each( $("#ingrList li"), function() {
			$("#"+this.id).removeClass("dis");
			$("#ingredient-sw-"+this.id).removeClass('excluded');
		});
	} else {
		$("#macros").show();
	}
	refreshListQuery();
}

function displaySW(subj,item) {
	if ($("#"+subj+'-sw-'+item).hasClass('active')) {
		$("#"+subj+'-sw-'+item).removeClass('active excluded');
		$("#"+subj+'-sw-'+item).addClass('inactive');
	} else {
		$("#"+subj+'-sw-'+item).addClass('active');
		$("#"+subj+'-sw-'+item).removeClass('excluded inactive');
	}
}
function displayExclude(item) {
	if ($("#ingredient"+'-sw-'+item).hasClass('excluded')) {
		$("#ingredient-sw-"+item).removeClass('excluded active');
		$("#ingredient-sw-"+item).addClass('inactive');
	} else {
		$("#ingredient-sw-"+item).addClass('excluded');
		$("#ingredient-sw-"+item).removeClass('inactive active');
	}
}
function switchMe(subj,item) {
	currentPage = 1;
	displaySW(subj,item);
	refreshListQuery();
}
function exclude(item) {
	currentPage = 1;
	displayExclude(item);
	refreshListQuery();
}

function excludeGroup(group) {
	$.each($("#ingrList li"), function() {
		if($('#ingredient-sw-'+this.id).hasClass("group-"+group)) { displayExclude(this.id) }
	});
	refreshListQuery();
}


function cleanIngr() {
	$.each( $("#ingrList li"), function() {
		$("#ingredient-sw-"+this.id).removeClass("excluded");
		$("#ingredient-sw-"+this.id).removeClass("active");
		$("#ingredient-sw-"+this.id).addClass("inactive");
	});
	refreshListQuery();
}

function refreshIngrs(query) {
	var filters = query.split('&');
	$.each(filters, function() {
		kv = this.split('=');
		values = kv[1].split(',');
		if (values.length>0) {
			$.each(values, function() {
				if (this.length>0) {
					if (kv[0]=='types') {
						$('#type-sw-'+this).removeClass("inactive");
						$('#type-sw-'+this).addClass("active");
					}
					if (kv[0]=='ingr') {
						$('#ingredient-sw-'+this).removeClass("inactive");
						$('#ingredient-sw-'+this).addClass("active");
					}
					if (kv[0]=='exclude') {
						$('#ingredient-sw-'+this).removeClass("inactive");
						$('#ingredient-sw-'+this).removeClass("active");
						$('#ingredient-sw-'+this).addClass("excluded");
					}
					if (kv[0]=='page') {
						currentPage = kv[1];
					}
					if (kv[0]=='strictSearch') {
						$('#strictSearch').attr("checked", "checked");
					}
				}
			}
			)

		}
	});
	hG = readCookie("hiddenGroups");
	if (hG) {
		hG = hG.split(',');
		$.each(hG, function() {
			$("#igswс-"+this).hide();
			$("#igswo-"+this).show();
			$("#ig-"+this).hide();
		});
	}
}


function refreshListQuery() {
	if (!firstRun) {
		var query = 'types=';
		allTypes = document.getElementById('typeList').childNodes;
		for (loop=0; loop<allTypes.length; loop++) {
			if(document.getElementById('type-sw-'+allTypes[loop].id).className=='active') {query=query+allTypes[loop].id+',' };
		}
		query=query+'&ingr='
		excludedList = 'exclude=';
		$.each($("#ingrList li"), function() {
			if($('#ingredient-sw-'+this.id).hasClass('active')) {query=query+this.id+','; };
			if($('#ingredient-sw-'+this.id).hasClass('excluded')) {excludedList=excludedList+this.id+','};
		});
		query = query+'&'+excludedList;
		query = query+'&page='+currentPage;
		if ($('#strictSearch').attr('checked')) {
			query = query+'&strictSearch=yes';
		}
		/* if ($('#maleSearch').attr('checked')) {
		query = query+'&maleSearch=yes';
		} */
		setCookie("search="+query+"");
	} else {
		query = readCookie('search');
		if (query) {
			refreshIngrs(query);
		} else {
			query = 'types=&ingr=&exclude=&page=1';
		}
		firstRun = false;
	}
	$("#foodContent").html('Загрузка...');
	$("#pager").html('');
	//$('#query').html(query);
	$.post( '/ajax/recipes-list/', query, function (data, textStatus) { displayResults(data)}, 'json' );
}

function gotoPage(numberOfPage) {
	currentPage = numberOfPage;
	refreshListQuery();
}

function showReceipt(rid) {
	$.post( '/ajax/print-recipe/', 'rid='+rid, function (data, textStatus) { $("#foodContent").html(data)}, 'html' );
}

function updateGr() {
	$.each($(".ingrGroupSw"), function () {
		display=false;
		grID = this.id;
		ids=this.id.split('-');
		$.each($(".group-"+ids[1]), function () {
			idd=this.id.split('-sw-');
			if (!$("#"+idd[1]).hasClass("dis")) {
			 display=true;
			}
		});
		if (!display) {
		 $("#"+grID).hide();	
		} else {
		 $("#"+grID).show();	
		}
	});
}

function displayResults(data) {
	if (data.receipts.length==0) {$("#foodContent").html('В нашей базе нет блюд с таким набором ингредиентов, попробуйте выбрать другие продукты'); $("#receiptsNum").html('Всего рецептов: ')} else {
		$("#foodContent").html('');
		$("#pager").html('');
		if ($('#totalReceipts').text()!=data.selectedReceipts) {
			$("#receiptsNum").html('Показано рецептов: <span id="selectedReceipts">'+data.selectedReceipts+'</span> из');
		} else {
			$("#receiptsNum").html('Всего рецептов: ');
		}

		$.each(data.receipts, function () {
			curentRecCont = "receipt-"+this.id;
			$('<div id="'+curentRecCont+'" class="receiptInList invisible">').appendTo("#foodContent");
			if (this.image!='blank') {
				var hrefFix = (instance!='post') ? 'http://prosto-post.ru' : '';
				$("#"+curentRecCont).append('<p class="img"><img src="'+hrefFix+'/pictures/receipts/thumb/'+this.image+'.jpg"></p>');
			}
			$("#"+curentRecCont).append('<div class="receiptInfoCont" id="'+curentRecCont+'Info"></div>');
			if (this.image!='blank') {
				$("#"+curentRecCont).addClass('wimg');
			}
			hrefFix = (instance=='post') ? 'recipes/' : '';
			$("#"+curentRecCont+'Info').append('<h2><a href="/'+hrefFix+this.id+'/">'+this.title+'</a></h2>');
			$("#"+curentRecCont+'Info').append('<p class="receiptDigest">'+this.text+'</p>');
			$("#"+curentRecCont+'Info').append('<p  id="'+curentRecCont+'Ingrs"></p>');
			if(this.ingrs) {
				$.each(this.ingrs, function () {
					$("#"+curentRecCont+'Ingrs').append('<span>'+$("#ingredient-sw-"+this).text()+'</span> ');
				});
			}
			$('#'+curentRecCont).fadeIn("slow");
		});

		if (!$('#strictSearch').attr('checked')) {
			$.each($("#ingrList li"), function () {
				check = this.id;
				found = false;
				$.each(data.availableIngr, function() { if (this==check) {found=true}});
				if (!found) {
					if (!$("#ingredient-sw-"+this.id).hasClass('excluded')) {
						$("#"+this.id).addClass("dis");
					}
				} else {
					$("#"+this.id).removeClass("dis");
				}
			});
		} else {
		}
	}

	if ($('#strictSearch').attr('checked')) {
		$.each( $("#ingrList li"), function() {
			$("#"+this.id).removeClass("dis");
		});
	}
	
	updateGr();

	var actives = Array();
	var excludes = Array();
	$.each($("#ingrList li"), function () {
		if ($("#ingredient-sw-"+this.id).hasClass('active')) {
			actives.push('<span>'+$("#ingredient-sw-"+this.id).html()+'</span>');
		}
		if ($("#ingredient-sw-"+this.id).hasClass('excluded')) {
			excludes.push('<span>'+$("#ingredient-sw-"+this.id).html()+'</span>');
		}
	});


	if ((actives.length>0) || (excludes.length>0)) {
		$("#yourChoice").html('Ваш запрос: ');
		if (actives.length>0) {
			actives = actives.join(', ');
			if ($('#strictSearch').attr('checked')) {
				strictWord = ' <strong>только</strong>';
			} else {
				strictWord = '';
			}
			$("#yourChoice").append('<span id="actives">блюда, содержащие'+strictWord+': '+actives+'</span>. ');
		}
		if (excludes.length>0) {
			excludes = excludes.join(', ');
			$("#yourChoice").append('<span id="excludes">Исключить: '+excludes+'</span>');
		}
	} else {
		$("#yourChoice").html('');
	}

	//pager

	if (data.selectedReceipts>receiptsOnPage) {
		numberOfPages = (data.selectedReceipts/receiptsOnPage)+1;
		for (i=1; i<numberOfPages; i++) {
			if (i<11) {
				$("#pager").append('<p id="page'+i+'"></p>');
				if (currentPage!=i) {
					$("#page"+i).append('<a href="/recipes/page'+i+'/" onClick="gotoPage('+i+'); return false;">'+i+'</a>');
				} else {
					$("#page"+i).append(''+i+'');
				}
			}
		}
		if (numberOfPages>10) {
			$("#pager").append('<p>...</p>');
		}
	}

	if (!$('#strictSearch').attr('checked')) {
		$('#ingrList img.remover').removeClass('invisible');
	} else {
		$('#ingrList img.remover').addClass('invisible');
	}

	//$("#time").html(data.time);
}

function setGrCookie(nowgroup) {
	var groups = new Array();
	$.each($(".ingrGroup"), function () {
		if ($("#"+this.id).css('display')=='none') {
			ids=this.id.split('-');
			groups.push(ids[1]);
		}
	});
	if (nowgroup) {
		groups.push(nowgroup);
	}
	gc = groups.join(',');
	setCookie("hiddenGroups="+gc+"");
}

function switchGroup(group) {
	if ($("#ig-"+group).css('display')=='block') {
		$("#igswс-"+group).hide();
		$("#igswo-"+group).show();
		$("#ig-"+group).hide("slow");
	} else {
		$("#igswс-"+group).show();
		$("#igswo-"+group).hide();
		$("#ig-"+group).show("slow");
	}
	setGrCookie(group);
}

function switchGroupAll(mode) {
	$.each($(".ingrGroup"), function () {
		ids=this.id.split('-');
		ids=ids[1];
		if (mode=="off") {
			$("#igswс-"+ids).hide();
			$("#igswo-"+ids).show();
			$("#ig-"+ids).hide();
		} else {
			$("#igswс-"+ids).show();
			$("#igswo-"+ids).hide();
			$("#ig-"+ids).show();
		}
	});
	setGrCookie("");
}

function windowSize()
{
	var h = 0;
	if(!window.innerWidth)
	{
		if(!(document.documentElement.clientWidth == 0)) {
			h = document.documentElement.clientHeight;
		}
		else {
			h = document.body.clientHeight;
		}
	}
	else {
		h = window.innerHeight;
	}
	return h;
}


searchLoop=function() {
	sstr = se.value
	if(Ba!=sstr) {
		if (sstr.length>0) {
			$(".ingrGroupSw").hide();
			$(".ingrGroup").show();
			$.each($("#ingrList li"), function() {
				if($('#ingredient-sw-'+this.id).text().substring(0,sstr.length).toUpperCase()==sstr.toUpperCase()) {
					$('#'+this.id).show();
				} else {
					$('#'+this.id).hide();
				}
			});
		} else {
			$(".ingrGroupSw").show();
			$("#ingrList li").show();
			hG = readCookie("hiddenGroups");
			if (hG) {
				hG = hG.split(',');
				$.each(hG, function() {
					$("#igswс-"+this).hide();
					$("#igswo-"+this).show();
					$("#ig-"+this).hide();
				});
			}
		}
	}
	Ba=sstr;
	setTimeout("searchLoop()", 100);
	return true
}

function initSearch() {
	se = document.getElementById("ingrSearch");
	setTimeout("searchLoop()",10);
}

function fixSearchPanelSize() {
	$("#foodIngrList").css('height', windowSize()-350);	
	setTimeout("fixSearchPanelSize()",1000);
}