var outputFormat = "json";

$(document).ready(function() {
	initSearchBoxes();
})

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

function initSearchBoxes(){
	
	$("#searchSuggestions").hide(0);
	
	$(".searchForm").each(
		function(){
			
			sDiv = this;
			sf = $('#'+this.id+' .searchField');
			
			sf.keyup(
				function(){
					
					currentSdiv = $(this).parent().parent();
					term = $(this).val();
					
					if(term.length > 0){
						searchFor(term);
					}else{
						$("#searchSuggestions").empty();
					}
				}
			)
			
			sf.blur(
				function(){
					$("#searchSuggestions").fadeOut("50");
				}
			)
		}
	)
}

function searchFor(term){
	
	$.post(
			API_URL+"auto_suggest_api.php", 
			{searchterm:term},
			searchCallback
			);
}

function searchCallback(data){
	
	if(data.matches == undefined) data = JSON.parse(data);
	
	if(data.error != undefined) return;
	
	onlyRecipes = $("#"+currentSdiv.attr("id")+" #onlyRecipes").val();
	
	str = '<ul>';
	for(i=0; (i<data.matches.length && i<5); i++){
		m = data.matches[i].match;
		str += '<li><a href="'+ABSOLUTE_PATH+'recipes/?q='+m+'&onlyRecipes='+onlyRecipes+'">'+m+'</a></li>';
	}
	str += '</ul>';
	
	$("#searchSuggestions").empty();
	$("#searchSuggestions").html(str);
	$("#searchSuggestions").fadeIn("50");
	
	sf = $("#"+currentSdiv.attr("id")+" .searchField");
	os = sf.offset();
	if(currentSdiv.attr("id") == "searchBoxFooter"){
		os.top -= $("#searchSuggestions ul").height();
	}else{
		os.top += sf.height() + 2;
	}
	
	$("#searchSuggestions").css("left", os.left+"px");
	$("#searchSuggestions").css("top", os.top+"px");
	
}

showingProduct = false;
showingBrand = false;
showingShare = false;
showingRecipe = false;
var recipeImageTimeout;

function showProduct(id){
	
	if(showingProduct == true) return;
	
	hideBrand();
	
	$('#productPopup').hide();
	
	if (products[id]['brand'] != "") {	
		brand = products[id]['brand'].toUpperCase();
	}else{
		brand = "";
	}
	
	$('#popUpName').html(brand+"<br/>"+products[id]['name']);
	$('#popUpImage').html('<img src="'+products[id]['image']+'" alt="'+products[id]['name']+'" '+products[id]['dimensions']+' border="0" />');
	$('#popUpDetails').html('<p>'+products[id]['details']+'</p>');
	
	startStr = "";
	avail = startStr;
	if(products[id]['availability']['coles'] == "Y") avail += " Coles";
	
	if (products[id]['availability']['woolworths'] == "Y") {
		if(avail != startStr) avail += ", ";
		avail += " Woolworths";
	}
	
	if (products[id]['availability']['major'] == "Y") {
		if(avail != startStr) avail += " & ";
		avail += " Major Independent Stores";
	}
	
	if(avail != startStr) avail = "Available at "+avail;
	$('#popUpAvailability').html('<p>'+avail+'</p>');
	
	
	if (products[id]['link'] != "") {
		$('#popUpLink').html('<a href="' + products[id]['link'] + '" target="_blank">find out more</a>');
	}else{
		$('#popUpLink').html('');
	}
	
	$('#productPopup').fadeIn(300);
	$('#productPopup').center();
	
	showingProduct = true;
}

function hideProduct(){
	
	$('#productPopup').fadeOut(300);
	showingProduct = false;
	
}


function showBrand(name){
	
	if(showingBrand == true) return;
	
	hideProduct();
	
	$('#brandPopup').hide();
	
	$('#brandDetails').html(name);
	
	$('#brandPopup').fadeIn(300);
	$('#brandPopup').center();
	
	showingBrand = true;
}

function hideBrand(){
	$('#brandPopup').fadeOut(300);
	showingBrand = false;
}

function showRecipeImage(timeOut){
	
	if(showingRecipe == true) return;
	
	hideRecipeImage();
	
	$('#recipeImagePopup').hide();
	
	//$('#brandDetails').html(name);
	
	$('#recipeImagePopup').fadeIn(300);
	$('#recipeImagePopup').center();
	
	if(timeOut == true){
		recipeImageTimeout = setTimeout("hideRecipeImage()", 3000);
	}else{
		recipeImageTimeout = null;
	}
	
	showingRecipe = true;
}

function hideRecipeImage(){
	$('#recipeImagePopup').fadeOut(300);
	showingRecipe = false;
	clearTimeout(recipeImageTimeout);
}

function neverViewClick(){
	var neverView = ($('#neverViewCheck').attr("checked") == true)?1:0;
	/*
	var url = window.location.href;
	var qPos = url.indexOf('?');
	var params = (qPos == -1) ? "" : url.substr(url.indexOf('?')+1);
	params = params.split('&');
	var newUrl = window.location.pathname + "?";
	for (var i = 0; i < params.length; i++) {
		params[i] = params[i].split('=');
		if(params[i][0] != "" && params[i][0] != "neverView") newUrl += params[i][0]+"="+params[i][1]+"&";
	}
	
	newUrl += "neverView="+neverView;
	window.location.href = newUrl;
	*/
	
	var date = new Date();
	date.setTime(date.getTime()+(20*24*60*60*1000));
	neverView_cookie = 'sgmneverview'+"="+escape(neverView)+"; expires="+date.toGMTString()+"; path=/";
	document.cookie= neverView_cookie;
}

function showShare(){
	
	if(showingShare == true) return;
	
	hideShare();
	
	$('#sharePopup').hide();
	
	//$('#brandDetails').html(name);
	
	$('#sharePopup').fadeIn(300);
	$('#sharePopup').center();
	
	showingShare = true;
}

function hideShare(){
	
	$('#sharePopup').fadeOut(300);
	showingShare = false;
	
}

function parseImagePath(oString,sizeIndex){	return oString.replace(/\//,"/"+sizeIndex+"_");}

$.ajaxSetup({
  global: true,
  dataType:"text",
  type: "POST",
  async:true
});

function deleteQueryStringFromURL(){
	var theIndex = window.location.href.indexOf("?");
	var newURL = window.location.href.substring(0,theIndex);
	window.location.href = newURL;
}

function showPreloader(){
	$("#ajaxPreloader").css("display","block");
}

function hidePreloader(){
	$("#ajaxPreloader").css("display","none");
}



