//TODO: Retirar funçao fi_valida do arquivo contact.inc.php


$(function() {//Variaveis e init do ticker
	if($('#tickerFrame').length) {
		window.ticker_layer = false ;
		window.step_time = 25 ;
		window.freeze_time = 2000 ;
		window.news_index = 0 ;
		window.title_index = 0 ;
		window.end_title = "_" ;
		window.title_max_size = 75 ; // 62
		window.pause = false ;
		window.freeze_timeout_id ;
		window.step_timeout_id ;
		window.step_char_length = 1 ;
		window.foo = false ;
		prepare();
		begin_roll_ticker();
	}
});

function fi_valida( f ) {
	if( f.sender_name.value == '' ){
		alert('Por favor, escreva seu nome.') ;
		return false ;
	}
	if( ( f.sender_mail.value.indexOf(".") < 1) || ( f.sender_mail.value.indexOf("@") <= 0 ) ) {
		alert('Por favor, digite seu e-mail corretamente.') ;
		return false ;
	}
	if( f.message.value == '' ){
		alert('Por favor, escreva sua mensagem.') ;
		return false ;
	}
	return true ;
}

function fi_set_cookie(name, value){
	if( name != '' ){
		var today = new Date() ;
		today.setTime( today.getTime() ) ;
		expires = 720 * 1000 * 60 * 60 * 24 ;
		var expires_date = new Date( today.getTime() + (expires) ) ;
		document.cookie = name + '=' + value + ';path=/;expires=' + expires_date.toGMTString() ;
	}
}

function fi_get_cookie( name ){
	if( name == '' )
		return '';
	
	var name_index = document.cookie.indexOf(name + '=');
	if( name_index == -1 )
		return '' ;
	
	var cookie_value = document.cookie.substr( name_index + name.length + 1 , document.cookie.length ),
		end_of_cookie = cookie_value.indexOf( ';' );
	
	if( end_of_cookie != -1 )
		cookie_value = cookie_value.substr( 0 , end_of_cookie );
	
	var space = cookie_value.indexOf( '+ ');
	while( space != -1 ) {
		cookie_value = cookie_value.substr( 0 , space) + ' ' + cookie_value.substr( space + 1 , cookie_value.length ) ;
		space = cookie_value.indexOf( '+' ) ;
	}
	
	return cookie_value ;
}

function fi_quote_list( obj ){
	var value = fi_get_cookie( 'FI_QUOTES' ) ;
	
	if ( value.indexOf(obj.value) == -1 ) {
		if ( obj.checked )
			value += ':' + String(obj.value);
	}
	else {
		if ( !obj.checked ){
			value = value.replace( ':' + String(obj.value) , '' ) ;
		}
	}
	fi_set_cookie('FI_QUOTES',value);
}


//Função do evento onchange do seletor de ações
function fi_change_quote( evt ) {//OK
    
    var value = this.options.selectedIndex == 0 ? this.options.selectedIndex : $(this).val();
	
	if ( value )
		$.getJSON(evt.data,{quote:value,format:'json'},fi_set_quote_values);
	else
		fi_set_quote_values();
}

//Preenche o box de Cotações com os dados da ação selecionada
function fi_set_quote_values(obj) {//OK
	if ( obj ) {
		$.each(fi_set_quote_values.itens,function(attr,elm) {
			if(elm.length)
				elm.html(obj[attr]);
		});
		$('#orderBalance').val(obj['fi_balance']);
	}
	else {
		$.each(fi_set_quote_values.itens,function(attr,elm) {
			if(elm.length)
				elm.empty();
		});
		$('#orderBalance').val('');
	}
	fi_check_preview();
}
fi_set_quote_values.itens = {
	fi_company_name:'#companyName',
	fi_current_price:'#buyPrice',
	fi_opening_value:'#buyOpeningValue',
	fi_closing_value:'#buyClosingValue',
	fi_oscillation:'#buyOscillation',
	fi_trade_quantity_day:'#buyVolume',
	fi_date:'#buyDate',
	fi_medium_price:'#sellMediumPrice',
	fi_quantity:'#sellStockNum'
};



//Popup da enfoque
function fi_abrecot() {//OK
	window.open(this.href, "Enfoque" , window.cache.enfoque_size );
	return false ;
}



//Contador de limite de caracteres
function charLimit(field,max,reference) {//OK
	if(field.value.length >= max) {
		field.value = field.value.substr(0,max);
		if(field.tagName.toLowerCase() == 'textarea')
			field.scrollTop = field.scrollHeight;
	}
	if(reference) {
		if(reference.value)
			reference.value = max - field.value.length;
		else
			reference.innerHTML = max - field.value.length;
	}
}

//TODO: trocar no admin por char_limit
function fi_text_counter( message_field, count_field, max_limit) {
	charLimit(message_field, max_limit, count_field);
}

//??
function fi_opgrph( q ) {
	window.open('grafico_interativo?qs='+q,'grafint','width=840,height=600,left=0,top=20');
}

