﻿
// *************************************************************************
//      CREATED BY:     GABOR SOLTESZ
//      PROPERTY OF:    HALO FINANCIAL LTD
//
//      Copyright:      © 2010 Halo Financial Ltd.
//                      All rights reserved.
//
//      Technical support: Please contact your Halo Affiliate Consultant
// *************************************************************************

var bCreditBelow = true; 
var bCreditAsImage = false; 
var bShowResultCurrency = true;
var bShowResultDecimalPoints = true;
var bDebug = false;
var strFromCurrency = null;
var strToCurrency = null;
var strFromAmount = null;

var clsCCSupport = new _clsCurrencyConverter();

function Halo_SetSetting(strSetting, vValue) {

	switch (strSetting)
	{
		case "STRING_FromCurrency":
		    strFromCurrency = vValue;	    
		    break;   
		case "STRING_ToCurrency":
		    strToCurrency = vValue;	    
		    break;   
		case "STRING_FromAmount":
		    strFromAmount = vValue;	    
		    break;   
		case "BOOLEAN_CreditBelow":
		    bCreditBelow = vValue;	    
		    break;   
		case "BOOLEAN_CreditAsImage":
		    bCreditAsImage = vValue;	    
		    break;   
		case "BOOLEAN_ShowResultCurrency":
		    bShowResultCurrency = vValue;
		    break;
		case "BOOLEAN_ShowResultDecimalPoints":
		    bShowResultDecimalPoints = vValue;
		    break;
		case "BOOLEAN_Debug":
		    bDebug = vValue;
		    break;
	}
	
}

function Halo_CurrencyConverterPopup() {

    clsCCSupport.CurrencyConverterPopup();
    
}

function Halo_InstantConvert(fromCurrencyCode, toCurrencyCode, fromAmount) {

    clsCCSupport.ConvertCurrencyAmount(fromCurrencyCode, toCurrencyCode, fromAmount);

}

function Halo_CurrencyConverterBox() {

    clsCCSupport.MakeCurrencyConverterBox();

}

function Halo_FullCurrencyConverter() {

    clsCCSupport.MakeFullCurrencyConverter();

}

function Halo_CalculateCCResult() {

    clsCCSupport.CalculateCCResult();

}











