var gImageSearch, resCnt = 0;

loadGoogle();
$('#edit-title').keyup(checkKeyPress);
//google.setOnLoadCallback(init);

window.setTimeout("init();", 1000);

function loadGoogle()
{
	 try {
	 	google.load('search', '1');
	 }
	 catch(e) {window.setTimeout("loadGoogle();", 1000);}
}

function init()
{
	try{
		gImageSearch = new google.search.ImageSearch();
	}
	catch(e)
	{
		window.setTimeout("init();", 1000);
		return;
	}
	gImageSearch.setSearchCompleteCallback(null, searchComplete);
}

function checkKeyPress(event)
{
	if(event.keyCode == 13)
	{
		if($('#extended').css('display') == 'block') return;
		$('#further').click();
	}
}

function startSearch()
{
	$('#sear_big').css('width','690px');
	if(document.getElementById('searchLoading') == null) $('#sear_big').prepend('<div id="searchLoading" style="color:#fff;position:absolute;margin: 100px 0 0 430px;font-weight:bold;background:#1D8BF8;padding:10px;z-index:5000;">Загрузка...</div>');
	try{
		gImageSearch.execute($('#edit-title').attr('value'));
	}
	catch(e)
	{
		window.setTimeout("startSearch();", 1000);
	}
}

function searchComplete()
{
	resCnt = 0;
	if(gImageSearch.results.length > 0)
	{
		var html = ['<p class="big center">Ты не загрузил картинку, поэтому система предлагает подставить одну из картинок из Google Image Search. Вот они, выбирай:</p>'];
		for(i=0; i<gImageSearch.results.length; i++)
		{
			if(resCnt > 3) break;
			var res = gImageSearch.results[i];
			if(res.url.indexOf('.jpg') < 1 && res.url.indexOf('.png') < 1 && res.url.indexOf('.gif') < 1) continue;
   			html.push('<div class="item"><img src="'+res.tbUrl+'" style="height:70px;margin:5px 5px 5px 0;cursor:pointer;" onclick="chooseGooglePhoto(\''+res.tbUrl+'\');" alt="'+res.contentNoFormatting+'" title="'+res.contentNoFormatting+'"/></div>');
   			resCnt++;
		}
		$('#searchLoading').remove();
		$('#searchResults').html(html.join(''));
		$('#sear_big').css('width','690px');
		$('#sear_big .gGallery').show();
	}
	else
	{
		$('#searchLoading').remove();
		$('#searchResults').html('');
		$('#sear_big .gGallery').show();
		$('#msg').html('Не удалось найти изображения для вашего запроса.');
	}
}

function chooseGooglePhoto(url)
{
	$('#edit-url').attr('value', url);
	document.forms[0].submit();
}

function checkForm(f)
{
	try{
		if($('#extended').css('display') != 'block') return;
	}
	catch(e) { return; }
	if($('#edit-title').attr('value') == '')
	{
		$('#msg').html('Поле "хочу сохранить" должно быть заполнено.');
		return;
	}
	if($('#edit-photo').attr('value') == '' || !$('#edit-photo').attr('value'))
	{
		startSearch();
		$('#msg').html('');
		return;
	}
	f.submit();
}
