/*global is24: false, jQuery:false, window:false, google:false */

/*jslint white: true, browser: true, devel: true, widget: true, onevar: false, undef: false, nomen: true, eqeqeq: true, plusplus: false, bitwise: true, regexp: false, strict: true, newcap: true, immed: true */

"use strict";

// Global namespace
window.de = window.de || {};
de.is24 = de.is24 || {};
de.is24.meinebaufi = de.is24.meinebaufi || {};

// ===================================== Utility stuff

de.is24.meinebaufi.utils = de.is24.meinebaufi.utils || {};

/**
 * Function to hide the first element and show the second element afterwards.
 * Both hide and show are performed using a smooth fade.
 * 
 * @param elementToHide
 *            [string] jQuery expression to select the element to hide
 * @param elementToShow
 *            [string] jQuery expression to select the element to show
 */
de.is24.meinebaufi.utils.hideAndShow = function (elementToHide, elementToShow) {
	jQuery(elementToHide).fadeOut(150, function () { 
		jQuery(elementToShow).fadeIn(250);
	});	
};

de.is24.meinebaufi.utils.FancySelect = function (elementSelector) {
	var selectElement = jQuery(elementSelector);

	jQuery(elementSelector).change(function () {
		var selectedOptionText = selectElement.find("option:selected").text();
		selectElement.parent().find(".fake_beschriftung").text(selectedOptionText);
	});

	selectElement.change();
};

// ===================================== Homepage stuff

de.is24.meinebaufi.homepage = de.is24.meinebaufi.homepage || {};

/**
 * @constructor Object that backs the financing project teaser table on the home
 *              page. Schedules and performs the rotation.
 * @param totalItems
 *            [integer] number of items taking part in the teaser rotation
 * @param rotationIntervalInMilliSeconds
 *            [integer] time to wait between rotations of the financing project
 *            table.
 * @param disableAutomaticRotation [boolean] disable the automatic rotation
 */
de.is24.meinebaufi.homepage.FinancingProjectTeaser = function (totalItems, rotationIntervalInMilliSeconds, disableAutomaticRotation) {
	var that = this;

	var maxIndex = totalItems - 1;
	var firstVisibleIndex = 0;
	var lastVisibleIndex = 4;

	this.rotate = function () {
		if (lastVisibleIndex >= maxIndex) {
			firstVisibleIndex = 0;
			lastVisibleIndex = 4;
		} else {
			firstVisibleIndex++;
			lastVisibleIndex++;
		}
		
		jQuery('.tabItem').hide();
		
		for (var index = firstVisibleIndex; index <= lastVisibleIndex; ++index) {
			jQuery('#teaserFinancingProject_' + index).show();
		}
	};
  
	if (!disableAutomaticRotation) {
		setInterval(function () {
			that.rotate();	  
		}, rotationIntervalInMilliSeconds);
	}
};

de.is24.meinebaufi.homepage.InterestRateTrendTeaser = function (loaderDiv, widgetBody, updateDiv) {
	
	var showLoanTermTrend = function (loanTerm, nominalInterestRate, nominalInterestRateTrend, effectiveInterestRate, effectiveInterestRateTrend) {
		if (!nominalInterestRate) {
			nominalInterestRate = '??';
		}
		if (!effectiveInterestRate) {
			effectiveInterestRate = '??';
		}

		widgetBody.append(
			'<div class="interestRateTrendReportItem">' +
			'<div class="col1 first">' + loanTerm + ' Jahre</div>' +
			'<div class="col2 trend_' + nominalInterestRateTrend + '">' + nominalInterestRate + ' %<div>&nbsp;</div></div>' +
			'<div class="col3 trend_' + effectiveInterestRateTrend + '">' + effectiveInterestRate + ' %<div>&nbsp;</div></div>' +
			'<div class="clear"></div>' +
			'</div>');
	};
	
	var prefixZeroIfUnderTen = function (seconds) {
		if (seconds < 10) {
			return '0' + seconds;
		}
		
		return seconds;
	};
	
	var currentDateString = function () {
		var date = new Date();
		
		var dateString = prefixZeroIfUnderTen(date.getDate()) + '.' + prefixZeroIfUnderTen(date.getMonth() + 1) + '.' + date.getFullYear();
		var timeString = date.getHours() + ':' + prefixZeroIfUnderTen(date.getMinutes());
		
		return dateString + ', ' + timeString;
	};
	
	var handleAjaxResponse = function (responseXml) {		
		updateDiv.html('Stand vom: ' + currentDateString());
		
		loaderDiv.hide();
		widgetBody.show();
		
		jQuery(responseXml).find('interest-rate-trend-report').find('report-items').find('report-item').each(function () {
			var that = jQuery(this);
			showLoanTermTrend(
				that.find('loan-term').text(), 
				that.find('nominal-interest-rate').text(), 
				that.find('nominal-interest-rate-trend').text().toLowerCase(), 
				that.find('effective-interest-rate').text(), 
				that.find('effective-interest-rate-trend').text().toLowerCase());
		});
	};	
	
	jQuery.ajax({ 
		url: "rest/interestRateTrendReport",
		cache: false,
		context: document.body,
		dataType: 'xml',
		success: function (data) {
			handleAjaxResponse(data);
		}
	});	
};

