//////////////////////////////////////////////////////////////////////////
///           Programmation des tabIndex
//////////////////////////////////////////////////////////////////////////
function prgTabIndex() {
	//programme les tabIndex
	$("select[name='paire']").attr("tabindex","1");
	$("select[name='trendW']").attr("tabindex","10");
	$("select[name='trendD']").attr("tabindex","20");
	$("select[name='trendH']").attr("tabindex","30");
	$("input[name='rW']").attr("tabindex","40");
	$("input[name='rD']").attr("tabindex","50");
	$("input[name='rH']").attr("tabindex","55");
	$("input[name='sW']").attr("tabindex","60");
	$("input[name='sD']").attr("tabindex","70");
	$("input[name='sH']").attr("tabindex","72");
	$("input[name='longshort']").attr("tabindex","75");
	$("input[name='entry']").attr("tabindex","80");
	$("input[name='stoploss']").attr("tabindex","90");
	$("input[name='t1']").attr("tabindex","100");
	$("input[name='t2']").attr("tabindex","110");
	$("input[name='risk']").attr("tabindex","120");
}
//////////////////////////////////////////////////////////////////////////
///           Programmation des Events
//////////////////////////////////////////////////////////////////////////
function prgEvent() {

	//Programme les Events
	$("select[name='paire']").change(function() {paireChange();});

	//le trade
	$("input[name='longshort']").change(function() {sensTradeChange();});
	$("input[name='entry']").change(function() {entryChange();});
	$("input[name='sW']").change(function() {verifAnalyse();});
	$("input[name='sD']").change(function() {verifAnalyse();});
	$("input[name='sH']").change(function() {verifAnalyse();});
	$("input[name='rW']").change(function() {verifAnalyse();});
	$("input[name='rD']").change(function() {verifAnalyse();});
	$("input[name='rH']").change(function() {verifAnalyse();});
	//   => les prix
	$("input[name='stoploss']").change(function() {valueChange('stoploss','entry','price');});
	$("input[name='trailing']").change(function() {valueChange('trailing','entry','price');});
	$("input[name='t1']").change(function() {valueChange('t1','entry','price');});
	$("input[name='t2']").change(function() {valueChange('t2','entry','price');});
	//   => les pips
	$("input[name='stoplossPips']").change(function() {valueChange('stoploss','entry','pips');});
	$("input[name='trailingPips']").change(function() {valueChange('trailing','entry','pips');});
	$("input[name='t1Pips']").change(function() {valueChange('t1','entry','pips');});
	$("input[name='t2Pips']").change(function() {valueChange('t2','entry','pips');});
	//   => les risk/reward
	$("input[name='t1RW']").change(function() {rwChange('t1');});
	$("input[name='t2RW']").change(function() {rwChange('t2');});
	
	//  FOCUS
	$("input[type=text]").focus(function(){ $(this).addClass("selectionne"); this.select(); });
	$("input[type=text]").blur(function(){ $(this).removeClass("selectionne"); });
	
	
	//Moneymanagement
	$("select[name='dev2']").change(function() {devChange();});
	$("input[name='margin']").change(function() {portefeuilleChange('margin');});
	$("input[name='risk']").change(function() {portefeuilleChange('risk');});
	$("input[name='riskPrice']").change(function() {portefeuilleChange('riskPrice');});
	$("input[name='posSize']").change(function() {portefeuilleChange('posSize'); });
	$("input[name='t1Price']").change(function() {portefeuilleChange('t1Price');});
	$("input[name='t2Price']").change(function() {portefeuilleChange('t2Price'); });
	
}

//////////////////////////////////////////////////////////////////////////
///           LONG +1 , SHORT -1 OU FLAT 0
//////////////////////////////////////////////////////////////////////////
function longshort() {
	var result;
	if ($("input[name='longshort']:checked").val()) {
		result=$("input[name='longshort']:checked").val();
	}else{
		result=$("input[name='longshort']").val();
	}
	//alert(result);
	return parseFloat(result);
}

//////////////////////////////////////////////////////////////////////////
///           CALCULE L'ECART ENTRE DEUX PRIX
//////////////////////////////////////////////////////////////////////////
function ecartPrix(p1,p2,what) {
	var mult;
	p1=parseFloat(p1);
	p2=parseFloat(p2);
	if (p1<30) {mult=10000;} else{mult=100;}
	if (what=="price") {
		//on renvoie un nombre de pips = ecart entre les deux prix
		return longshort()*Math.round((p2-p1)*mult);
	}else if (what=="pips") {
		//on renvoie un prix = prix + x pips
		return Math.round(mult*(p1 + longshort()*(p2/mult)))/mult;	
	}
}