//Cálculo do valor de corretagem
function fi_get_brokerage(v) {//OK
	if(v > 0) {
		if(v <= 135.07)
			return 2.70;
		else {// v >= 135.08
			if(v <= 498.62)
				return v * 0.02;
			else {// v >= 498.63
				if(v <= 1514.69)
					return (v * 0.015) + 2.49;
				else {// v >= 1514.70
					if(v <= 3029.38)
						return (v * 0.01) + 10.06;
					else// v >= 3029.39
						return (v * 0.005) + 25.21;
				}
			}
		}
	}
	return 0;
}

//Constante para calculo de emolumentos
window.EMOLUMENT = 0.035 / 100;//OK

//Calcular o valor a ser pago/ganho por uma ação aplicando as taxas
function fi_check_balance( f ) {
	
	var p = 0, quantity, v ;
	
	//Pegar valor de mercado
	if ( $('#pricing_market:checked').length )
		p = $('#buyPrice').text() ;
	
	//Pegar valor desejado pelo usuário
	else {
		p = $('#value');
		p = p.val( p.val().replace( /\.([0-9][0-9]?)/ , ",$1" ) ).val();
	}
	
	quantity = $('#quantity');
	
	//Caso já esteja definido o valor a ser pago e a quantidade desejada
	if ( p && quantity.val() ) {

        if (p < 0 || quantity.val() < 0 ){
            return;
        }
        
		v = converter(quantity.val(),'numero') * converter(p,'numero') ;
		
		return v;
		
	}
	return 0;
}






//Gera o exemplo da estimativa do valor de compra/venda
function fi_check_preview() {//OK
	var form = $('#transaction')[0],
		preview = $('#preview');
	if ( preview.length ) {
		var total_cost = fi_check_balance( form );

		if ( total_cost ) {
			if(total_cost.toFixed(5).split('.')[1][2] == 5)
				total_cost += 0.001;
			
			var value = total_cost.toFixed(2);
			
			preview.val(converter(value,'moeda')) ;
		}
		else
			preview.val('');
	}
	else
		preview.val('') ;
}


function converter(number,format) {//OK
	if(!number || !format)
		return 0;
	if(format == 'moeda') {
		number = number.toString().replace('.',',');
		var arr = reverseArray(number.split(',')[0].split('')),
			max = arr.length>3?parseInt(arr.length / 3,10):0;
		max -= arr.length % 3 === 0?1:0;
		for(var i=1;i<=max;i++)
			arr.splice((3*i)+(i-1),0,'.');
		arr = reverseArray(arr);
		
		number = arr.join('') + ',' + (number.split(',')[1] || '00');
		return number;
	}
	else if(format == 'numero')
		return number = parseFloat(number.replace('.','').replace(',','.'));
}

function reverseArray(array) {//OK
	for(var i=array.length-1,tmp=[];i>=0;i--)
		tmp.push(array[i]);
	return tmp;
}

//VALIDAÇÕES
function fi_check_order(form) {
	$('#value, #company, #quantity, #expiration_date').css('background-color','#FFFFFF');
	var start_stop = ! ($('#start_stop').val() === '0');
	
	//Ação
	var quoteBox = $('#company',form);
	if ( ! quoteBox.val() ){
		alert( 'Selecione um papel antes de executar a ordem.' ) ;
		quoteBox.focus().css('background-color','#FFCCCC');
		return false ;
	}
	
	//Preço
	var checked = $('input:checked',form);
	if ( ! checked.length && !start_stop ) {
		alert( 'Selecione "A mercado" ou defina o preço.' ) ;
		return false ;
	}
	if ( checked.attr('id') == 'pricing_fixed' || start_stop ) {
		var value = $('#value',form);
		if ( ! value.val() ){
			alert( 'Informe o preço.' ) ;
			value.focus() ;
			value.css('background-color','#FFCCCC');
			return false ;
		}
		else if ( ! ( /^\W+|\d+$/ ).test( $.trim( value.val() ) ) ) {
			alert( 'Informe um preço válido.' ) ;
			value.focus() ;
			value.css('background-color','#FFCCCC');
			return false ;
		}
	}
	
	//Quantidade
	var quantity = $('#quantity',form);
	if ( ! quantity.val() ){
		alert( 'Informe a quantidade de ações.' ) ;
		quantity.focus().css('background-color','#FFCCCC') ;
		return false ;
	}
	else if( ! ( /^\d+$/ ).test( $.trim( quantity.val() ) ) ) {
		alert( 'Informe uma quantidade válida de ações.' ) ;
		quantity.focus().css('background-color','#FFCCCC') ;
		return false ;
	}
	
	//Data de expiração
	var expiration_date = $('#expiration_date',form);
	if ( ! expiration_date.val() ){
		alert( 'Informe a data de vencimento da ordem.' ) ;
		expiration_date.focus().css('background-Color','#FFCCCC') ;
		return false ;
	}
	else if( ! ( /^\d{1,2}\/\d{1,2}\/(?:\d{2}|\d{4})$/ ).test( $.trim(expiration_date.val()) ) ) {
		alert( 'Informe uma data de vencimento válida.' ) ;
		expiration_date.focus().css('background-Color','#FFCCCC') ;
		return false ;
	}
	
	var total_cost = fi_check_balance( form );
	var venda = $('#sellStockNum').length;
	var capital = $('#orderBalance').val();
	//Se tentarmos comprar um valor maior do que temos em caixa
	if ( total_cost !== 0 && !venda && capital < total_cost){
		alert( 'Você não tem saldo suficiente para executar essa operação.' ) ;
		return false;
	}
	//Se tentarmos vender mais ações do que temos
	else if(total_cost !== 0 && venda && parseFloat($('#sellStockNum').text().replace('.','').replace(',','.')) < parseFloat(quantity.val().replace('.','').replace(',','.'))) {
		alert( 'Você não tem ações suficientes para executar uma ordem neste valor.' ) ;
		return false ;
	}
	//Se tentarmos transacionar mais do que o limite restante de valor de transações
	if ( parseFloat($('#transactionsTotal').val()) < total_cost ) {
		alert( 'O seu limite de transações diário não comporta esta ordem.' ) ;
		return false ;
	}
	return true ;
}

