/**
 * @author Javier Arias and Claudio Cesar Sanchez Tejeda
 */

/*************************  autocompletado ************************************************/ 
dom_ready_functions[dom_ready_functions.length] = function (){	
	
	
	obj = actb(document.getElementById('loc'),[],document.getElementById('autocomplete_container'));
	
	obj.actb_firstText=true;
	
	callbackFunction2=function(response){
		obj.actb_keywords = response;
		obj.show();	
	}
	
	autocomplete_textbox=$('#loc');
	
	autocomplete_textbox.keypress(function(){
		if (this.value.ltrim().length==3){			
			$.ajax({			
				url: "../autocomplete_service.php",
				data: 'qs='+ this.value.trim(),		
				timeout: 60000,
				dataType: "json",	
				success: callbackFunction2
			});
		}
	})
	
}

/***************************** validate location ************************************/ 

dom_ready_functions[dom_ready_functions.length] = function ()
{
	// hace preloading del banner
	if (typeof(banner_preload)!='undefined') banner_preload();
	
	// setea el validador
	var formValidator = new validatorZ('form', false);
	formValidator.submit = false;	
	formValidator.addValidation('loc', formValidator.checkNull, 'Please, enter the location where you would like to perform the search.');	
	formValidator.addValidation('keywords', formValidator.checkIsNotSigns, 'Sorry, only valid letters are allowed on keyword field.');	
	formValidator.addValidation('module', formValidator.checkSelect, 'Please, select a category.', 0);	
	formValidator.addValidation('min_price', formValidator.checkNumber, 'Please, enter a valid min price.', 0);	
	formValidator.addValidation('max_price', formValidator.checkNumber, 'Please, enter a valid max price.', 0);	
	formValidator.setForm();	
	// muestra banner en el submit del form
	formValidator.submitCustomFunction = function () 
	{
		if (document.getElementById("banner") && $('#show_banner').val() == '1'){
			lightbox.set_content($("#banner"));
			$("#banner").show();
			lightbox.show();
		}
		return true;		
	}
	
	if (!$('#show_banner')[0]);
		$('#form').append('<input type="hidden" id="show_banner"  name="show_banner" value="1" />');
}
/************************************************************************************/

dom_ready_functions[dom_ready_functions.length] = function ()
{	
	$('a[@name=login_to_href]').click (function() { return call_log_system(this.href, save_function)});
	//$('#save_result_link').click (function() { return check_save_checks(this.href);});
	
	if ($('#link_watchdog_no_results').val())
	{
		var call_function = function()
		{
			call_log_system($('#link_watchdog_no_results').val(), save_function_no_results)
		}

		if ($('#page_no_results')[0])
		{
			call_function = function()
			{			
				skip_login = true;
				call_log_system($('#link_watchdog_no_results').val(), function(){
						set_log_system_content('page_no_results');
				});
			}
		}
		window.onload = call_function;
	}
}
/*
function check_save_checks(href)
{
	if (login)
	{
		check = false;

		$('#chks :checkbox').each(function() 
		{
			if (this.checked)
				check = true;
		});

		if (!check)
			alert ('Please, select one or more results to save');
		else
			call_log_system(href, save_function);
	}
	else 
		call_log_system();
	return false;
}
*/
function save_function(save_ajax_file)
{
	if (!login)
		call_back_function_before_loggin = function (response) { save_function(save_ajax_file); };
	else 
	{
		loginFormValidator.messageCustomFunction = function (errorMessages) 
		{
			var stringErrorMessages = '';
			for (var i=0; i < errorMessages.length; i++)
				stringErrorMessages += '<p>' + errorMessages[i] + '</p>' ;
			save_error_message(stringErrorMessages);
		}
		loginFormValidator.submitCustomFunction = function ()
		{
			$('#content_system_login').fadeOut('slow', function(){
				newLightbox.height('70', function() {
					$('#wait_system_login').fadeIn('slow', function(){
						$.ajax({url: save_ajax_file, 
		   						type: 'post',
								data: $('#log_system_form').formSerialize(),
								dataType: 'json',
								success: save_response
							   }); 
					});
				});
			});
			return false;
		}
		
		match = save_ajax_file.match(/\/libs\/ajax\/(save_\w+).php/i);
		set_log_system_content(match[1]);
		return false;
	}
}

function save_function_no_results(save_ajax_file)
{
	save_function(save_ajax_file);
	selected = '';
	initialize_up_area();
	$('#title').html('Save time and create a Watchdog alert.');
	$('#message_area').addClass("ok_message");
	$('#message_area table tr td').html('<table><tr><td valign="middle" style="width: 20%"><img src="' + root_path + '/images/info-ok.gif" /></td><td valign="middle">Sorry, but it appears there are no current listings matching your criteria</td></tr></table>');
	$('.area1').css('display', 'none');
	$('.area2').show();
	if (!login)
	{
		$('#content_system_login').css('height', '360px');
		$('.buttons').css('margin-top', '-30px');
		$('.button').hide();
		$('.area2').css('height', '80px');
		$('#inputs_area').css('height', '100px');
		$('#inputs_log_system').html('<table class="inputs" style="margin-top: 2px;"><tr><td valign="center"><p style="font-size:11px;">When you create a watchdog alert with Gosasa, we search millions of sites every hour for you and email the listings matching your criteria right to your Inbox!<br /></p></td></tr></table>');
		$('.area1').show();		
		$(".area1").insertAfter(".area3");
		$(".area1 > div").css('margin-top', '0');
	}
	else
	{
		$('#message_area').css('height', '100px');
		$('.buttons').css('margin-top', '');
		$('table.inputs').html('<tr><td colspan="2"><p style="font-size:11px;">When you create a watchdog alert with Gosasa, we search millions of sites every hour for you and email the listings matching your criteria right to your Inbox!</p></td></tr><tr><td style="width: 40%">Watchdog name</td><td style="width: 60%"><input id="name_sav_res" name="name_sav_res" /></td></tr>').css('width', '97%').css('margin-left', '5px');
		loginFormValidator.setForm();
		$('.button').click(function() {
			$('#message_area').hide();
			$('#message_area').css('height', '150px');
			$('.blockMsg').css('height', '215px')
		});
	}
	$('#extra_div').hide();
}

