var base_href = 'http://www.bbfx.co.uk/';
var comboLock = 0;
var comboBase = 0;
var focusTrigger = 0;

$(document).ready(function(){

  if ($('.targetBlank').length > 0) {
    $("a.targetBlank").attr('target','_blank');
  }

// DROP DOWN FLAG MENU
// * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    $(".currencyCombo").mouseenter(function(){
      comboLock = 1;
    }).mouseleave(function(){
      comboLock = 0;
    });

    $("li.selected a").click(function(){
      var comboId = $(this).attr('id');
      if (comboId ==  "BaseCurrency") {
        $("#TargetCurrency").next("ul").css("display","none");
      } else {
        $("#BaseCurrency").next("ul").css("display","none");
      }
	  $(this).next("ul").toggle();
    });

    $(".currencyCombo li ul li").click(function(){
      var comboId = $(this).parents('li.selected').find('a').attr('id');
      var countryName = $(this).find('.fxCountry').text();
      var currencyName = $(this).find('.fxCurrency').text();
	  loadCurrency(comboId,countryName,currencyName);
      $(".currencyCombo ul").css("display","none");
    });


// RATE SLIDER
// * * * * * * * * * * * * * * * * * * * * * * * * * * * *

   if($("#draggable").length>0){

       var userAmount = $(".lastFigure span").attr("class");
	   var userAmountType = userAmount.charAt(0);
	   var bigFigure = deleteComas($(".lastFigure a").attr("title"));
	   if(userAmountType == 'a'){ // a = Send slider to center
		  $("#draggable").css('left', 196);
	   } else { // b = Position
	   
	      // Convert class name into a round number
	      for (i=0; i < userAmount.length; i++) {
            if(userAmount.charAt(i) == 'b') {
               userAmount = userAmount.replace('b','');
	        }
            if(userAmount.charAt(i) == '_') {
               userAmount = userAmount.replace('_','.');
	        }
          }
		  
	      var bigFigure = deleteComas($(".lastFigure a").attr("title"));
          var flagPosition = (userAmount * 400) / bigFigure;
		  if (flagPosition < 4) {flagPosition = 4;}
		  $("#draggable").css('left', flagPosition - 4);

	   }
   }


     $("#draggable").draggable({
           axis: 'x' ,
           grid: [4, 20] ,
           opacity: 0.60 ,
           distance:4,
		   containment: 'parent' ,
		   start: function(event, ui) { $("#Exchange , #BaseAmount").css("color","#bd8f04"); } ,
           drag: function(event, ui) {
               var step = getStep();
	           var bigFigure = deleteComas($(".lastFigure a").attr("title"));
               var rate = $("#BaseRate").text();
               converse(step,bigFigure,rate);
           } , 
		   stop: function(event, ui) { 
		       $("#Exchange , #BaseAmount").css("color","#000000");
               var step = getStep();
	           var bigFigure = deleteComas($(".lastFigure a").attr("title"));
               var rate = $("#BaseRate").text();
			   converse(step,bigFigure,rate);
			   $("#SHOWContStep").html("Step =" + step);
		   }
	 });


     function getStep(){
        var flagSlider = $("#draggable").offset();
		var flagContainer = $("#SlideContainer").offset();
        var step = 1 + (flagSlider.left - flagContainer.left)/4;
		return step;
	 }


     function converse(step,bigFigure,rate){
       var accuracy = 2;
	   var baseAmount = parseInt((step*bigFigure)/100);
	   var baseAmount = baseAmount.toFixed(accuracy);
   	   if(step == 1){baseAmount=1;accuracy=6;}
	   var exchage = (baseAmount*rate).toFixed(accuracy);
       $("#BaseAmount").html(insertCommas(baseAmount));
       $("#Exchange").html(insertCommas(exchage));
     }


     function deleteComas (str){
        for (i=0; i < str.length; i++) {			
			switch(str.charAt(i)) {
                case ',':
                    str = str.replace(',','');
                    break;
                case 'k':
                    str = str.replace('k','000');
                    break;
                case 'M':
                    str = str.replace('M','000000');
                    break;
            }
        }
	    return parseFloat(str);
     }



     function insertCommas(nStr){
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
     }

