var hypoCalculatorTranslations = new Object();

function calculateHypo() {
	
	var xPriceId = 'price';
	var xOwnInvestId = 'ownInvest';
	var xYearSelectId = 'yearSelect';
	var xResultId = 'result';
	
	var xMessage1Id = '';
	var xMessage2Id = '';
	
	var xInterestRate = 0.0569;
	var xOwnInvestRatio = 0.8;
	var xPrice = 0;
	var xOwnInvest = 0;
	var xYear = 0;
	var xResult = 0;
		
	if (document.getElementById(xPriceId) && document.getElementById(xOwnInvestId) && 
			document.getElementById(xYearSelectId) && document.getElementById(xResultId)) {
		
		try {			
			// PARSE PRICE
			try {
				xPrice = intval(parseInt(trimText(document.getElementById(xPriceId).value)));
			} catch (priceError) {
				xPrice = 0;
			}
			
			// PARSE OWN INVEST
			try {
				xOwnInvest = intval(parseInt(trimText(document.getElementById(xOwnInvestId).value)));
			} catch (priceError) {
				xOwnInvest = 0;
			}
			
			// PARSE YEAR
			try {
				xYear = intval(parseInt(document.getElementById(xYearSelectId).options[document.getElementById(xYearSelectId).selectedIndex].value));
			} catch (priceError) {
				xYear = 0;
			}
			
			if (xPrice > 0 && xYear > 0) {				
				// CALCULATE
				xResult = (((xPrice-xOwnInvest)*xInterestRate/12)/(1-Math.pow((1/(1+xInterestRate/12)),(12*xYear))));
				
				// APPEND RESULT
				document.getElementById(xResultId).value=Math.round(xResult);
				return true;		
			}			
			document.getElementById(xResultId).value = '';				
			
		} catch (e) {
			
		}
	}
}

$(function() {

    $('.hypoCalculatorCallBack').click(function() {
    	var wasShown = $('.hypoCalculatorEmailModalWrapper:visible').length > 0;
        $('.hypoCalculatorEmailModalWrapper').slideToggle('fast', function(){
        	if (!wasShown) {
	        	$('#TB_ajaxContent')[0].scrollTop = $('fieldset.hypoCalcModal').height();
	        	$('input.hypoCalculatorEmailFullname').focus();
        	}
        });
    });

    $('.hypoCalculatorEmailButtonSend').click(function() {

        $('.hypoCalculatorEmailErrors').css('display', 'none');
        $('.hypoCalculatorEmailErrors').html('');
        $('.hypoCalculatorEmailMessage').css('display', 'none');
        $('.hypoCalculatorEmailMessage').html('');

        formVars = {};
        formVars['random'] = new Date().getTime();
        formVars['ajax'] = 1;
        formVars['ajaxAction'] = 'sendEmail';
        formVars['propertyPrice'] = $('.hypoCalculatorPropertyPrice').val();
        formVars['ownFunds'] = $('.hypoCalculatorOwnFunds').val();
        formVars['loanMaturity'] = $('.hypoCalculatorLoanMaturity').val();
        formVars['loanAmount'] = $('.hypoCalculatorLoanAmount').val();
        formVars['interestRate'] = $('.hypoCalculatorInterestRate').val();
        formVars['monthlyPayment'] = $('.hypoCalculatorMonthlyPayment').val();
        formVars['fullname'] = $('.hypoCalculatorEmailFullname').val();
        formVars['phoneNumber'] = $('.hypoCalculatorEmailPhoneNumber').val();
        ajaxUrl = '/cs/web/ajax/hypocalculator/';

        $.ajax({
            type: 'GET',
            timeout: 30,
            url: ajaxUrl,
            data: formVars,
            async: false,
            dataType: 'xml',
            success: function(xmlResponse){
                if ($(xmlResponse).find('response').length > 0) {
                    if ($(xmlResponse).find('result').text() == 1) {
                        $('.hypoCalculatorEmailModalWrapper').slideUp();
                        $('.hypoCalculatorEmailMessage').html($(xmlResponse).find('messages').text());
                        $('.hypoCalculatorEmailMessage').css('display', 'block');
                        $('.hypoCalculatorEmailFullname').val('');
                        $('.hypoCalculatorEmailPhoneNumber').val('');
                    } else {
                        $('.hypoCalculatorEmailErrors').html($(xmlResponse).find('messages').text());
                        $('.hypoCalculatorEmailErrors').css('display', 'block');
                    }

                }
            },
            error: function(err){
            	if ((err.status != 200) && (typeof(err.statusText) != 'undefined') && (err.statusText != '')) {

            	}
            }
        });

    });

    $('input.hypocalcBtn').click(function() {

        var hcWidgetPropertyPrice = $('#price').val();
        var hcWidgetOwnFunds = $('#ownInvest').val();
        var hcWidgetLoanMaturity = $('#yearSelect').val();

        $('.hypoCalculatorErrors').css('display', 'none');
        $('.hypoCalculatorErrors').html('');
        $('.hypoCalculatorEmailErrors').css('display', 'none');
        $('.hypoCalculatorEmailErrors').html('');
        $('.hypoCalculatorEmailMessage').css('display', 'none');
        $('.hypoCalculatorEmailMessage').html('');

        $('.hypoCalculatorPropertyPrice').val(hcWidgetPropertyPrice);
        $('.hypoCalculatorOwnFunds').val(hcWidgetOwnFunds);
        $('.hypoCalculatorLoanMaturity').val(hcWidgetLoanMaturity);

        $('.hypoCalculatorLoanAmount').val('');
        $('.hypoCalculatorInterestRate').val('');
        $('.hypoCalculatorMonthlyPayment').val('');

        $('.hypoCalculatorButtonCalculate').trigger('click');

        tb_show('', '#TB_inline?height=390&width=470&inlineId=hiddenModalContentHypoCalculator');
        return false;
    });

    $('.hypoCalculatorButtonCalculate').click(function() {

        var hcPropertyPrice = $('.hypoCalculatorPropertyPrice').val();
        var hcOwnFunds = $('.hypoCalculatorOwnFunds').val();
        var hcLoanMaturity = $('.hypoCalculatorLoanMaturity').val();
        var hcLoanAmount = 0;
        var hcInterestRate = 0;
        var hcMonthlyPayment = 0;

        if (hcOwnFunds == '') {
            hcOwnFunds = 0;
        }

        $('.hypoCalculatorErrors').css('display', 'none');

        if (hcPropertyPrice == '') {
            $('.hypoCalculatorErrors').html(hypoCalculatorTranslations.errorPropertyNoteEmpty);
            $('.hypoCalculatorErrors').css('display', 'block');
        } else if (isNaN(hcPropertyPrice) || (hcPropertyPrice < 0)) {
            $('.hypoCalculatorErrors').html(hypoCalculatorTranslations.errorPropertyNoteWrong);
            $('.hypoCalculatorErrors').css('display', 'block');
        } else if (isNaN(hcOwnFunds) || (hcOwnFunds < 0)) {
            $('.hypoCalculatorErrors').html(hypoCalculatorTranslations.errorOwnFundsWrong);
            $('.hypoCalculatorErrors').css('display', 'block');
        } else if (isNaN(hcLoanMaturity)) {
            $('.hypoCalculatorErrors').html(hypoCalculatorTranslations.errorLoanMaturityWrong);
            $('.hypoCalculatorErrors').css('display', 'block');
        } else {

            hcLoanAmount = hcPropertyPrice - hcOwnFunds;

            if ((hcLoanAmount / hcPropertyPrice) > 0.8) {
                hcInterestRate = parseFloat(hypoCalculatorTranslations.annualInterestRateHigher);
            } else {
                hcInterestRate = parseFloat(hypoCalculatorTranslations.annualInterestRateLower);
            }

            if (isNaN(hcInterestRate)) {
                return false;
            }

            var hcTempValue = 1 / (1 + (hcInterestRate * 0.01 / 12));

            hcMonthlyPayment = ((1 - hcTempValue) * hcLoanAmount) / (hcTempValue * (1 - Math.pow(hcTempValue, hcLoanMaturity * 12)));

            hcMonthlyPayment = Math.round(hcMonthlyPayment);

        }

        $('.hypoCalculatorLoanAmount').val(hcLoanAmount);
        $('.hypoCalculatorInterestRate').val(hcInterestRate);
        $('.hypoCalculatorMonthlyPayment').val(hcMonthlyPayment);

        return false;
    });

});

