var LAGOINHA = window.LAGOINHA || {};
var FORTALEZA = window.FORTALEZA || {};

FORTALEZA.search_img_error = function(img){
	//if( location.search.indexOf( "photo=true" ) == -1 )
	//{
		noImageUrl = 'http://img.todaoferta.uol.com.br/interface/fortaleza/no_image.gif';
		$(img)
			.attr('src',noImageUrl)
			.attr('width','120')
			.attr('height','120')
			.attr('alt','Imagem indisponível')
			.unbind('error')
			.removeAttr('onerror')
			.parents('div.cont-image').eq(0).removeClass('image-medium').removeClass('image-small').addClass('no-image');
	//}
	//else
	//{
		//$(img)
			//.attr('src','http://img.todaoferta.uol.com.br/interface/unavailable/normalPhoto.jpg')
			//.attr('alt','Imagem indisponível')
			//.unbind('error')
			//.removeAttr('onerror')
	//}
}


FORTALEZA.install_order_by = function(){
	$('#selOrderBy').change(function(e){
		location.href = 'http://ofertas.todaoferta.uol.com.br/'+$(this).val();
	});
}

FORTALEZA.install_get_phone_number = function(){
	$('.seller-info .actions .phone a').click(function(e){
		e.preventDefault();
		e.stopPropagation();
		var forceGet = new Image();
		var elmA = this
		var aHref = $(elmA).attr('href');
	    var hashAnn = $('a.cont-details',$(elmA).parents('.wrap-all-info')).attr('href');
        hashAnn = hashAnn.slice(hashAnn.lastIndexOf('-')+1,hashAnn.length)
	    if(hashAnn.indexOf('#') != -1)
           hashAnn = hashAnn.slice(0,hashAnn.indexOf('#'));
        if(hashAnn.indexOf('?') != -1)
           hashAnn = hashAnn.slice(0,hashAnn.indexOf('?'));

		forceGet.src='http://comprar.todaoferta.uol.com.br/listingDetail/increasePhoneViewCounter.html?id='+aHref.slice(aHref.lastIndexOf('#')+1,aHref.length)+'&listingId='+hashAnn;
		$(elmA).unbind().click(function(e){e.preventDefault()});
		$.get( "/decryptPhone.html?phone=" + $(elmA).attr('rel'), {},
		function( response )
		{
			var codRoiMeter;
			var hashAnn = $('a.cont-details',$(elmA).parents('.wrap-all-info')).attr('href');
			hashAnn = hashAnn.slice(hashAnn.lastIndexOf('-')+1,hashAnn.length)
			if(hashAnn.indexOf('#') != -1)
				hashAnn = hashAnn.slice(0,hashAnn.indexOf('#'));
			if(hashAnn.indexOf('?') != -1)
				hashAnn = hashAnn.slice(0,hashAnn.indexOf('?'));
			if($('body').is('.fortaleza-imoveis')){
				codRoiMeter = 27;
				$('body').append('<iframe name="ROIMeterCodeInjection" style="display:none" src="http://clicklogger.rm.uol.com.br/?msr=Conversoes:1&prd=27&oper=15&grp=mod:1"></iframe>');
			} else {
				codRoiMeter = 28;
				$('body').append('<iframe name="ROIMeterCodeInjection" style="display:none" src="http://clicklogger.rm.uol.com.br/?msr=Conversoes:1&prd=28&oper=15&grp=mod:1"></iframe>');
			}
			var imgRoiMeter = new Image();
			imgRoiMeter.src = 'http://clicklogger.rm.uol.com.br/?prd='+codRoiMeter+'&grp=hash:'+hashAnn+'&msr=Visualizacoes%20de%20Telefonemas:1&oper=1&rdn='+LAGOINHA.keygen();
			$(elmA).parent().html('<span>'+response+'</span>');
		}
	);
	});
}

FORTALEZA.start_photos_magnifier = function()
{
	$( "ul.announcements-list li .ann-info .cont-image a.zoom" ).mouseover( FORTALEZA.show_super_photo );
	$( "ul.announcements-list li .ann-info .cont-image a.zoom" ).mouseout( FORTALEZA.hide_super_photo );
}