function _clsCurrencyConverter() {

    var const_PUBLIC_CONVERTER_BOX = 1;
    var const_HOME_CONVERTER_BOX = 2;
    var const_FULL_CONVERTER_STRIP = 3;
    var const_CONVERTER_SMALL_STRIP = 4;
    
    // ---------------------------------
    
    var ConverterRequests = new Array();
    var convDisplayBox = null;
    var convDisplayFull = null;
    var convDisplay = null;
    var convDisplayStrip = null;
    var currencyList = null;
    var dataOnly = false;
    var gettingData = false;
    var bNoData = false;
    var strErrorMessage = "...error!";
    
    this.ConvertCurrencyAmount = function(fromCurrencyCode, toCurrencyCode, fromAmount) {

        try {
            if (currencyList==null) {
                if (gettingData==false) {
                    gettingData = true;
                    dataOnly = true;
                    GetCurrencyList();
                }    
            }        

            convRequest=new Object();
            convRequest.fromCurrencyCode=fromCurrencyCode;
            convRequest.toCurrencyCode=toCurrencyCode;
            convRequest.fromAmount=fromAmount;
            
            var fieldName = "haloCurrConvResult" + ConverterRequests.length;
            var strField = "<span id='" + fieldName + "'><img src='https://secure.halofinancial.com/images/getting_data.gif' title='connecting to server...'>please wait...</span>";
            document.write(strField);
            
            convRequest.fieldName=fieldName;
            ConverterRequests.push(convRequest);
            
            ProcessConverterRequests();

        } catch(e) {
            if (bDebug==true) {
                alert("ConvertCurrencyAmount. \n" + e.message);
            }
        }

    }

    var GetCurrencyList = function() {

        try {
            var request = 'https://secure.halofinancial.com/SupportServices/CurrencyConverter/CurrencyConverterData.ashx?access=restricted';
            //var request = 'http://localhost/secure.halofinancial/SupportServices/CurrencyConverter/CurrencyConverterData.ashx?access=restricted';
            
            JSON_CAll(request);

        } catch(e) {
            if (bDebug==true) {
                alert("GetCurrencyList. \n" + e.message);
            }
        }

    }

    var GetCurrencyDisplay = function(displayID) {

        try {
            var request = 'https://secure.halofinancial.com/SupportServices/CurrencyConverter/CurrencyConverterDisplay.ashx?display=' + displayID;
            //var request = 'http://localhost/secure.halofinancial/SupportServices/CurrencyConverter/CurrencyConverterDisplay.ashx?display=' + displayID;

            JSON_CAll(request);

        } catch(e) {
            if (bDebug==true) {
                alert("GetCurrencyDisplay. \n" + e.message);
            }
        }
        
    }
    
    this.gotData = function(jsonData) {

        try {
            if (bDebug==true) {
                alert("Data call back.");
            }   
            if (jsonData != null) {
                if (jsonData.ArrayOfCurrencyList != null) { 
                    LoadCurrencies(jsonData.ArrayOfCurrencyList.CurrencyList);  
                    return true; 
                } else {
                    strErrorMessage = jsonData;
                }    
            }

            LoadCurrencies(null);
        } catch(e) {
            if (bDebug==true) {
                alert("gotData. \n" + e.message);
            }
        }

    }

    this.gotDisplay = function(iType, jsonData) {

        try {
            if (bDebug == true) {
                alert("Display call back for: " + iType);
            }

            if (jsonData != null) {
                var fieldName = null;

                switch (iType) {
                    case const_PUBLIC_CONVERTER_BOX:
                        if (convDisplayBox != null) {
                            fieldName = convDisplayBox.fieldName;
                        }
                        break;

                    case const_FULL_CONVERTER_STRIP:
                        if (convDisplayFull != null) {
                            fieldName = convDisplayFull.fieldName;
                        }
                        break;

                    case const_CONVERTER_SMALL_STRIP:
                        if (convDisplayStrip != null) {
                            fieldName = convDisplayStrip.fieldName;
                        }
                        break;

                    default:
                        if (convDisplay != null) {
                            fieldName = convDisplay.fieldName;
                        }
                }

                if (fieldName != null) {
                    if (bDebug == true) {
                        alert("Display field name: " + fieldName);
                    }
                    
                    var fieldObj = document.getElementById(fieldName);

                    if (fieldObj != null) {
                        var strHtml = jsonData;
                        fieldObj.innerHTML = strHtml;
                    }
                }

                dataOnly = false;
                if (gettingData == false) {
                    gettingData = true;
                    GetCurrencyList();
                }
            }
        } catch (e) {
            if (bDebug == true) {
                alert("gotDisplay. \n" + e.message);
            }
        }

    }
    
    var ProcessConverterRequests = function() {
        
        try {
            if (ConverterRequests.length > 0) {  
                var i = 0;
                var count = ConverterRequests.length;
                for (i=0; i<count; i++){
                    var convRequest = ConverterRequests[i];
                    var fieldName = convRequest.fieldName;
                    
                    if (fieldName!=null) {
                        var fieldObj = document.getElementById(fieldName);
                        
                        if (fieldObj!=null) {
                            var strHtml = "";
                            
                            if (currencyList!=null && bNoData==false) {
                                strHtml = MakeCCResult(convRequest);
                            } else {
                                if (gettingData == false) {
                                    strHtml = MakeErrorResult();
                                }    
                            }   
                            if (strHtml != "") { 
                                fieldObj.innerHTML = strHtml;
                            }    
                        }
                    }
                }
            }            
            
        } catch(e) {
            if (bDebug==true) {
                alert("ProcessConverterRequests. \n" + e.message);
            }
        }
    }

    var MakeCCResult = function(convRequest) {

        try {
            var strHtml = "";
            var strFromAmount;
            var strFromRate;
            var strToRate;
            var dblResult = 0;
            var i=0;
            var iList;
            var iResultDecimals = 0;
            
            var fromC = convRequest.fromCurrencyCode;
                fromC = fromC.toUpperCase();
            var toC = convRequest.toCurrencyCode;
                toC = toC.toUpperCase();
            var strFromAmount = convRequest.fromAmount;
            
            iList = currencyList.length;
            
            for (i=0; i<iList; i++) {
                objCurrency = currencyList[i];
                
                var strCode = objCurrency.CurrencyCode;
                var strValue = objCurrency.GBPRate;

                if (fromC==strCode) {
                    strFromRate = strValue;
                }

                if (toC==strCode) {
                    strToRate = strValue;
                }
            }
            
            dblResult = Calculate(strFromAmount, strFromRate, strToRate);
            
            strHtml += "<table border='0' cellpadding='0' cellspacing='0'>";
            strHtml += "    <tr>";
            strHtml += "        <td align='left'>";
            if (bShowResultCurrency == true) {
                strHtml += toC + " ";
            }            

            if (bShowResultDecimalPoints==true) {
                iResultDecimals = 2;
            } else {
                iResultDecimals = 0;
            }
            
            strHtml += number_format(dblResult, iResultDecimals, '.', ',');
            strHtml += "        </td>";
            if (bCreditBelow==true) {
                strHtml += "    </tr>";
                strHtml += "    <tr>";
            }
            strHtml += "        <td style='font-family: Arial; color: red; font-size: 9px; padding-left: 2px;' align='left'>";
            if (bCreditAsImage==true) {
                strHtml += "<a href='https://secure.halofinancial.com/SubmitForms/LiveQuote.aspx' target='_blank' title='Example exchange rates are provided by Halo Financial. Click here for a live quote.' style='color: Red; text-decoration: none;'><img src='https://secure.halofinancial.com/Images/halo_logo_tiny.jpg' border='0' alt='Halo Financial' title='Example exchange rates are provided by Halo Financial. Click here for a live quote.' /><a/>"
            } else {
                strHtml += "<a href='https://secure.halofinancial.com/SubmitForms/LiveQuote.aspx' target='_blank' title='Example exchange rates are provided by Halo Financial. Click here for a live quote.' style='color: Red; text-decoration: none;'>Halo Financial<a/>"
            }
            strHtml += "        </td>";
            strHtml += "    </tr>";
            strHtml += "</table>";

            return(strHtml);
            
        } catch(e) {
            if (bDebug==true) {
                alert("MakeCCResult. \n" + e.message);
            }
        }

    }
    
    var MakeErrorResult = function() {

        try {
            var strHtml = "";
            
            strHtml += "<table border='0' cellpadding='0' cellspacing='0'>";
            strHtml += "    <tr>";
            strHtml += "        <td style='font-family: Arial; color: red; font-size: 9px; padding-left: 5px;' align='left'>";
            strHtml += strErrorMessage
            strHtml += "        </td>";
            strHtml += "    </tr>";
            strHtml += "</table>";

            return(strHtml);

        } catch(e) {
            if (bDebug==true) {
                alert("MakeErrorResult. \n" + e.message);
            }
        }
    }
    
    this.CurrencyConverterPopup = function() {

        try {
            // Full window currency converter...
            var strWinName = "HaloFinancialCurrencyConverter";
            var strUrl = "http://www.halofinancial.com/currency_converter/";
            var sFeatures="height=310,width=625,resizable=no,scrollbars=no,status=no,directories=no,address=no";
        		
            window.open(strUrl,strWinName,sFeatures);
        } catch(e) {
            if (bDebug==true) {
                alert("CurrencyConverterPopup. \n" + e.message);
            }
        }

    }

    this.MakeCurrencyConverterBox = function() {

        try {
            convDisplayBox = new Object();
                   
            var fieldName = "haloCurrConvBoxDisplay";
            var strField = "<span id='" + fieldName + "'><img src='https://secure.halofinancial.com/images/getting_data.gif' title='connecting to server...'>please wait...</span>";
            document.write(strField);
            
            convDisplayBox.fieldName=fieldName;

            GetCurrencyDisplay(const_PUBLIC_CONVERTER_BOX);
        } catch(e) {
            if (bDebug==true) {
                alert("MakeCurrencyConverterBox. \n" + e.message);
            }
        }
    }
    
    this.MakeFullCurrencyConverter = function() {

        // A nicely designed currency converter to add to your site
         try {
             convDisplayFull = new Object();
                   
            var fieldName = "haloCurrConvFullDisplay";
            var strField = "<span id='" + fieldName + "'><img src='https://secure.halofinancial.com/images/getting_data.gif' title='connecting to server...'>please wait...</span>";
            document.write(strField);
            
            convDisplayFull.fieldName=fieldName;

            GetCurrencyDisplay(const_FULL_CONVERTER_STRIP);
            
        } catch(e) {
            if (bDebug==true) {
                alert("MakeFullCurrencyConverter. \n" + e.message);
            }
        }        
    }

    this._MakeCurrencyConverter = function() {

        try {
            convDisplay = new Object();
                   
            var fieldName = "haloCurrConvDisplay";
            var strField = "<span id='" + fieldName + "'><img src='https://secure.halofinancial.com/images/getting_data.gif' title='connecting to server...'>please wait...</span>";
            document.write(strField);
            
            convDisplay.fieldName=fieldName;

            GetCurrencyDisplay(const_HOME_CONVERTER_BOX);
        } catch(e) {
            if (bDebug==true) {
                alert("MakeCurrencyConverter. \n" + e.message);
            }
        }        
       
    }

    this._MakeCurrencyConverterSmallStrip = function() {
        
        try {
            convDisplayStrip = new Object();
                   
            var fieldName = "haloCurrConvStripDisplay";
            var strField = "<span id='" + fieldName + "'><img src='https://secure.halofinancial.com/images/getting_data.gif' title='connecting to server...'>please wait...</span>";
            document.write(strField);
            
            convDisplayStrip.fieldName=fieldName;

            GetCurrencyDisplay(const_CONVERTER_SMALL_STRIP);
        
        } catch(e) {
            alert("MakeCurrencyConverterSmallStrip. \n" + e.message);
            
        }
        
    }

    this.CalculateCCResult = function() {
        // USED BY AUTOMATION
        var objFromAmountBox = document.getElementById("txtCCFromAmount");
        var objFromCurrencyList = document.getElementById("cboCCFromCurrency");
        var objToCurrencyList = document.getElementById("cboCCToCurrency");
        var objResultBox = document.getElementById("lblCCResultBox");
        var objCCRateBox = document.getElementById("lblCCRateBox");
        var strFromAmount = objFromAmountBox.value;
        var dblFromAmount;
        var dblFromRate;
        var dblToRate;
        var dblRate;
        var dblResult = 0;
        var strZeroResult = "0.00";
        var iResultDecimals = 2;
        
        try {
            dblFromRate = objFromCurrencyList.options[objFromCurrencyList.selectedIndex].value;
            dblToRate = objToCurrencyList.options[objToCurrencyList.selectedIndex].value;
            
            if (isNaN(strFromAmount)==false){
                dblFromAmount = 0 + strFromAmount;
            } else {
                dblFromAmount = 0;
            }
            
            if (dblToRate!=0) {
                dblRate = dblFromRate / dblToRate;
                if (dblRate!=0) {
                    dblResult = dblFromAmount / dblRate;
                }    
            }    
            
        } catch(e) {
            
            if (bDebug==true) {
                alert("CalculateCCResult. \n" + e.message);
            }    
            dblResult = 0;
            
        }
        
        if (bShowResultDecimalPoints==true) {
            strZeroResult = "0.00";
            iResultDecimals = 2;
        } else {
            strZeroResult = "0";
            iResultDecimals = 0;
        }
        
        if (isNaN(dblResult)==true || isFinite(dblResult)==false) {
            objResultBox.innerHTML = strZeroResult;
        } else {
            objResultBox.innerHTML = number_format(dblResult, iResultDecimals, '.', ',');
        }    
        
        try {
            dblRate = 1 / dblRate;
            if (isNaN(dblRate)==true || isFinite(dblRate)==false) {
                objCCRateBox.innerHTML = strZeroResult;
            } else {
                objCCRateBox.innerHTML = number_format(dblRate, iResultDecimals, '.', ',');
            }    
        } catch(e) {
            try {
                objCCRateBox.innerHTML = strZeroResult;
            } catch(e) {
            }        
        }
    }

    var Calculate = function(strFromAmount, strFromRate, strToRate) {

        try {
            var dblFromAmount = 0 + strFromAmount;
            var dblFromRate = 0 + strFromRate;
            var dblToRate = 0 + strToRate;
            
            var dblRate = dblFromRate / dblToRate;
            dblResult = dblFromAmount / dblRate;
        } catch(e) {
            dblResult = 0;
        }
        
        return(dblResult);
    }

    var number_format = function(a, b, c, d) {
    // var result = number_format(aNumber, 2, '.', ',');

     a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
     e = a + '';
     f = e.split('.');
     if (!f[0]) {
      f[0] = '0';
     }
     if (!f[1]) {
      f[1] = '';
     }
     if (f[1].length < b) {
      g = f[1];
      for (i=f[1].length + 1; i <= b; i++) {
       g += '0';
      }
      f[1] = g;
     }
     if(d != '' && f[0].length > 3) {
      h = f[0];
      f[0] = '';
      for(j = 3; j < h.length; j+=3) {
       i = h.slice(h.length - j, h.length - j + 3);
       f[0] = d + i +  f[0] + '';
      }
      j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
      f[0] = j + f[0];
     }
     c = (b <= 0) ? '' : c;
     return f[0] + c + f[1];
    }

    // READ QUERY STRING FROM URL

    var PageQuery = function(q) {
        if(q.length > 1) this.q = q.substring(1, q.length);
        else this.q = null;
        this.keyValuePairs = new Array();
        if(q) {
        for(var i=0; i < this.q.split("&").length; i++) {
        this.keyValuePairs[i] = this.q.split("&")[i];
        }
        }
        this.getKeyValuePairs = function() { return this.keyValuePairs; }
        this.getValue = function(s) {
        for(var j=0; j < this.keyValuePairs.length; j++) {
        if(this.keyValuePairs[j].split("=")[0] == s)
        return this.keyValuePairs[j].split("=")[1];
        }
        return false;
        }
        this.getParameters = function() {
        var a = new Array(this.getLength());
        for(var j=0; j < this.keyValuePairs.length; j++) {
        a[j] = this.keyValuePairs[j].split("=")[0];
        }
        return a;
        }
        this.getLength = function() { return this.keyValuePairs.length; } 
    }

    var queryString = function(key){
        var page = new PageQuery(window.location.search); 
        return unescape(page.getValue(key)); 
    }
        
    var LoadCurrencies = function(args) {

        gettingData = false;
        
        if (args==null) {
            bNoData=true;
        }
        
        try {
        
            currencyList = args;
            
            ProcessConverterRequests();

            if (dataOnly == true) 
            {
                return;
            }
            
            DropDownLists_RemoveWaitMessage();

            if (currencyList != null) {
                DisplayCurrencies(currencyList);
            } else {
                DropDownLists_AddError();
            }    
            

        } catch(e) {
            if (bDebug==true) {
                alert("LoadCurrencies. \n" + e.message);
            }
        }    
            
    }

    var DisplayCurrencies = function(currencyList) {
        var objCurrency;
        var iList;

        var fromC = queryString("from");
        var toC = queryString("to");
        var amount = queryString("amount");

        if (fromC=="false") {
            fromC=strFromCurrency;
        }    
        if (toC=="false") {
            toC=strToCurrency;
        }
        if (amount=="false") {
            amount=strFromAmount;
        }

        iList = currencyList.length -1;

        for (i=0; i < iList; i++) {

            objCurrency = currencyList[i];
            
            if (objCurrency!=null) {
                DropDownLists_AddItem(objCurrency, fromC, toC);
            }
        }
        
        if (amount!=null) {
            try {
                var objFromAmountBox = document.getElementById("txtCCFromAmount");
                objFromAmountBox.value = amount;
                Halo_CalculateCCResult();
            } catch(e) {
            
            }
        }    
    }
    
    var DropDownLists_AddItem = function(objCurrency, fromC, toC) {

        try {
        
            var objFromCurrencyList = document.getElementById('cboCCFromCurrency');
            var objToCurrencyList = document.getElementById('cboCCToCurrency');
            var anOption = document.createElement('OPTION');
            
            var strCode = objCurrency.CurrencyCode;
            var strName = objCurrency.CurrencyName;
            var strValue = objCurrency.GBPRate;
            var bFromSelected = false;
            var bToSelected = false;
            
            if (fromC!=null) {
                fromC = fromC.toUpperCase();
                if (fromC==strCode) {
                    bFromSelected = true;
                }
            }
            if (toC!=null) {
                toC = toC.toUpperCase();
                if (toC==strCode) {
                    bToSelected = true;
                }
            }
            
            objFromCurrencyList.options[objFromCurrencyList.options.length] = new Option(strName, strValue, bFromSelected, bFromSelected);
            objToCurrencyList.options[objToCurrencyList.options.length] = new Option(strName, strValue, bToSelected, bToSelected);
        
        } catch(e) {
            if (bDebug==true) {
                alert("DropDownLists_AddItem. \n" + e.message);
            }
        }
        
    }

    var DropDownLists_AddError = function() {

        try {
        
            var objFromCurrencyList = document.getElementById('cboCCFromCurrency');
            var objToCurrencyList = document.getElementById('cboCCToCurrency');
            
            objFromCurrencyList.options[objFromCurrencyList.options.length] = new Option(strErrorMessage, strErrorMessage, true, true);
            objToCurrencyList.options[objToCurrencyList.options.length] = new Option(strErrorMessage, strErrorMessage, true, true);
        
        } catch(e) {
            if (bDebug==true) {
                alert("DropDownLists_AddError. \n" + e.message);
            }
        }
        
    }
    
    var DropDownLists_RemoveWaitMessage = function() {

        try {
            var objFromCurrencyList = document.getElementById('cboCCFromCurrency');
            var objToCurrencyList = document.getElementById('cboCCToCurrency');
            
            objFromCurrencyList.remove(1);
            objToCurrencyList.remove(1);

        } catch(e) {
            if (bDebug==true) {
                alert("DropDownLists_RemoveWaitMessage. \n" + e.message);
            }
        }

    }
    
    
    var JSON_CAll = function(request) {

        try {
            
            aObj = new JSONscriptRequest(request);
            aObj.buildScriptTag();
            aObj.addScriptTag();

        } catch(e) {
            if (bDebug==true) {
                alert("JSON_CALL. \n" + e.message);
            }
        }
    
    }
    
    // JSON SUPPORT

    function JSONscriptRequest(fullUrl) {
        // REST request path
        this.fullUrl = fullUrl; 
        // Keep IE from caching requests
        this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
        // Get the DOM location to put the script tag
        this.headLoc = document.getElementsByTagName("head").item(0);
        // Generate a unique script tag id
        this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
    }

    // Static script ID counter
    JSONscriptRequest.scriptCounter = 1;

    // buildScriptTag method
    //
    JSONscriptRequest.prototype.buildScriptTag = function () {

        // Create the script tag
        this.scriptObj = document.createElement("script");
        
        // Add script object attributes
        this.scriptObj.setAttribute("type", "text/javascript");
        this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
        this.scriptObj.setAttribute("id", this.scriptId);
    }
     
    // removeScriptTag method
    // 
    JSONscriptRequest.prototype.removeScriptTag = function () {
        // Destroy the script tag
        this.headLoc.removeChild(this.scriptObj);  
    }

    // addScriptTag method
    //
    JSONscriptRequest.prototype.addScriptTag = function () {
        // Create the script tag
        this.headLoc.appendChild(this.scriptObj);
    }
}