function kbNewWin(src,name,w,h,prop,lp,tp) {
	if ((!w && !h) && (lp && tp)) {
		w = screen.width - (lp * 2);
		h = screen.height - (tp * 2) - tp;
		tp = tp / 2;
	} else if ((w && h) && (!lp && !tp)) {
		lp = (screen.width - w) / 2;
		tp = (screen.height - h) / 2;
	}
	prop = (!prop)? "" : prop+",";
	prop += (!w && !h)? "" : "width="+w+",height="+h+",left="+lp+",top="+tp;
	Win = window.open(src,name,prop);
	Win.focus();
}

function kbCalc () {
    var xPriceId = 'price';
	var xOwnInvestId = 'ownInvest';
	var xYearSelectId = 'yearSelect';

    var kbCena = 0;
	var kbSporeni = 0;
	var kbSplatnost = 0;

        // PARSE PRICE
		try {
			kbCena = intval(parseInt(trimText(document.getElementById(xPriceId).value)));
		} catch (priceError) {
			kbCena = 0;
		}

		// PARSE OWN INVEST
		try {
			kbSporeni = intval(parseInt(trimText(document.getElementById(xOwnInvestId).value)));
		} catch (investError) {
			kbSporeni = 0;
		}

		// PARSE YEAR
		try {
			kbSplatnost = intval(parseInt(document.getElementById(xYearSelectId).options[document.getElementById(xYearSelectId).selectedIndex].value));
		} catch (yearError) {
			kbSplatnost = 0;
		}

	kbNewWin('http:\x2f\x2fwww.kb.cz\x2fcs\x2fapp\x2fmort_calc.shtml?rates=3&cena='+kbCena+'&sporeni='+kbSporeni+'&splatnost='+kbSplatnost,'kbMortCalc',467,405,'status=yes');
}


function intval(mixed_var,base) {
    var tmp;
 
    var type = typeof(mixed_var);
 
    if(type == 'boolean'){
        if (mixed_var == true) {
            return 1;
        } else {
            return 0;
        }
    } else if(type == 'string'){
        tmp = parseInt(mixed_var * 1);
        if(isNaN(tmp) || !isFinite(tmp)){
            return 0;
        } else{
            return tmp.toString(base || 10);
        }
    } else if(type == 'number' && isFinite(mixed_var) ){
        return Math.floor(mixed_var);
    } else{
        return 0;
    }
}

function trimText(mixed_var) {
	mixed_var = mixed_var.replace (/\s+/g, '');
	return mixed_var;
}
