﻿/// <reference path="jQuery.js" />
/// <reference path="hmc-widget-base.js" />

function Widget1(customParameters) {

    // private variables
    //#region

    var rootUrl = "http://www.helpmycash.com/widgets/";
    var wgtsStylesUrl = rootUrl+ "Content/CSS/styles.css";
    var wgt1stylesUrl = rootUrl + "Content/CSS/widget1styles.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 logoHeaderImageUrl = rootUrl + "Content/Images/help-my-cash.gif";
    var logoImageUrl = rootUrl + "Content/Images/Logo.gif";
    var rootId = "hmc-wgt-divRootWgt1";
    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 containerId;

    var parameters = {
        //labels
    widgetHeader: "Calculadora Hipotecaria",
        loanAmountLabel: "Hipoteca",
        calcHeader: "Calcula tu cuota",        
        interestRateLabel: "Tipo de interés",
        termLabel: "Plazo en años",
        calcBtnText: "Calcular",
        monthlyPaymentLabel: "Cuota mensual*",
        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",

        //URLs
        serviceURL: "http://service.helpmycash.com/App/Services/WidgetService.asmx/MonthlyPayment"
    };

    var txtBoxLoanAmountId = "hmc-wgt-txtboxLoanAmount";    
    var txtBoxInterestRateId = "hmc-wgt-txtBoxInterestRate";   
    var txtBoxTermId = "hmc-wgt-txtBoxTerm";
    
    var lblMonthlyPaymentId = "hmc-wgt-lblMonthlyPayment";
    
    //controls
    var txtLoanAmount;
    var txtBoxInterestRate;
    var txtBoxTerm;

    //validators
    var varLoanAmount;
    var valInterestRate;
    var valTerm;
    //#endregion

    // return
    var lblMonthlyPayment;

       //#region

    //#endregion

    // private methods
    //#region

    function btnCalculate_click() {

        if (!varLoanAmount.isValid() || !valInterestRate.isValid() || !valTerm.isValid()) {
            //alert("Entered data not valid!");
            return;
        }
        jQuery.ajax({ url: parameters.serviceURL,
            data:
			{
			    loanAmount: varLoanAmount.getValue(),
			    interestRate: valInterestRate.getValue(),
			    loanTerm: valTerm.getValue()
			},
            dataType: "jsonp",
            success: function(json) {
                var result = eval("(" + json.d + ")");
                //debugger;
                lblMonthlyPayment.text(result.monthPayment + "€");
            },
            error: function() {
            alert("Server error occured!!");
            }
        });
    }


    function createRoot() {
        if (document.lastWidget1Id) { document.lastWidget1Id++; }
        else { document.lastWidget1Id = 1; }

        containerId = "hmc-wgt-wgt1container" + document.lastWidget1Id;
        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 type=\"text\" id=\"" + txtBoxLoanAmountId + "\" class=\"hmc-wgt-txtBox\"/></div>" +
            "<div class=\"hmc-wgt-column3\"><span class=\"hmc-wgt-quntType\">€</span>" +
            "</div> <div class=\"hmc-wgt-column1\">" + parameters.interestRateLabel + "</div> <div class=\"hmc-wgt-column2\">" +
            "<input type=\"text\" id=\"" + txtBoxInterestRateId + "\" class=\"hmc-wgt-txtBox\"/>" +
            "</div><div class=\"hmc-wgt-column3\"> <span class=\"hmc-wgt-quntType\">%</span></div>" +
            "<div class=\"hmc-wgt-column1\">" + parameters.termLabel + "</div><div class=\"hmc-wgt-column2\">" +
            "<input type=\"text\" id=\"" + txtBoxTermId + "\" class=\"hmc-wgt-txtBox\"/></div><div style=\"clear: both;\"></div>" +
            "</div> <div class=\"calculo-hipotecas\">&nbsp;</div>" +
            "<input type=\"button\" id=\"btnCalculate\" value=\"" + parameters.calcBtnText + "\" /> " +
            "<div class=\"calculo-hipotecas\">&nbsp;</div> <div class=\"hmc-wgt-calcResults\"> " +
        //results
            "<div class=\"hmc-wgt-column1\"> "+parameters.monthlyPaymentLabel + "</div> <div class=\"hmc-wgt-column2\">" +
            "<span id=\""+lblMonthlyPaymentId +"\">&nbsp;</span></div><div style=\"clear: both;\"></div></div>"+
            "<div class=\"hmc-wgt-majorPrecision\">" + parameters.majorPrecisionLabel + "&nbsp;" +
            "<a href=\"" + majorPrecisionLink + "\" target=\"_blank\">" + parameters.majorPrecisionLinkText + "</a></div>" +
            "<div class=\"hmc-wgt-helpMyCash\"><a href=\"" + helpMyCashLink + "\" class=\"calculadora-hipotecas\" target=\"_blank\">" +
            "<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.lnkWidget1stylesAdded) {
            addLink(wgt1stylesUrl);
            document.lnkWidget1stylesAdded = 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;
            }
        }
        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 (ToolTip) == "undefined" || typeof (jQuery.tooltip) == "undefined") {
            setTimeout(tryReady, 20);
        }
        else {
            if (!IE) { initialize(); return; }
            
            jQuery(function() {
                initialize();
            });
        }
    }
    function initialize() {
        jQuery.noConflict();
        parameters = jQuery.extend(parameters, customParameters);
        createTree();

        var preStr = "#" + rootId + " #" + containerId + " ";

        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 />")
						.parent()
							.addClass("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 btnCalculate = jQuery(preStr + " input[id=btnCalculate]");
        var helpIcon = jQuery(preStr + " #imgHelpIcon");
           
        if (!IE) {
            btnCalculate.corner("5px");
        }

        btnCalculate.click(function() {
            btnCalculate_click();
            return false;
        });
        var wgtTxtBoxColl = jQuery(preStr + " .hmc-wgt-txtBox");
        
        txtLoanAmount = wgtTxtBoxColl.filter("#" + txtBoxLoanAmountId);
        txtBoxInterestRate = wgtTxtBoxColl.filter("#" + txtBoxInterestRateId);
        txtBoxTerm = wgtTxtBoxColl.filter("#" + txtBoxTermId);

        lblMonthlyPayment = jQuery(preStr + "#" +lblMonthlyPaymentId);

        varLoanAmount = new NumericValidator(txtLoanAmount);
        varLoanAmount.minValue = 1000;
        varLoanAmount.maxValue = 9999999;
        varLoanAmount.decimalsCount = 0;

        valInterestRate = new NumericValidator(txtBoxInterestRate);
        valInterestRate.minValue = 0.01;
        valInterestRate.maxValue = 9.99;
        valInterestRate.decimalsCount = 2;
        valInterestRate.defaultValue = 2.50;

        valTerm = new NumericValidator(txtBoxTerm);
        valTerm.minValue = 1;
        valTerm.maxValue = 50;
        valTerm.decimalsCount = 0;
        valTerm.defaultValue = 30;
    }

    //#endregion

    // constructor logic
    //#region

    createRoot();
   
    addLinks();
    tryReady();
    
    //#endregion
}