//////////////////////////////////////////////////////////////////////////
///           SELECTIONNE UNE NOUVELLE PAIRE
//////////////////////////////////////////////////////////////////////////
function paireChange() {
	//on sélectionne une nouvelle paire
	//=> on met à jour le prix
	var paire=$("select[name='paire'] option:selected").val();
	$.ajax({
	  url: "/script/analyses/publications/price.php?paire="+paire,
	  cache: false,
	  dataType: 'html',
	  success: function(prix){
		$("input[name='price']").val(prix);
	  }
	});

}
//////////////////////////////////////////////////////////////////////////
///           CHANGE LES PRIX ET LES PIPS
//////////////////////////////////////////////////////////////////////////
function valueChange(sr,ref,what) {
	var price;
	var priceRef;
	if (what=="price") {
		//on vient de changer un prix ==> on recalcule le nombre de pips equivalents
		//alert($("input[name='"+sr+"']").val());
		price=$("input[name='"+sr+"']").val();
		priceRef=$("input[name='"+ref+"']").val();
		$("input[name='"+sr+"Pips']").val(ecartPrix(priceRef,price,what));
	}else if (what=="pips") {
		//on vient de changer des pips on recalcule le prix équivalent
		if ( (sr=='stoploss') || (sr=='trailing') ) {
			//on s'assure que la valeur est bien négative
			$("input[name='"+sr+"Pips']").val(-1*Math.abs($("input[name='"+sr+"Pips']").val()));		
		}
		if ( (sr=='t1') || (sr=='t2') ) {
			//on s'assure que la valeur est bien positif
			$("input[name='"+sr+"Pips']").val(Math.abs($("input[name='"+sr+"Pips']").val()));
		}
		price=$("input[name='"+sr+"Pips']").val();
		priceRef=$("input[name='"+ref+"']").val();
		$("input[name='"+sr+"']").val(ecartPrix(priceRef,price,what));
	}
	if ( (sr=='stoploss') || (sr=='t1') || (sr=='t2') || (sr=='entry') ) { 
		//cas particulier : on vient de changer un élément du trade
		// => il faut recalculer le risk/reward
		rwChange(what); 
	}
	if ( (sr=='stoploss') ) { 
		//cas particulier : on vient de changer le stop
		// => on change le trailing stop
		$("input[name='trailingPips']").val( $("input[name='stoplossPips']").val()*2);
		valueChange('trailing','entry','pips');
	}
	verifAnalyse();

	positionSizing();
}
//////////////////////////////////////////////////////////////////////////
///           CHANGE LES RISK REWARD
//////////////////////////////////////////////////////////////////////////
function rwChange(what) {
	var price1;
	var price2;
	var priceRef;
	var priceStop;
	var rw1;
	var rw2;
	if ((what=="price") || (what=="pips")) {
		//on a modifié les prix ou les pips
		// => on calcule le risk/reward
		price1=$("input[name='t1']").val();
		price2=$("input[name='t2']").val();
		priceRef=$("input[name='entry']").val();
		priceStop=$("input[name='stoploss']").val();
		rw1=(priceRef-price1)/(priceRef-priceStop);
		rw2=(priceRef-price2)/(priceRef-priceStop);
		$("input[name='t1RW']").val(Math.abs( Math.round(rw1*10)/10));
		$("input[name='t2RW']").val(Math.abs( Math.round(rw2*10)/10));
	}else if ((what=='t1') || (what=='t2')) {
		//on a modifié les risk/reward 1
		//  => on calcule les prix
		rw1=parseFloat($("input[name='"+what+"RW']").val());
		priceRef=parseFloat($("input[name='entry']").val());
		priceStop=parseFloat($("input[name='stoploss']").val());
		price1=Math.round( 10000*(priceRef+rw1*(priceRef-priceStop)) )/10000;
		$("input[name='"+what+"']").val(price1);
		valueChange(what,'entry','price');
	}
	portefeuilleChange('rw');
}
//////////////////////////////////////////////////////////////////////////
///           Modifie le prix d'entrée
//////////////////////////////////////////////////////////////////////////
function entryChange() {
	valueChange('stoploss','entry','price');
	valueChange('trailing','entry','price');
	valueChange('t1','entry','price');
	valueChange('t2','entry','price');
}

//////////////////////////////////////////////////////////////////////////
///           CHANGE LE SENS DU TRADE
//////////////////////////////////////////////////////////////////////////
function sensTradeChange() {
	valueChange('stoploss','entry','pips');
	valueChange('trailing','entry','pips');
	valueChange('t1','entry','pips');
	valueChange('t2','entry','pips');
}