//Verificar se os valores estão muito diferentes da realidade
function fi_check_price(form) {//OK
	var pricing_fixed = $('#pricing_fixed:checked');
	
	//Se o usuário escolher por definir um preço e não estivermos no start ou stop de ações
	if ( $('#start_stop').val() === '0' && pricing_fixed.length ) {
		//preço desejado para pagar pela ação
		var definedValue = converter($('#value').val(),'numero') ,
			//preço da ação
			trueValue = converter($('#buyPrice').text(),'numero') ,
			
			i = definedValue && trueValue? definedValue / trueValue: false;
		
		if ( !isNaN(i) && i ) {
			var condition;
			
			if ( $('#sell').val() == 1 ) {
				if ( i <= 0.8 )
					condition = String(Math.floor((1-i)*100)).replace('.',',') + '% menor' ;
			}
			else{
				if ( i >= 1.2 )
					condition = String(Math.floor((i-1)*100)).replace('.',',') + '% maior' ;
			}
			if ( condition.length )
				return window.confirm( 'ATENÇÃO: O preço informado nessa ordem é '+condition+' que o preço corrente do papel ('+converter(trueValue,'moeda')+'). Tem certeza de que deseja executar essa ordem?' ) ;
		}
	}
	return true ;
}

//Função de exibição da ajuda
function fi_toggle_help_visibility(){
	var layer = document.getElementById('help');
	//var window = document.getElementById('page');
	if ( layer ){
		var pos_x = Math.floor( ( Number(document.body.offsetWidth) - Number(layer.offsetWidth) ) / 2 ) ;
		layer.style.top = '300px' ;
		layer.style.left = pos_x + 'px' ;
		layer.style.visibility = layer.style.visibility == 'hidden' ?  'visible' : 'hidden' ;
	}
	return false;
}



$(function() {
	$('#menu-economia a').click(function() {
		$('#menu-economia div.iframe').toggle();
		$(this).toggleClass('aberto');
		return false;
	});
	var elms = $('#expiration_date, #start_date, #end_date, #check_start_date, #check_end_date, #intervalDate');
	elms.each(function() {
		if(this.type && this.type == 'text')
			var foo = new Epoch('epoch_popup','popup',this);
	});
	var img = document.createElement('img');
	$(img).attr('src',window.cache.imgsrc + '/ico-ajuda-seta.gif').addClass('seta');
	$('#help').append(img);
	
	if(navigator.userAgent.indexOf('MSIE 6.0') != -1) {
		var iframe = document.createElement('iframe');
		iframe.src = '';
		iframe.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
		iframe.frameborder = 0;
		iframe.id = 'iframe_help';
		iframe = $(iframe);
		$('#help').before(iframe);
	}
	$('a.help, #help #title a').click(function() {
		var help = $('#help');
		
		if(this.className == 'help') {
			var pos = $(this).position();
			help.css('left',pos.left - ($('#help').width() + 25));
			typeof(iframe)!='undefined' && iframe.css({'left':help.css('left'),height:help.height()+4});
		}
		
		help.toggle();
		
		typeof(iframe)!='undefined' && iframe.toggle();
		
		return false;
	});
	
	if($('#transaction').length) {
		
		for(var itens in fi_set_quote_values.itens)
			fi_set_quote_values.itens[itens] = $(fi_set_quote_values.itens[itens]);
		
		//Evento onchange
		var company = $('#company');
		company.bind('change',window.quote_url,fi_change_quote);
		company.change();
		
		$('#transaction').submit(function(evt) {
			return fi_check_price(this) && fi_check_order(this);
		});
		
		//calculo da estimativa
		$('#pricing_market, #pricing_fixed').change(fi_check_preview);
		
		
		$('#value')
		//calculo da estimativa
		.blur(fi_check_preview)
		//marca a opção de valor
		.focus(function() {$('#pricing_fixed').attr('checked','checked');});
		
		//calculo da estimativa
		$('#quantity').blur(fi_check_preview);
		
		
	}
	
	//$('a.help').click(fi_toggle_help_visibility);
});
$(function() {$('a.quote').click(fi_abrecot);});