FORTALEZA.show_super_photo = function( e )
{
	trigger = $( this );
	if( trigger.is( "a" ) == false )
	{
		trigger = trigger.parents( "a" ).eq(0);
	}
	if( $( ".super-photo", trigger ).size() == 0 )
	{
		if($( "img" ,trigger ).eq(0).attr( "alt" )){
			var legenda = $( "img" ,trigger ).eq(0).attr( "alt" );
		}
		else {
				var legenda = ' ';
		}
		$( trigger ).append( '<div class="super-photo"><a href="#" class="hide-super-photo">fechar</a><div class="zoomImageContainer"><img alt="" src="' + $( "img" ,trigger ).eq(0).attr( "src" ).replace( "normalPhoto", "bigPhoto" ).replace( "galeryPhoto", "bigPhoto" ) + '" /></div><p>'+legenda+'</p><span class="arrow">&nbsp;</span></div>' );
	}
	$( "ul.announcements-list li .ann-info .cont-image a.zoom" ).css('z-index',2);
	$( trigger ).css('z-index',20);
	$( ".super-photo", trigger ).show();
	$( ".hide-super-photo", trigger ).click(function(e){
		e.preventDefault();
		FORTALEZA.hide_super_photo(e, trigger);
	});
}

FORTALEZA.hide_super_photo = function( e, trigger )
{
	if(!trigger)
		trigger = $( this );
	$( ".super-photo", trigger ).hide();
}

FORTALEZA.install_save_on_wishlist = function() {
	$('ul.actions li.wishlist a').click(function(e){
		e.preventDefault();
		e.stopPropagation();
		FORTALEZA.wishlistHelpper(this);
	});
}

FORTALEZA.wishlistHelpper = function(linkEml) {
	$('body').append('<div id="wishResponse" class="hidden"></div>')
	window.wishAjaxURL = $(linkEml).attr('href')+'&flavor=html&random='+(new Date()).getTime();
	// bloco para garantir o login funcionando - START
	//window.nonAuthMessage = NOT_AUTH_FAV;
	window.TB_login_callback = function() {
		$('#TB_ajaxContent').load(window.wishAjaxURL);
	}
	// bloco para garantir o login funcionando - END
	$('#wishResponse').load(window.wishAjaxURL, function(responseText){
		TB_show(null,'#TB_inline?height=170&width=300&inlineId=wishResponse',null);
		if(responseText.match(/__NOTAUTHCODE__/gim)){
			$('#TB_ajaxContent #watchItemResponse *').not('h3').remove();
			$('#TB_ajaxContent #watchItemResponse').append('<p class="msg-mini wait-mini">Aguarde...</p>')
			try{UOLPROD.TB_login()}catch(e){void(null)}
		}
	});
}

FORTALEZA.install_send_to_friend = function() {
	$('ul.actions li.friend a').click(function(e){
		e.preventDefault();
		e.stopPropagation();
		$('.hiddenTellAFriendURL, .hiddenTellAFriendName').attr('name','');
		$('.hiddenTellAFriendURL', $(this).parent()).attr('name','tellAFriendURL');
		$('.hiddenTellAFriendName', $(this).parent()).attr('name','tellAFriendName');
		FORTALEZA.inviteLink(this);
	});
}

FORTALEZA.set_searched_url_cookie = function() {
	$('ul.announcements-list').click(function(e){
		var elmA = '';
		if($(e.target).is('a')){
			elmA = e.target;
		}else if($(e.target).parents('a').is('a')){
			elmA = $(e.target).parents('a')[0];
		}
		var lnkAhref = $(elmA).attr('href');
		if(elmA != '' && (lnkAhref.indexOf('/locacao') != -1 || lnkAhref.indexOf('/venda') != -1 || lnkAhref.indexOf('/temporada') != -1 || lnkAhref.indexOf('/lancamento') != -1 || lnkAhref.indexOf('/comprar'))){
			e.preventDefault();
			var lnkAnn = $(elmA).attr('href');
			var posAnn = $.trim($('.position',$(elmA).parents('li')).html());
			var totalAnn = $.trim($('#resultsTotal').html()).replace(/[^0-9]/g,'');
			var hashAnn = lnkAnn.slice(lnkAnn.lastIndexOf('-')+1,lnkAnn.length)
			if(hashAnn.indexOf('#') != -1)
				hashAnn = hashAnn.slice(0,hashAnn.indexOf('#'));
			if(hashAnn.indexOf('?') != -1)
				hashAnn = hashAnn.slice(0,hashAnn.indexOf('?'));
			LAGOINHA.set_cookie(hashAnn, posAnn+':'+totalAnn+':'+document.location.href.replace(/;/g,'%3B'));
			document.location = lnkAnn;
		}
	});
}

FORTALEZA.install_see_federations = function() {
	$('#top-refinement .see-all-options .see-federations').click(function(e){
		e.preventDefault();
		e.stopPropagation();
		$('#top-refinement p.simple-label').html('Temos resultados em mais de um estado:');
		$('#top-refinement #filter-list-city').hide();
		$('#top-refinement #filter-list-federation').show();
		$('#top-refinement .close-filter a').html('não quero escolher o local');
		$('#top-refinement .close-filter').show();
		$('#top-refinement .see-all-options').hide();
	});
}