// BUTTONS
// * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    $("#ExecuteConversion").click(function(){
        if(executeConversion()){$("#formWrap").submit();return false;}
    });

    
    $("#HistoricalButton").click(function(){ executeHistorical(); });
    
	$("#AmountToConvert").focus(function () {focusTrigger = 1;});
	$("#AmountToConvert").blur(function () {focusTrigger = 0;});
    
    $("#InvertHome").click(function(){ invertCurrencies(); });
	 

// GENERATE CROSS TABLE BUTTON
// * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     $("#StepsHrzShort .orangeBotton").click(function(){
           var BaseCurrency = $("#BaseCurrency").find('.fxCurrency').text();
           var ExchangeDate = $("#ExchangeDate").val();
           var targetURL = "historical.php?base=" + BaseCurrency + "&xdate=" + ExchangeDate;
           window.location = targetURL;
     });

// GENERATE GUIDE BUTTON
// * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     $("#GenerateGuide").click(function(){
           var BaseCurrency = $("#BaseCurrency").find('.fxCurrency').text();
           var TargetCurrency = $("#TargetCurrency").find('.fxCurrency').text();
           var targetURL = base_href + BaseCurrency + "/" + TargetCurrency + "/Travel-Guide";
           window.location = targetURL;
     });

// DATE PICKER
// * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    if ($('#ExchangeDate').length > 0) {
	    $('#ExchangeDate').datePicker({
               startDate: '01/01/1970',
               endDate: (new Date()).asString(),
		       clickInput:true,
		       createButton:false
        });
	}
});




$(document).click(function() { 
    if (comboLock == 0) {$(".currencyCombo ul").css("display","none");}
});




// EXECUTE CONVERSION FUNCTION
// * * * * * * * * * * * * * * * * * * * * * * * * * * * *

function executeConversion(){
    var BaseCurrency = $("#BaseCurrency").find('.fxCurrency').text();
    var TargetCurrency = $("#TargetCurrency").find('.fxCurrency').text();
    var AmountToConvert = $("#AmountToConvertDisplay").val();
    if (BaseCurrency == TargetCurrency) {
         alert("Please choose two different currencies");
         return false;
    } else if (AmountToConvert == '' || AmountToConvert == '0') {
         alert("Please enter the amount you would like to convert");
         return false;
    } else {
         var targetURL = base_href + BaseCurrency + "/" + TargetCurrency + "/" + AmountToConvert;
         $("#formWrap").attr({ 
             action: targetURL ,
             method: "get"
         });
         return true;
    }
}

function executeHistorical(){
    var BaseCurrency = $("#BaseCurrency").find('.fxCurrency').text();
    var ExchangeDate = $("#ExchangeDate").val();
    for (i=0; i < ExchangeDate.length; i++) {
         if(ExchangeDate.charAt(i) == '/') {
            ExchangeDate = ExchangeDate.replace('/','-');
	     }
      }
    var targetURL = base_href + BaseCurrency + "/historical/" + ExchangeDate;
    window.location = targetURL;
}

// EXECUTE INVERTION
// * * * * * * * * * * * * * * * * * * * * * * * * * * * *

function invertCurrencies(){
//alert("");
    var baseCountryName = $("#BaseCurrency .fxCountry").text();
    var baseCurrencyName = $("#BaseCurrency .fxCurrency").text();
    var targetCountryName = $("#TargetCurrency .fxCountry").text();
    var targetCurrencyName = $("#TargetCurrency .fxCurrency").text();
    loadCurrency('TargetCurrency',baseCountryName,baseCurrencyName);
    loadCurrency('BaseCurrency',targetCountryName,targetCurrencyName);
}

function loadCurrency(comboId,countryName,currencyName){
	var className = "fx" + currencyName;
	$("#" + comboId).find(" .fxCountry").html(countryName);
	$("#" + comboId).find(" .fxCurrency").html(currencyName);
	$("#" + comboId).removeClass();
	$("#" + comboId).addClass(className);
}
