var tableFilter = {
    tableData: [],
    filters: [],

    init: function() {
        var myTableData = this.tableData;
        $('#allHouses tbody tr .hausinfo').each(function() {
                var hausInfoStr  = $(this).attr('title');
                var hausInfo = hausInfoStr.split('|');        

                //var haus = hausInfo[0];
                //var geschoss = hausInfo[1];
                //var lage = hausInfo[2];
                //var zimmer = hausInfo[3];
                //var wohnflaeche = hausInfo[4];
                //var rowId = hausInfo[5];

                myTableData[hausInfo[5]] = hausInfo;
        });
        

        this.doFilters();
    },
    addFilter: function(func) {
        this.filters.push(func);
    },
    doFilters: function() {
        // zunaechst alle verstecken:
        $('#allHouses tbody tr').hide();

        var i;
        for(i=0;i<this.tableData.length;i++) {
            var x;
            var allValid = true;
            for (x=0;x<this.filters.length;x++) {
                var isValid = this.filters[x](this.tableData[i]);
                if (!isValid) {
                    allValid = false;
                    
                }
            }
            if (allValid === true) {
                $('#allHouses tbody .wohnung'+i).show();
            }
        }

        // Update tablesorter...
        $("#allHouses").trigger("update");
        $("#allHouses").trigger("appendCache");
    }
};

tableFilter.addFilter(function(row) {
    // Filtere anhand des selktierten hauses

    var selectedHaus = $('select[name="haus"]').val();

    if (selectedHaus === 'all') {
        return true;
    }

    if (selectedHaus === row[0]) {
        return true;
    }
    return false;
});

tableFilter.addFilter(function(row) {
    // Filtere anhand des Zimmers

    var selectedZimmer = $('select[name="zimmer"]').val();

    if (selectedZimmer === 'all') {
        return true;
    }

    if (selectedZimmer === row[3]) {
        return true;
        
    }
    return false;
});

tableFilter.addFilter(function(row) {
    // Filtere anhand der Wohnflaeche

    var selectedWohnflaechenRange = $('select[name="wohnflaeche"]').val();

    if (selectedWohnflaechenRange === 'all') {
        return true;
    }

    var wohnflaecheInfo = selectedWohnflaechenRange.split('|');   

    var von = wohnflaecheInfo[0];
    var bis = wohnflaecheInfo[1];
    
    if (von <= row[4] && bis > row[4]) {
        return true;
    }

    return false;
});

tableFilter.addFilter(function(row) {
    // Filtere anhand des Geschosses
    var selectedGeschoss = $('select[name="geschoss"]').val();

    if (selectedGeschoss === 'all') {
        return true;
    }

    if (selectedGeschoss === row[1]) {
        return true;
    }
    return false;
});

function fadeOut() {
	$('#layer').fadeOut();
	$("body").css("overflow", "auto");
}

