﻿(function($) {
    //Attach this new method to jQuery  
    $.fn.extend({

        // Extender function
        converter: function(options) {
            var defaults = {
                url: "http://www.bmpslovakia.sk/eurofxref-daily.php?callback=ParseEcbXML",
                showdate: true,
                dec: 2
            };

            var options = $.extend(defaults, options);

            // Iterate over the current set of matched elements
            return this.each(function() {
                var opt = options,
                memory = { from: null, to: null },
                textBoxValue = null,
                buttonConvert = null,
                comboBoxFrom = null,
                comboBoxTo = null,
                resultPanel = null,
                scriptPanel = null,
                currencyMap = null,
				datePanel = null,
                undefined;

                // Global XML parser function
                window.ParseEcbXML = function(xml) {
                    // Disable convert button before refresh
                    enableConverter(false);

                    // Initialize currency array
                    currencyMap = new Array();
                    currencyMap[0] = {
                        currencyName: "EUR",
                        rate: 1.00
                    };

                    if ($.browser.msie) {
                        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                        xmlDoc.loadXML(xml);

						var chNode = xmlDoc.childNodes[1].childNodes[0];
                        var cubes = chNode.childNodes;
						
                        for (var i = 0; i < cubes.length; i++) {
                            currencyMap[i + 1] = {
                                currencyName: cubes[i].attributes[0].value,
                                rate: cubes[i].attributes[1].value
                            };
                        }
						setDate(chNode.attributes[0].value);
                    } else {
                        $(xml).find("Cube:first > Cube").each(function(i) {
                            currencyMap[i + 1] = {
                                currencyName: $(this).attr("currency"),
                                rate: $(this).attr("rate")
                            };
                        });
					    setDate($(xml).find("Cube:first").attr("time"));
                    }

                    // Retrieve jquery objects
                    var fromValue = $(comboBoxFrom);
                    var toValue = $(comboBoxTo);

                    if (fromValue != null && toValue != null) {
                        // Reset combobox controls
                        fromValue.empty();
                        toValue.empty();

                        // Fill comboboxes with currency abbrevations
                        for (var i = 0; i < currencyMap.length; ++i) {
                            var option = "<option value=\"" + currencyMap[i].currencyName + "\">" +
                                    currencyMap[i].currencyName + "</option>";
                            fromValue.append(option);
							toValue.append(option);
                            
							if (memory.from == currencyMap[i].currencyName) {
								comboBoxFrom.selectedIndex = i;
                            }
                            if (memory.to == currencyMap[i].currencyName) {
								comboBoxTo.selectedIndex = i;
                            }
                        }
                        memory.from = null;
                        memory.to = null;
                    }

                    // Enable convert button
                    enableConverter(true);
                };

                // Helper functions
                findCurrencyRate = function(name) {
                    if (currencyMap != null) {
                        for (var i = 1; i < currencyMap.length; ++i) {
                            if (currencyMap[i].currencyName == name) {
                                return currencyMap[i].rate;
                            }
                        }
                    }
                    return null;
                };

                getFormatedValue = function(currencyFrom, fromValue, currencyTo, toValue) {
                    var formatted = (Math.round(currencyTo * Math.pow(10, opt.dec))
                                                     / Math.pow(10, opt.dec)).toString();

                    var quantity = 0, dotAt = formatted.indexOf('.');
                    if (dotAt >= 0) {
                        quantity = formatted.length - dotAt - 1;
                    } else {
                        formatted += ".";
                    }

                    for (var i = quantity; i < opt.dec; ++i) {
                        formatted += "0";
                    }

                    return (currencyFrom + " " + fromValue + " = " + formatted + " " + toValue);
                };
				
				setDate = function(dateText) {
					datePanel.innerHTML = "Alkalmazott d&aacute;tum: " + dateText;
				}

                enableConverter = function(state) {
                    if (arguments.length > 0) {
                        if (buttonConvert != null) {
                            buttonConvert.disabled = !state;
                        }
                        if ($.datepicker && options.showdate) {
                            $(comboBoxDate)[0].disabled = !state;
                        }
                    } else {
                        return !buttonConvert.disabled;
                    }
                };

                sessionGuid = function() {
                    S4 = function() {
                        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                    }
                    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
                };

                // Build up control panel
                {
                    var panel = $(this);

                    // Add date div
                    datePanel = document.createElement("div");
					datePanel.style.fontSize = "xx-small";
					datePanel.style.color = "red";
                    panel.append(datePanel);

                    // Add text element
                    panel.append("&Ouml;sszeg: ");

                    // Add currency inputbox
                    textBoxValue = document.createElement("input");
                    textBoxValue.value = "1.00";
                    textBoxValue.type = "text";
					textBoxValue.maxLength = 9;
                    textBoxValue.size = 12;

                    panel.append(textBoxValue);

                    // Add text element
                    panel.append(" R&oacute;l: ");

                    // Add currency combobox
                    comboBoxFrom = document.createElement("select");
                    panel.append(comboBoxFrom);

                    // Add text element
                    panel.append(" Ra: ");

                    // Add currency comboboxes
                    comboBoxTo = document.createElement("select");
                    panel.append(comboBoxTo);

                    // Execute remote script
                    scriptPanel = document.createElement("script");
                    scriptPanel.src = opt.url + "&guid=" + sessionGuid();
                    scriptPanel.type = "text/javascript";
                    panel.append(scriptPanel);

                    if ($.datepicker && options.showdate) {
                        // Add text element
                        panel.append(" D&aacute;tum: ");

                        // Add currency comboboxes
                        comboBoxDate = document.createElement("input");
                        comboBoxDate.type = "text";
                        comboBoxDate.size = 7;
                        panel.append(comboBoxDate);

                        /* Hungarian initialisation for the jQuery UI date picker plugin. */
                        /* Written by Istvan Karaszi (jquery@spam.raszi.hu). */
                        $.datepicker.regional['hu'] = {
                            closeText: 'bez&aacute;r&aacute;s',
                            prevText: '&laquo; vissza',
                            nextText: 'előre &raquo;',
                            currentText: 'ma',
                            monthNames: ['Janu&aacute;r', 'Febru&aacute;r', 'M&aacute;rcius', '&Aacute;prilis', 'M&aacute;jus', 'J&uacute;nius',
                                'J&uacute;lius', 'Augusztus', 'Szeptember', 'Okt&oacute;ber', 'November', 'December'],
                            monthNamesShort: ['Jan', 'Feb', 'M&aacute;r', '&Aacute;pr', 'M&aacute;j', 'J&uacute;n',
                                        'J&uacute;l', 'Aug', 'Szep', 'Okt', 'Nov', 'Dec'],
                            dayNames: ['Vas&aacute;rnap', 'H&#233;tf&ouml;', 'Kedd', 'Szerda', 'Cs&uuml;t&ouml;rt&ouml;k', 'P&eacute;ntek', 'Szombat'],
                            dayNamesShort: ['Vas', 'H&eacute;t', 'Ked', 'Sze', 'Cs&uuml;', 'P&eacute;n', 'Szo'],
                            dayNamesMin: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'],
                            weekHeader: 'H&#233;',
                            dateFormat: 'yy-mm-dd',
                            firstDay: 1,
                            isRTL: false,
                            showMonthAfterYear: false,
                            yearSuffix: ''
                        };
                        /******************************************************************/

                        $(comboBoxDate).datepicker($.extend({
                            showMonthAfterYear: false,
                            dateFormat: "yy-mm-dd",
                            minDate: new Date(2009, 1 - 1, 2),
                            maxDate: "+0D",
                            changeMonth: true,
                            changeYear: true,
                            onSelect: function(dateText, inst) {
                                // Remove script from document
                                $(scriptPanel).remove();

                                // Store combobox selected items after refresh
                                memory.from = comboBoxFrom.value;
                                memory.to = comboBoxTo.value;

                                // Build request string
                                scriptPanel.src = opt.url + "&date=" + dateText + "&guid=" + sessionGuid();

                                // Add script tag
                                panel.append(scriptPanel);
                            }
                        }, $.datepicker.regional["hu"]));
                    }
                    panel.append(" "); // Insert a white space

                    // Add convert button
                    buttonConvert = document.createElement("input");
                    buttonConvert.value = "Számol";
                    buttonConvert.type = "button";
                    panel.append(buttonConvert);

                    // Add result div
                    resultPanel = document.createElement("div");
                    panel.append(resultPanel);

                    // Add copyright div
                    panel.append("<div style=\"font-size:x-small\"><a href=\"http://www.bmpslovakia.sk/\" alt=\"BMP Slovakia\" style=\"text-decoration:none;color:blue\">B.M.P. Slovakia - All rights reserved / V&#154;etky pr&aacute;va vyhraden&eacute;</a></div>");
                }

                // Add currency textbox keyboard handler
                textBoxValueKeyPress = function(e) {
                    if (e.which == 13) { // = Enter
                        // $(buttonConvert).click(); ???
                        buttonConvertClick();
                    } else if (((e.which < 48) || (e.which > 57)) && (e.which != 46) &&
						(e.which != 8) && (e.which == 37) && (e.which == 39)) { // ! '0' = > '9' || '.' || BackSpace || Left Arrow || Right Arrow
                        e.preventDefault();
                    }
                };
                $(textBoxValue).keypress(textBoxValueKeyPress);

                // Add convert button handler
                buttonConvertClick = function() {
                    // Check converter state
                    if (enableConverter()) {
                        // Retrieve DOM objects/values
                        var currencyValue = textBoxValue.value;
                        var fromValue = comboBoxFrom.value;
                        var toValue = comboBoxTo.value;
                        var result = $(resultPanel);

                        // Conversion between currencies
                        if (currencyValue != undefined || currencyValue != null || currencyValue != "") {

                            // Validate currency value
                            if (currencyValue.match(/^\d+([\.,]\d+)?$/)) {
                                if (fromValue == toValue) {
                                    // Same currencies, no conversion required
                                    result.text(getFormatedValue(currencyValue, fromValue, currencyValue, toValue));
                                } else {
                                    // Conversion
                                    var money = (fromValue != "EUR") ?
                                    currencyValue / findCurrencyRate(fromValue) : currencyValue;
                                    if (toValue != "EUR") {
                                        money = money * findCurrencyRate(toValue);
                                    }

                                    result.text(getFormatedValue(currencyValue, fromValue, money, toValue));
                                }
                            } else {
                                result.text("");
                            }
                        } else {
                            result.text("Hiba sz&aacute;m&eacute;rt&eacute;k megad&aacute;s&aacute;ban!");
                        }
                    }
                };
                $(buttonConvert).click(buttonConvertClick);
            });
        }
    });
})(jQuery);