FORTALEZA.seeAllLocationFilter = function() {
	if($('#top-refinement').length){
		$('#top-refinement #simple-selection').hide();
		$('#top-refinement .see-all-options').hide();
		$('#top-refinement .closed-filters').hide();
		$('#top-refinement .closed-filters').removeClass('show');
		$('#top-refinement #multiple-selection').show();
		$('#top-refinement .selected-filters').show();
		$('#top-refinement .delete-filters-help').show();
		$('#top-refinement .close-filter').show();
		$('#top-refinement h3').show();
	}
}

FORTALEZA.install_see_all = function() {
	$('#top-refinement .see-all-options .see-default').click(function(e){
		e.preventDefault();
		e.stopPropagation();
		FORTALEZA.seeAllLocationFilter();
	});
}

FORTALEZA.closeLocationsFilter = function() {
	$('#top-refinement h3').hide();
	$('#top-refinement #simple-selection').hide();
	$('#top-refinement #multiple-selection').hide();
	$('#top-refinement .selected-filters').hide();
	$('#top-refinement .delete-filters-help').hide();
	$('#top-refinement #filter-list-federation').hide();
	$('#top-refinement .close-filter').hide();
	$('#top-refinement .closed-filters').show();
}

FORTALEZA.install_close_filters = function() {
	$('#top-refinement .close-filter a').click(function(e){
		e.preventDefault();
		e.stopPropagation();
		FORTALEZA.closeLocationsFilter();
	});
}

FORTALEZA.get_selected_districts = function() {
	var districtsArray = $('#multiple-selection li :checked');
	if(districtsArray.length > 0){
		$('#top-refinement .btBuscar').removeClass('disabledButton');
		$('#form-districts').html('<span id="mais-bairros" style="display:block;"><a href="#" onclick="FORTALEZA.seeAllLocationFilter();return false;">Selecionar bairros</a></span>');
		var toAppend = "";
		for( var x = 0 ; x < districtsArray.length ; x++ ){
			var districtName = $(districtsArray[x]).parent().text();
			var pathDistrict = $(districtsArray[x]).val();
			var name = $(districtsArray[x]).attr('name');
			toAppend += '<input type="hidden" name="' + name + '" value="'+ pathDistrict +'" /></div>';
			
		}
		//toAppend += '<input type="hidden" value="' + districtsType + '" name="districtsType" id="districtsTypeAux" />';
		$('#form-districts').append(toAppend);
		return true;
	}
	return false;
}

FORTALEZA.install_search_districts = function() {
	$('#top-refinement .btBuscar').click(function(e){
		e.preventDefault();
		e.stopPropagation();
		if(FORTALEZA.get_selected_districts())
			$('#refinement:eq(0)').submit();
	});
}

FORTALEZA.verifyCheckedDistricts = function() {
	var districtsArray = $('#multiple-selection li :checked');
	if(districtsArray.length > 0){
		$('#top-refinement .btBuscar').removeClass('disabledButton');
	}else{
		$('#top-refinement .btBuscar').addClass('disabledButton');
	}
	return districtsArray.size();
}

FORTALEZA.install_click_check_districts = function() {
	$('#multiple-selection li input').click(function(e){
		var qtos = FORTALEZA.verifyCheckedDistricts();
		if(qtos >= 31){
			if($(this).attr('checked')){
				e.stopPropagation();
				e.preventDefault();
				alert('Você pode selecionar até 30 bairros.')
			}
		}
	});
}

FORTALEZA.install_change_subcategory = function() {
	$('#nav_subcategory_id').change(function(){
		FORTALEZA.shBeddroomsOptions($(this).val(), $('#dormitorios'));
	});
}

var startup = function()
{
	FORTALEZA.install_order_by();
	FORTALEZA.install_get_phone_number();
	FORTALEZA.start_photos_magnifier();
	FORTALEZA.install_save_on_wishlist();
	FORTALEZA.install_send_to_friend();
	FORTALEZA.set_searched_url_cookie();
	FORTALEZA.install_see_federations();
	FORTALEZA.install_see_all();
	FORTALEZA.install_search_districts();
	FORTALEZA.verifyCheckedDistricts();
	FORTALEZA.install_click_check_districts();
	FORTALEZA.install_close_filters();
	if($('body').is('.property-search')){
		FORTALEZA.install_change_subcategory();
		FORTALEZA.shBeddroomsOptions($('#nav_subcategory_id').val(), $('#dormitorios'));
	}
}
$( startup );