function save_response(ajax_response)
{
	$('#wait_system_login').fadeOut(function(){

		if (ajax_response['message_type'] == 'error')
		{
			$('#content_system_login').css('height', '190px');
			newLightbox.height('195', function() {$('#content_system_login').fadeIn('slow');});		
			save_error_message(ajax_response['message']);
		}
		else
			save_ok_message(ajax_response['message']);
	});
}

function save_error_message(message)
{
	message = '<table><tr><td valign="middle" style="width: 20%"><img src="' + root_path + '/images/info-error.gif" /></td><td valign="middle">' + message + '</td></tr></table>';
	$('#message_area').addClass("error_message");
	$('#message_area').removeClass("ok_message");
	$('#message_area').addClass("save_area_message");
	$('#message_area table tr td').html(message);
	fade_areas('.area3', '.area2');
	setTimeout("fade_areas('.area2', '.area3')", 5000);
}

function save_ok_message(message)
{
	message = '<table style="height: 120px"><tr><td valign="middle" style="width: 20%"><img src="' + root_path + '/images/info-ok.gif" /></td><td valign="middle">' + message + '</td></tr></table>';
	$('#title').html('Congratulations');
	$('#inputs_area').css('height', '150px');
	$('#inputs_area').addClass("ok_message");
	$('.button').hide();
	$('.buttons').css('margin-top', '-5px');
	$('.log_system_close').css('color', '#1563AF');
	$('#inputs_log_system').html(message);
	$('#content_system_login').css('height', '190px');
	newLightbox.height('195', function() {$('#content_system_login').fadeIn('slow');});		
}

function fade_areas(area1, area2)
{
	$(area1).fadeOut('slow', function() {
		$(area2).fadeIn('slow', function(){
			$('.safari_hack').html('d');
		});
	});
}

/************************************************************************************/

dom_ready_functions[dom_ready_functions.length] = function ()
{	
	var href = location.href.replace(/&source=[^&]+/, '');
	
	$('#sources_list').click(function() {
		skip_login = true;
		call_log_system($('#link_watchdog_no_results').val(), function(){
			set_log_system_content('sources_list');
		});
	});
	
	if (href != location.href)
		$('#sources_list').parent().append('<a href="' + href + '">(All sources)</a>');
}

function finish_source_search(response)
{
	var table_string = '<table style="border-collapse: collapse; width: 280px; margin-left: 5px;"><tr>';
	var style_string = '';
	
	for (var i = 0; i < response.length; i++)
	{
		if ((i % 2) == 0 && i > 1)
		{
			table_string += '</tr><tr>';
			if (!style_string)
				style_string = 'style="background: #B3EFB7;"';
			else
				style_string = '';
		}
			
		table_string += '<td ' + style_string + '><a href="#"><span>' + response[i]['site_name'] + '</span> (' + response[i]['amount'] + ')</a></td><td ' + style_string + '><input type="checkbox"></td>';
	}
	if ((i % 2) == 0)
		table_string += '</tr>';
	else
		table_string += '<td ' + style_string + '></td><td ' + style_string + '><input type="checkbox" style="visibility: hidden;"></td></tr>';
		
	
	table_string += '</table>';
		
	$('#sources_form').html(table_string);
	$('#sources_form table td').css('width', '40%').css('padding', '0').css('text-align', 'left').css('padding-left', '3px').css('padding-top', '1px').css('padding-bottom', '1px').attr('valign', 'middle');
	$('#log_system_form :checkbox').css('margin', '0').parent().css('width', '10%').attr('align', 'center');
	$('#sources_form table a').css('font', '7pt arial').css('text-decoration', 'none').click(function() {
		$(this).parent().next().children().click();
		return false;
	});
	
	$('#log_system_submit').unbind('click').click(function ()
	{
		var sources_string = '&source=';

		$('#log_system_form :checkbox').each(function() {
			if (this.checked)
			{
				var source = $(this).parent().prev().children('a').children('span').html();
				if (source != 'ALL')
					sources_string += encodeURIComponent(source) + '|';
				else 
				{
					sources_string = '&source=ALL'
					return false;
				}	 
			}
		});
		if (sources_string == '&source=')
			alert('You must select one source');
		else
		{ 
			var href = location.href.replace(/&source=[^&]+/, '');
			if(sources_string == '&source=ALL')
			{
				if (location.href == href)
					alert('You already perform a full search!');
				else
					location.href = href; 
			} 
			else
			{
				href += sources_string.substr(0, sources_string.length - 1);
				location.href = href;
			}
		}	
		return false;
	});
	
	end_loading(284);
}