// ========================= LEGACY CODE BELOW =================================


function initTooltips() {
    jQuery("img[alt='info']").tooltip({
        offset: [0, -3],
        relative: true
    });
    // see http://flowplayer.org/tools/forum/30/37281 for an explanation
    jQuery("img[alt='info']").live("mouseover", function () { 
        if (!jQuery(this).data("tooltip")) {
            var me = jQuery(this);
            if (!me.hasClass('decorated')) {
                me.tooltip({
                    offset: [0, -3],
                    relative: true,
                    api: true
                }).show();
                me.addClass('decorated');
            }
        }
    }); 
}

function initZinsangebotTooltips() {
    jQuery("div[class*='error']").tooltip({
        offset: [0, 0],
        relative: true
    });
    // see http://flowplayer.org/tools/forum/30/37281 for an explanation
    jQuery("div[class*='error']").live("mouseover", function () { 
        if (!jQuery(this).data("tooltip")) {
            var me = jQuery(this);
            if (!me.hasClass('decorated')) {
                me.tooltip({
                    offset: [0, 0],
                    relative: true,
                    api: true
                }).show();
                me.addClass('decorated');
            }
        }
    }); 
    jQuery("div[class*='missing']").tooltip({
        offset: [0, 0],
        relative: true
    });
    // see http://flowplayer.org/tools/forum/30/37281 for an explanation
    jQuery("div[class*='missing']").live("mouseover", function () { 
        if (!jQuery(this).data("tooltip")) {
            var me = jQuery(this);
            if (!me.hasClass('decorated')) {
                me.tooltip({
                    offset: [0, 0],
                    relative: true,
                    api: true
                }).show();
                me.addClass('decorated');
            }
        }
    }); 
}

function initSelects() {
    var selects = jQuery('select.styled');
    var i;
    // alert("Anzahl Selects:" + selects.length);
    for (i = 0; i < selects.length; i++) {
        var str = jQuery(selects[i]).find('option:selected').text();
        jQuery(selects[i]).parent().find('.fake_beschriftung').text(str);
    }
    initTooltips();
}

function initSlider(limit) {
    jQuery("#slider").slider({
        min: 2,
        max: limit * 2,
        slide: function (event, ui) {
            jQuery("input[name$='tilgungshoehe']").val((ui.value / 2.0).toString().replace('.', ','));
        },
        stop: function (event, ui) {
            jQuery("input[name$='tilgungshoehe']").val((ui.value / 2.0).toString().replace('.', ','));
            jQuery("input[name$='tilgungshoehe']").trigger('focus');
            jQuery("input[name$='tilgungshoehe']").trigger('blur'); 
        }
    });
    jQuery("#slider").slider("value", (jQuery("input[name$='tilgungshoehe']").val().replace(',', '.')) * 2);
}

function padDigits(n, totalDigits) {
    var pd = '';
    if (totalDigits > n.length && n.length > 0) {
        for (i = 0; i < (totalDigits - n.length); i++) {
            pd += '0';
        }
    }
    return pd + n;
}

