$(document).ready(function(){	
	gg.status(true);
	//button search
	$('#button-search').click(function(){
		gg.newSearch();
	});
	//button pre image
	$('#button-prev').click(function(){
		gg.status(true);
		gg.numberCurrent--;
		gg.googleQuery();
	});
	//button next image
	$('#button-next').click(function(){
		gg.status(true);
		gg.numberCurrent++;
		gg.googleQuery();
	});
	gg.refreshInterface();
	$('#button-next').addClass('disabled');
	
	$('#slaud-on').change(function(){
		gg.slaud();
	});
	
	//change size of box with a image
	gg.resize();
	$(window).resize(function(){
		gg.resize();
	});
	
	//not effected change
	$('select,#search-key,#begin-number,').change(function(){
		if (!gg.searchFirst) {
			gg.noEffectChange();
		}
	});
	
	//$('#search-option').jqTransform();
	gg.status(false);
});

var gg = {	
	urlSearch : '/proxy.php', //url for get images
	versionProtocol: '1.0', //version of google API
	search: '', //the query for a search
	numberCurrent: 0, //current number
	safe: '', //the level safe,
	imageSize: '', //the size of images, if empty then all
	searchFirst: true, //first search
	timeSlaud: undefined
}

//function for show slauds
gg.slaud = function () {
	setTimeout('gg.slaud();', 100);
	if (gg.work) {
		return;
	}
	if ($('#slaud-on').attr('checked')) {
		if (gg.timeSlaud == undefined) {
			gg.timeSlaud = setTimeout('gg.status(true);gg.numberCurrent++;gg.timeSlaud=undefined;gg.googleQuery();', parseInt($('#time').val()) * 1000);
		}
	} else {
		if (gg.timeSlaud != undefined) {
			clearTimeout(gg.timeSlaud);
			gg.timeSlaud = undefined;
		}
	}
}

/**
 * Resize box for images
 */
gg.resize = function() {
	$('#box-image').css('max-height', parseInt($(window).height()) - 55 + 'px').css('max-width', $(window).width());
}

gg.newSearch = function() {
	gg.status(true);
	gg.search = $('#search-key').val();
	gg.numberCurrent = parseInt($('#begin-number').val());
	gg.safe = $('#filtr-safe').val();
	gg.imageSize = $('#image-size').val();
	gg.searchFirst = false;
	gg.refreshInterface();
	gg.googleQuery();
}

gg.status = function(work) {
	gg.work = work;
	if (work) {
		$('#status').show();
	} else {
		$('#status').hide();
	}
}

/**
 * Show message
 */
gg.message = function(message) {
	$('#message').html(message);
}

gg.refreshInterface = function(){
	$('input[type=button]').removeClass('disabled');
	if (gg.numberCurrent == 0) {
		$('#button-prev').addClass('disabled');
	}
}

/**
 * The query to a google server 
 */
gg.googleQuery = function() {
	$.ajax({
		url: gg.urlSearch,
		data: {
			v: gg.versionProtocol,
			q: gg.search,
			start: gg.numberCurrent,
			safe: gg.safe,
			imgsz: gg.imageSize
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			gg.message('Произошла ошибка ' + textStatus + '. Попробуйте повторить попытку позже или обновить страницу.');
			gg.status(false);
		},
		success: function(data/*, textStatus, XMLHttpRequest*/) {
			gg.message('');
			if (parseInt(data.responseStatus) != 200) {
				//if error set default window
				gg.numberCurrent = 0;
				gg.refreshInterface();
			} else {				
				if (data.responseData.results.length > 0) {
					gg.updateImage(data.responseData.results[0].unescapedUrl, data.responseData.results[0].width, data.responseData.results[0].height, data.responseData.results[0].title);
				} else {
					//if not search
					gg.updateImage();
					gg.message('По такому запросу ничего не найдено.');
				}
			}                     
		},
		dataType: 'json'
	});
}

/**
 * Update a current image
 */
gg.updateImage = function(src, width, height, title){
	if (src == undefined) {
		$('#box-image').html('');
		gg.status(false);
		return ;
	}
	
	//define size
	var wK = width / parseInt($('#box-image').css('max-width')), hK = height / parseInt($('#box-image').css('max-height'));
	var newHeight, newWidth;	
	if (wK < 1 && hK < 1) {
		newHeight = height;
		newWidth = width; 	
	} else if (wK > 1 && hK < 1) {
 		newHeight = parseInt(height / wK);
		newWidth = parseInt(width / wK);
	} else if (wK < 1 && hK > 1) {
		newHeight = parseInt(height / hK);
		newWidth = parseInt(width / hK);
	} else {
		newHeight = parseInt(height / (hK > wK ? hK : wK));
		newWidth = parseInt(width / (hK > wK ? hK : wK));		
	}	
		
	$('#box-image').html('<img class="image-search" src="' + src + '" width="' + newWidth + '" height="' + newHeight + '" title="' + title + '"/>');
	$('.image-search').load(function(){
		gg.status(false);
	}).error(function(){
		gg.message('Ошибка загрузки изображения, возможно оно было удалено с сервера.');
		gg.status(false);
	}).abort(function(){
		gg.message('Загрузка изображения прервана.');
		gg.status(false);
	});	
}

/**
 * Show the message if change - not save
 */
gg.noEffectChange = function() {
	gg.message('Для применения изменнеий, проведите повторый поиск.');
}