//////////////////////////////////////////////////////////////////////////
///           Calcule la taille de la position
//////////////////////////////////////////////////////////////////////////
function positionSizing() {
	var riskPrice=$("input[name='riskPrice']").val();
	var dev1dev2=$("input[name='dev1dev2']").val();
	var stoploss=$("input[name='stoploss']").val();
	var entry=$("input[name='entry']").val();
	
	
/*	price=$("input[name='price']").val();
	if (price<20) {mult=10000;}else{mult=100;}

	valeurPip=riskPrice/stoplossPips;
*/
	var posSize=Math.round(Math.abs(riskPrice/((entry-stoploss)*dev1dev2)));
	$("input[name='posSize']").val(posSize);
}

//////////////////////////////////////////////////////////////////////////
///           Modifie un parametre du portefeuille
//////////////////////////////////////////////////////////////////////////
function portefeuilleChange(what) {
	var risk_pc=$("input[name='risk']").val();
	var riskPrice_pc=$("input[name='riskPrice']").val();
	var dev1dev2=$("input[name='dev1dev2']").val();
	var margin=$("input[name='margin']").val();
	var posSize=$("input[name='posSize']").val();
	var stoploss=$("input[name='stoploss']").val();
	var entry=$("input[name='entry']").val();
	var t1RW=$("input[name='t1RW']").val();
	var t2RW=$("input[name='t2RW']").val();
	var t1Price=$("input[name='t1Price']").val();
	var t2Price=$("input[name='t2Price']").val();

	if (what=='risk') {
		//calcule riskPrice
		riskPrice_pc=margin*risk_pc/100;
		$("input[name='riskPrice']").val(Math.round((riskPrice_pc)*100)/100);
		t1Price=riskPrice_pc*t1RW;
		t2Price=riskPrice_pc*t2RW;
		$("input[name='t1Price']").val(Math.round((t1Price)*100)/100);
		$("input[name='t2Price']").val(Math.round((t2Price)*100)/100);
	}else if (what=='riskPrice') {
		//calcule risk
		risk_pc=riskPrice_pc/margin*100;
		$("input[name='risk']").val(Math.round((risk_pc)*100)/100);
		t1Price=riskPrice_pc*t1RW;
		t2Price=riskPrice_pc*t2RW;
		$("input[name='t1Price']").val(Math.round((t1Price)*100)/100);
		$("input[name='t2Price']").val(Math.round((t2Price)*100)/100);
	}else if (what=='posSize') {
		//calcule riskPrice puis risk
		riskPrice_pc=Math.abs(((entry-stoploss)*dev1dev2)*posSize);
		risk_pc=riskPrice_pc/margin*100;
		$("input[name='risk']").val(Math.round((risk_pc)*100)/100  );
		$("input[name='riskPrice']").val(Math.round((riskPrice_pc)*100)/100);
		t1Price=riskPrice_pc*t1RW;
		t2Price=riskPrice_pc*t2RW;
		$("input[name='t1Price']").val(Math.round((t1Price)*100)/100);
		$("input[name='t2Price']").val(Math.round((t2Price)*100)/100);
	}else if (what=='margin') {
		//calcule riskPrice
		riskPrice_pc=margin*risk_pc/100;
		$("input[name='riskPrice']").val(Math.round((riskPrice_pc)*100)/100);
		t1Price=riskPrice_pc*t1RW;
		t2Price=riskPrice_pc*t2RW;
		$("input[name='t1Price']").val(Math.round((t1Price)*100)/100);
		$("input[name='t2Price']").val(Math.round((t2Price)*100)/100);
		enregistreCookie();
	}else if (what=='rw') {
		//risk/reward modifié => t1Price et t2Price à calculer
		t1Price=riskPrice_pc*t1RW;
		t2Price=riskPrice_pc*t2RW;
		$("input[name='t1Price']").val(Math.round((t1Price)*100)/100);
		$("input[name='t2Price']").val(Math.round((t2Price)*100)/100);
	}else if (what=='t1Price') {
		//On calcule le riskPrice => puis tout le reste
		riskPrice_pc=t1Price/t1RW
		$("input[name='riskPrice']").val(Math.round((riskPrice_pc)*100)/100);
		portefeuilleChange('riskPrice');
	}else if (what=='t2Price') {
		//On calcule le riskPrice => puis tout le reste
		riskPrice_pc=t2Price/t2RW
		$("input[name='riskPrice']").val(Math.round((riskPrice_pc)*100)/100);
		portefeuilleChange('riskPrice');
	}
	
	positionSizing();
}