var popupWindow;

function mbfpopup(url) {
    popupWindow = window.open(url, 'name', 
            'height=700,width=600,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no');
    if (popupWindow.focus) {
        popupWindow.focus();
    }
}

String.prototype.startsWith = function (str) {
	var result = this.match("^" + str);
    return result && result.toString() === str;
};

String.prototype.endsWith = function (str) {
	var result = this.match(str + "$");
    return result && result.toString() === str;
};

function fvdetail(fvid) {
    location.href = 'finanzierungsvorhaben_detail.seam?fvid='.concat(fvid).concat(
            '&amp;cid=#{conversation.id}&amp;conversationPropagation=join');
}

function fvdetailFiltered(mouseEvent, fvid) {
    var elementID;
    // if event doesn't exist,
    // use window.event
    if (!mouseEvent) {
        mouseEvent = window.event;
    }

    if (mouseEvent.target) {
        // get the id of the element that was clicked (firefox)
        elementID = mouseEvent.target.id;
    } else if (mouseEvent.srcElement) {
        // get the id of the element that was clicked (IE)
        elementID = mouseEvent.srcElement.id;
    }
    
    // perform the desired action UNLESS a checkbox or a link were clicked
    if (elementID.endsWith("checkbox")) {
        return;
    }
    if (elementID.endsWith("linka") || elementID.endsWith("linkua")) {
        return;
    }
    if (elementID.endsWith("linkf") || elementID.endsWith("linkuf")) {
        return;
    }
    if (elementID.endsWith("linkd") || elementID.endsWith("linkud")) {
        return;
    }

    fvdetail(fvid);
}

function initGreeting(smallGreeting) {
    var gwidth = jQuery("#greeting").width();
    if (gwidth > 300) {
        jQuery("#greeting").text(smallGreeting);
        while (jQuery("#greeting").width() > 300) {
            smallGreeting = smallGreeting.slice(0, -1);
            jQuery("#greeting").text(smallGreeting + "...");
        }
    }
    jQuery("#greeting").removeClass("hidden_field");
}

function pcto_dis() {
    if (document.createElement) { 
        var cto_dis_im = document.createElement('IFRAME');
        if (cto_dis_im) { 
            cto_dis_im.width = '1px'; 
            cto_dis_im.height = '1px'; 
            cto_dis_im.style.display = 'none'; 
            cto_dis_im.src = 'http://dis.criteo.com/dis/dis.aspx?p=1999&c=2&cb=' + Math.floor(Math.random() * 99999999999); 
            var cto_dis_doc = document.getElementById('pcto_dis_div'); 
            if (cto_dis_doc !== null && cto_dis_doc.appendChild) { 
                cto_dis_doc.appendChild(cto_dis_im);
            }
        }
    }
}

function criteo(id) {
    // Wee need to alias document here to baffle jslint
    var d = document;

    d.write('<div id="pcto_dis_div" style="display:none"></div>');
    d.write('<div style="display:none"><img src="http://immobilienscout24de.widget.criteo.com/pgi/display.js?p1=' +
            escape('v=2&wi=7711471&t=mb' + id + '&s=1&i1=MeineBaufi&p1=1&q1=1') + 
            '&t1=transaction&resptype=gif&cb=' + Math.floor(Math.random() * 99999999999) + 
            '" onload="pcto_dis();"/></div>');
}

function loadChart(contextPath, zr, rg, zb, ia, fo, bw) {
    var cdurl = contextPath + '/rest/chartdata?zr=' + zr;
    if (rg) {
        cdurl += '%26rg=' + rg;
    }
    if (zb) {
        cdurl += '%26zb=' + zb;
    }
    if (ia) {
        cdurl += '%26ia=' + ia;
    }
    if (fo) {
        cdurl += '%26fo=' + fo;
    }
    if (bw) {
        cdurl += '%26bw=' + bw;
    }
    swfobject.embedSWF(contextPath + "/open-flash-chart.swf", "my_chart", "700", "350", "9.0.0", "expressInstall.swf", {"data-file" : cdurl});
}