$(document).ready(function() {

    $('img[id="webcam"]').each(function() {
        setInterval(function() {
            $('#webcam').attr('src', 'http://178.63.3.159/record/current.jpg?rand=' + (Math.random()*1000).toString());
            $('#webcam').css('width', '640px');
            $('#webcam').css('height', '480px');
        }, 600000);
    });


	//$(" #nav ul ").css({display: "none"}); // Opera Fix
	$("#navigation .nav_level_1_dropdown").hover(function(){
			$(this).find('ul:first').css({visibility: "visible",display: "none"}).fadeIn();
			$(this).children('a:first').addClass('dropdownActive');
	},function(){
			$(this).find('ul:first').css({visibility: "hidden"});
			$(this).children('a:first').removeClass('dropdownActive');
			Cufon.replace('#navigation ul li a', { fontFamily: 'TSTAR-Regular', hover: true });
	});

	$("#navigation .dropdown").click(function() { return false; });
	$("[href=#]").click(function() { return false; })

    $('meta[name="pagealias"]').each(function() {
	var currentPage = $(this).attr('content'); 
		if (currentPage === 'news') {
			  var currentMonth = $('#currentMonth').val();
			  var currentYear = $('#currentMonth').val();

			  $('.date > li > a').bind('click', function() {
			    var linkContent = $(this).html();

			    var monthYear =  linkContent.split(" ");

			    var month = monthYear[0];
			    var year = monthYear[1];

			    if (year === currentYear && month === currentMonth) {
			      return false;
			    } else {
			      $('.date .current~ul').slideUp();
			      $('.date .current').removeClass('current');
			      $(this).parent().children('ul:first').slideDown();
			      $(this).addClass('current');

			      currentYear = year;
			      currentMonth = month;
			    }

			    return false;
			  });
		} else if (currentPage === 'kontakt') {

		    $('#submitform').bind('click', function() {
			$('#f1').submit();
			return false;
		    });
		
		    $('#f1').validate({
			rules: {
			    vorname: {
			    required: true
			},
			    nachname: {
			    required: true
			},
			    telefon: {
			    required: true
			},
			    nachricht: {
			    required: true
			},
			    email: {
			    required: true,
			    email: true
			}
		    },
		    submitHandler: function (form) {

			$('#f1').ajaxSubmit();
			$('#contactForm').fadeOut(function() {
			    $('#contactForm').html('<h2>Nachricht versendet!</h2><p>Vielen Dank für Ihre Mitteilung, wir werden uns in Kürze melden.</p>');
			    $('#contactForm').fadeIn();
			});
			return false;
		    },
		    invalidHandler: function(form, validator) {
			//console.log('Form invalide');;
			return false;
		    },
		    messages: {
			vorname: "",
			nachname: "",
			telefon: "",
			nachricht: "",
			email: ""
		    },
		    errorClass: 'fail',
		    validClass: ''
		 });
		
		} else if (currentPage === 'startseite') {
			$(window).bind('resize', function() {
				//console.log('resize');
				$('#layer').css('width', '100%');
				$('#layer').css('height', '100%');
			});
		} else if (currentPage === 'lageplan') {
			$('#lageplanmap area').bind('mouseenter', function() {
				var overlayId = $(this).attr('title');
				$('#lageplan_overlay_'+overlayId).show();
				//console.log('mouseenter');
			});

 			$('#lageplanmap area').bind('mouseleave', function() {
				var overlayId = $(this).attr('title');
				$('#lageplan_overlay_'+overlayId).hide();
				//console.log('leave');
			});

			$('.lageplan_overlay').bind('mouseenter', function() {
				$(this).show();
			});

			$('.lageplan_overlay').bind('mouseleave', function() {
				$(this).hide();
			});

		} else if (currentPage === 'immobilienuebersicht') {
            $.tablesorter.addParser({ 
                // set a unique id 
                id: 'wohnflaeche', 
                is: function(s) { 
                    // return false so this parser is not auto detected 
                    return false; 
                 }, 
                 format: function(s) { 
                    // format your data for normalization 
                    return s.toLowerCase().replace(/\sqm/,'').replace(/,/,'.'); 
                }, 
                // set type, either numeric or text 
                type: 'numeric' 
            }); 

           
            $("#allHouses").tablesorter({
                        sortList: [[0,0], [1,0]],
                        widgets: ['zebra'],
                        widgetZebra:  {css: ['light', '']},
                        headers: {
                            2: {sorter: 'wohnflaeche'},
                            4: {sorter: false},
                            5: {sorter: false}
                        }
            });

            tableFilter.init();
            $('select[name="haus"], select[name="zimmer"], select[name="wohnflaeche"], select[name="geschoss"]').bind('change', function() {
                tableFilter.doFilters();
            });

            $('#allHouses tbody tr').bind('mouseover', function() {
                $(this).children('.hausinfo').each(function() { 
                    var hausInfoStr  = $(this).attr('title');
                    var hausInfo = hausInfoStr.split('|');
                    var haus = hausInfo[0];
                    var geschoss = hausInfo[1];
                    var lage = hausInfo[2];
                    
                    //immo.showWohnung(haus, geschoss, lage);
                });
            });

            $('#allHouses tbody').bind('mouseout', function() {
                var curSelection = $('select[name="haus"]').val();
                if (curSelection === 'all') {
                    //immo.showDefault();
                } else {
                    //immo.showDefaultHouse(curSelection);
                }
            });
 
        }
	});
});

