﻿/// <reference path="jQuery.js" />
/// <reference path="hmc-widget-base.js" />
/// <reference path="JScript1.js" />
/// <reference path="JSON.js" />

//sayAllert

function Widget4(customParameters) {

    // private variables
    //#region

    var IE = /*@cc_on!@*/false;
    var majorPrecisionLink = "http://www.helpmycash.com/";
    var helpMyCashLink = "http://www.helpmycash.com/";
    var comprateloLink = " http://www.helpmycash.com/hipoteca/calculo-hipotecas/"

    var rootUrl = "http://www.helpmycash.com/widgets/";
    var wgtsStylesUrl = rootUrl + "Content/CSS/styles.css";
    var wgt4stylesUrl = rootUrl + "Content/CSS/Widget4styles.css";
    var jQueryUrl = rootUrl + "Content/Scripts/jQuery.js";
    var jQueryTooltipUrl = rootUrl + "Content/Scripts/jQuery.tooltip.js";
    var jQueryCornersUrl = rootUrl + "Content/Scripts/jQuery.corners.js";
    var widgetBaseScrUrl = rootUrl + "Content/Scripts/hmc-widget-base.js";
    var sliderUrl = rootUrl + "Content/Scripts/Slider-4.js";
    var logoHeaderImageUrl = rootUrl + "Content/Images/help-my-cash.gif";
    var logoImageUrl = rootUrl + "Content/Images/Logo.gif";
    var helpIconUrl = rootUrl + "Content/Images/HelpIcon.gif";


    var parameters = {
        //labels
        widgetHeader: "Calculadora Hipotecaria",
        calcHeader: "Impacto Euribor  sobre tu cuota",
        loanAmountLabel: "Hipoteca",
        loanTermLabel: "Plazo en años",
        differentialLabel: "Diferencial",
        calcBtnText: "Calcular",
        eiroborDefaultValue: '1.215',
        euriborLabel: "Euribor ",
        monthlyPayment: "Cuota",
        majorPrecisionLabel: "*Varía por hipoteca:",
        majorPrecisionLinkText: "Más información",
        calcFooter: "<a href='http://www.helpmycash.com/calcula-tu-mejor-hipoteca/' title='encuentra y negocia la mejor hipoteca' target='_blank'>Encuentra y negocia la mejor hipoteca</a>",
        widgetFooterPreLink: "¿Te gusta este widget?",
        widgetFooterLinkText: "Compártelo",
        backgroundColor: "#137E74",
        //URLs
        serviceURL: "http://service.helpmycash.com/App/Services/WidgetService.asmx/MonthlyPaymentRate"
    };

    var rootId = "hmc-wgt-divRootWgt4";

    var containerId;
    var txtBoxLoanAmountId = "hmc-wgt-txtBoxLoanAmount";
    var txtBoxLoanTermId = "hmc-wgt-txtBoxLoanTerm";
    var txtBoxDifferentialId = "hmc-wgt-txtBoxDifferential";

    var lblMonthlyPaymentId = "hmc-wgt-lblMonthlyPayment";
    var lblEuriborFieldId = "hmc-wgt-lblEuriborField"
    //controls

    var txtBoxLoanAmount;
    var txtBoxLoanTerm;
    var txtBoxDifferential;




    var lblLoanAmount;
    var lblEuriborField

    //sliders
    var sliderObj;
    var divSlidersId;
    var lblMonthlyPayment

    //validators
    var valLoanAmount;
    var valBoxLoanTerm;
    var valDifferential;
    //#endregion

    // public methods
    //#region

    //#endregion

    // private methods
    //#region

    function btnCalculate_click() {
        if (!valLoanAmount.isValid() || !valBoxLoanTerm.isValid()
             || !valDifferential.isValid()) {
            //alert("Entered data not valid!");
            return;
        }
        // alert(valLoanAmount.getValue() + " " + valBoxLoanTerm.getValue() + " " + valDifferential.getValue());  //+ " " + sliderObj.getValue())
        jQuery.ajax({ url: parameters.serviceURL,
            data:
			{
			    loanAmount: valLoanAmount.getValue(),
			    loanTerm: valBoxLoanTerm.getValue(),
			    differential: valDifferential.getValue(),
			    euriborValue: (sliderObj.getValue())
			},
            dataType: "jsonp",
            success: function(json) {
                var result = eval("(" + json.d + ")");

                lblMonthlyPayment.html(result.monthPayment + "&euro;");
            },
            error: function() {
                alert("Server error occured!");
            }
        });
    }

    function createRoot() {
        if (document.lastWidget4Id) { document.lastWidget4Id++; }
        else { document.lastWidget4Id = 1; }

        containerId = "hmc-wgt-wgt4container" + document.lastWidget4Id;
        divSlidersId = "hmc-wgt-slider-4" + +document.lastWidget4Id;
        document.write("<div id=\"" + rootId + "\"><div class=\"hmc-wgt-container\" id=\"" + containerId + "\"></div></div>")
    }

    function createTree() {
        jQuery("#" + containerId).html("<div class=\"calculadora-hipotecas\">" +
			"<img src=\"" + logoHeaderImageUrl + "\" alt=\"helpmycash\" title=\"Helpmycash - cálculo de hipotecas\" />" +
			"<span>" + parameters.widgetHeader + "</span> </div><div style=\"clear: both;\"></div>" +
			"<div class=\"hmc-wgt-calcBody\"><span class=\"hmc-wgt-calcHeader\">" +
			 parameters.calcHeader + "</span><div class=\"hmc-wgt-calcParams\"><div class=\"hmc-wgt-column1\">" +
			 parameters.loanAmountLabel + "</div><div class=\"hmc-wgt-column2\">" +
			"<input id=\"" + txtBoxLoanAmountId + "\" type=\"text\" class=\"hmc-wgt-txtBox\" /></div><div class=\"hmc-wgt-column3\"><span class=\"quntType\">&euro;</span></div><div class=\"hmc-wgt-column1\">" +
			parameters.loanTermLabel + "</div><div class=\"hmc-wgt-column2\">" +
			"<input id=\"" + txtBoxLoanTermId + "\" type=\"text\" class=\"hmc-wgt-txtBox\" /></div><div class=\"hmc-wgt-column3\"><span class=\"quntType\"></span></div><div class=\"hmc-wgt-column1\">" +
			parameters.differentialLabel +
			" <img id=\"imgHelpIcon\" src=\"" + helpIconUrl + "\" alt=\"HOLA\" /> </div><div class=\"hmc-wgt-column2\">" +
			"<input id=\"" + txtBoxDifferentialId + "\" type=\"text\" class=\"hmc-wgt-txtBox\"  /></div><div class=\"hmc-wgt-column3\"><span class=\"quntType\">%</span></div>" +

	        "</div><div style=\"clear: both;\"></div><div class=\"calculo-hipotecas\">&nbsp;</div>" +
	        "<input type=\"button\" id=\"btnCalculate\" value=\"" + parameters.calcBtnText + "\" />" +
        //results
			"<div class=\"calculo-hipotecas\">&nbsp;</div>" +
			"<div class=\"hmc-wgt-calcResults\">" +
			"<div class=\"hmc-wgt-column1\">" + parameters.euriborLabel + "</div>" +
			"<div class=\"hmc-wgt-column2\">" + parameters.monthlyPayment + "</div>" +
			"<div style=\"clear: both;\"></div></div>" +
        //sliders
            "<div id =\"hmc-wgt-sliderMaxValue\">7%</div>" +
            "<div id=\"hmc-wgt-sliderWrapper\">" +
            "<div class=\"hmc-wgt-sliderDiv\"><div id=\"" + divSlidersId + "\" ondragstart=\"return false\" onselectstart=\"return false\"></div></div>" +
            "<div id=\"hmc-wgt-Euribor\"><span id=\"" + lblEuriborFieldId + "\">0,00%</span>" +
            "<span id=\"" + lblMonthlyPaymentId + "\"></span></div></div>" + //<div style=\"clear: both;\"></div>" +
        //endslider 			
			"<div class=\"hmc-wgt-majorPrecision\">" +
			parameters.majorPrecisionLabel + "&nbsp;" +
			"<a target=\"_blank\" href=\"" + majorPrecisionLink + "\">" + parameters.majorPrecisionLinkText + "</a></div><div class=\"hmc-wgt-helpMyCash\">" +
			"<a target=\"_blank\" href=\"" + helpMyCashLink + "\" class=\"calculadora-hipotecas\">" +
			"<img src=\"" + logoImageUrl + "\" alt=\"Helpmycash\" title=\"Helpmycash - cálculo de hipotecas\" /><span>Help<span>My</span>Cash</span><br /></a></div><center><span class=\"hmc-wgt-calcFooter\">" +
			parameters.calcFooter + "</span></center><div style=\"clear: both;\"></div></div><center><span class=\"hmc-wgt-widgetFooter\">" +
			parameters.widgetFooterPreLink + "&nbsp;<a href=\"" + comprateloLink + "\" target=\"_blank\">" +
			parameters.widgetFooterLinkText + "</a></span></center>");
    }

    function addLinks() {
        if (!document.lnkBaseWidgetStylesAdded) {
            addLink(wgtsStylesUrl);
            document.lnkBaseWidgetStylesAdded = true;
        }

        if (!document.lnkWidget4stylesAdded) {
            addLink(wgt4stylesUrl);
            document.lnkWidget4stylesAdded = true;
        }

        if (!window.jQuery && !document.scrJQueryAdded) {
            addScriptReference(jQueryUrl);
            document.scrJQueryAdded = true;
        }

        addJQueryDependentScript();
    }

    function addJQueryDependentScript() {
        if (window.jQuery) {
            if (!document.scrJQueryTooltipAdded) {
                writeScriptReference(jQueryTooltipUrl);
                document.scrJQueryTooltipAdded = true;
            }

            if (!document.scrJQueryCornersAdded) {
                writeScriptReference(jQueryCornersUrl);
                document.scrJQueryCornersAdded = true;
            }

            if (!document.scrWidgetBaseAdded) {
                writeScriptReference(widgetBaseScrUrl);
                document.scrWidgetBaseAdded = true;
            }

            if (!document.scrSlider4Added) {
                writeScriptReference(sliderUrl);
                document.scrSlider4Added = true;
            }
        }
        else {
            setTimeout(addJQueryDependentScript, 20);
        }
    }

    function addLink(linkUrl) {
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = linkUrl;
        link.media = "all";
        document.getElementsByTagName('head')[0].appendChild(link);
    }

    function addScriptReference(scriptUrl) {
        var script = document.createElement("script");
        script.src = scriptUrl;
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    function writeScriptReference(scriptUrl) {
        jQuery("head").append("<script type=\"text/javascript\" src=\"" + scriptUrl + "\"></script>");
    }

    function tryReady() {
        if (typeof (window.jQuery) == "undefined" || typeof (jQuery().corner) == "undefined" || typeof (slider) == "undefined" ||
        typeof (NumericValidator) == "undefined") {
            setTimeout(tryReady, 20);
        }
        else {
            if (!IE) { initialize(); return; }

            jQuery(document).ready(function() {
                initialize();
            });
        }
    }

    function initialize() {
        jQuery.noConflict();
        parameters = jQuery.extend(parameters, customParameters);
        createTree();

        var preStr = "#" + rootId + " #" + containerId + " ";
        initializeSlider(preStr);


        jQuery(preStr + ".hmc-wgt-calcBody").corner("5px");
        var container = jQuery(preStr).corner("5px");

        container.css("background-color", parameters.backgroundColor);

        var wgtTxtBox = jQuery(preStr + " .hmc-wgt-txtBox");
        wgtTxtBox.each(function() {
            if (!jQuery(this).parent().hasClass("hmc-wgt-txtBoxWrapper")) {
                jQuery(this).wrap("<div class=\"hmc-wgt-txtBoxWrapper\" />");
            }
        });

        jQuery(preStr + " div.hmc-wgt-txtBoxWrapper").corner("5px");

        jQuery(preStr + " div.calculo-hipotecas").each(function() {
            if (!jQuery(this).parent().hasClass("calculo-hipotecasWrapper")) {
                jQuery(this).wrap("<div class=\"calculo-hipotecasWrapper\" />");
            }
        });

        var helpIcon = jQuery(preStr + " #imgHelpIcon");
        var t = new ToolTip(helpIcon, "% que se añade al índice de referencia (en general EURIBOR) para calcular el tipo de interés variable.");
        helpIcon.css("margin-bottom", "-2px");

        var btnCalculate = jQuery(preStr + " input[id=btnCalculate]");
        if (!IE) {
            btnCalculate.corner("5px");
        }
        btnCalculate.click(function() { btnCalculate_click(); });
        var wgtTxtBoxColl = jQuery(preStr + " .hmc-wgt-txtBox");

        txtLoanAmount = wgtTxtBoxColl.filter("#" + txtBoxLoanAmountId);
        txtBoxLoanTerm = wgtTxtBoxColl.filter("#" + txtBoxLoanTermId);
        txtBoxDifferential = wgtTxtBoxColl.filter("#" + txtBoxDifferentialId);

        valLoanAmount = new NumericValidator(txtLoanAmount);
        valLoanAmount.minValue = 1000;
        valLoanAmount.maxValue = 9999999;
        valLoanAmount.decimalsCount = 0;
        valLoanAmount.defaultValue = 150000;

        valBoxLoanTerm = new NumericValidator(txtBoxLoanTerm);
        valBoxLoanTerm.minValue = 1;
        valBoxLoanTerm.maxValue = 50;
        valBoxLoanTerm.decimalsCount = 0;
        valBoxLoanTerm.defaultValue = 30;

        valDifferential = new NumericValidator(txtBoxDifferential);
        valDifferential.minValue = 0.01;
        valDifferential.maxValue = 9.99;
        valDifferential.decimalsCount = 2;
        valDifferential.defaultValue = 1.09;
    }

    function initializeSlider(preStr) {
        var lblEuriborField = jQuery(preStr + "#" + lblEuriborFieldId)
        sliderObj = new slider(divSlidersId, 125, 0, 7000, 5, parseFloat(parameters.eiroborDefaultValue) * 1000, lblEuriborField);
        sliderObj.setValue(parseFloat(parameters.eiroborDefaultValue) * 1000); 
        jQuery(preStr + "#" + divSlidersId + "_knob").mouseup(function() { btnCalculate_click(); });
        jQuery(preStr + "#" + divSlidersId + "_slider").click(function() { btnCalculate_click(); });
        lblMonthlyPayment = jQuery(preStr + "#" + lblMonthlyPaymentId)
    }

    //#endregion

    // constructor logic
    //#region

    addLinks();

    createRoot();

    tryReady();

    //#endregion
}