//////////////////////////////////////////////////////////////////////////
///           Modifie l devise du portefeuille (moneymanagement)
//////////////////////////////////////////////////////////////////////////
function devChange() {
	var dev1=$("input[name='dev1']").val();
	var dev2=$("select[name='dev2']").val();
	if (dev1!=dev2) {
		paire=dev1+dev2;
		$.ajax({
		  url: "/script/analyses/publications/price.php?paire="+paire,
		  cache: false,
		  dataType: 'html',
		  success: function(prix){
			$("input[name='dev1dev2']").val(prix);
			positionSizing();
		  }
		});
	}else{
			$("input[name='dev1dev2']").val(1);
			positionSizing();
	}
	$("#dev2bis").html(dev2.toUpperCase());
	enregistreCookie();
}
//////////////////////////////////////////////////////////////////////////
///           ENREGISTREMENT cookies
//////////////////////////////////////////////////////////////////////////
function enregistreCookie() {
	var dev2=$("select[name='dev2']").val();
	var margin=$("input[name='margin']").val();
	$.cookie("AT_mataf","_"+margin+"_"+dev2+"_",{ expires: 90 });
}


//////////////////////////////////////////////////////////////////////////
///           VERIFICATION GLOBALE
//////////////////////////////////////////////////////////////////////////
function verifAnalyse() {
	$("#listeErreurs").text("");
	$("input").removeClass("erreurAnalyse");
	var listeErreurs="";
	//On vérifie que toutes les données sont cohérentes
	var price=$("input[name='price']").val();
	var rW=$("input[name='rW']").val();
	var rD=$("input[name='rD']").val();
	var rH=$("input[name='rH']").val();
	var sW=$("input[name='sW']").val();
	var sD=$("input[name='sD']").val();
	var sH=$("input[name='sH']").val();
	var entry=$("input[name='entry']").val();
	var stoploss=$("input[name='stoploss']").val();
	var trailing=$("input[name='trailing']").val();
	var t1=$("input[name='t1']").val();
	var t2=$("input[name='t2']").val();
	
	
	//  ==> écart entre prix d'entrée et cours actuel <100 pips
	if ((entry!="") && (price!="") && (Math.abs(ecartPrix(entry,price,"price"))>50)) {
		listeErreurs+="Le prix d'entrée est assez éloigné du cours actuel : "+ecartPrix(entry,price,"price")+" pips<br />";
		$("input[name='price']").addClass("erreurAnalyse");
		$("input[name='entry']").addClass("erreurAnalyse");
	}
	//  ==> sW<sD<sH<price<rH<rD<rW
	if ((sW!="") && (sD!="") && (sH!="") && (price!="") && ((sW>sD) || (sD>sH) || (sH>price)) ){
		listeErreurs+="Error -> Supports<br />";
		$("input[name='sW']").addClass("erreurAnalyse");
		$("input[name='sD']").addClass("erreurAnalyse");
		$("input[name='sH']").addClass("erreurAnalyse");
		$("input[name='price']").addClass("erreurAnalyse");
	}
	if ((rW!="") && (rD!="") && (rH!="") && (price!="") && ((rW<rD) || (rD<rH) || (rH<price)) ){
		listeErreurs+="Error -> Resistance<br />";
		$("input[name='rW']").addClass("erreurAnalyse");
		$("input[name='rD']").addClass("erreurAnalyse");
		$("input[name='rH']").addClass("erreurAnalyse");
		$("input[name='price']").addClass("erreurAnalyse");
	}

	//  ==> si vente trailing>stop>entree>objectif1>objectif2 (inverse si achat)
	if ((stoploss!="") && (trailing!="") && (longshort()*(stoploss-trailing)<0)) {
		listeErreurs+="Stop & Trailing<br />";
		$("input[name='stoploss']").addClass("erreurAnalyse");
		$("input[name='trailing']").addClass("erreurAnalyse");
	}
	if ((entry!="") && (stoploss!="") && (longshort()*(entry-stoploss)<0)) {
		listeErreurs+="Entry & stop<br />";
		$("input[name='stoploss']").addClass("erreurAnalyse");
		$("input[name='entry']").addClass("erreurAnalyse");
	}
	if ((t1!="") && (entry!="") && (longshort()*(t1-entry)<0)) {
		listeErreurs+="target 1 & entry<br />";
		$("input[name='t1']").addClass("erreurAnalyse");
		$("input[name='entry']").addClass("erreurAnalyse");
	}
	if ((t2!="") && (t1!="") && (longshort()*(t2-t1)<0)) {
		listeErreurs+="target 2 ² target 1<br />";
		$("input[name='t1']").addClass("erreurAnalyse");
		$("input[name='t2']").addClass("erreurAnalyse");
	}

	if (listeErreurs!="") {listeErreurs="<b>Warning</b><br>"+listeErreurs; }
	$("#listeErreurs").html(listeErreurs);

}

