$(document).ready(function(){
    
        // Create your event handlers
        function myHandler(e) {
            //$('.more').live("click",function()
            //{
                var ID = $(this).attr("id");
                
                if(ID)
                {
                    $("#more"+ID).html('<img src="/images/moreajax.png" />');
                    var category = jQuery.query.get('category');
                    var offset = ID;
                    var price = jQuery.query.get('price');
                    var region = jQuery.query.get('region');

                    if (jQuery.query.get('status')) {
                        var status = jQuery.query.get('status');
                    } else {
                        var status = $.trim($("#status-div").html());
                    }
                    if (jQuery.query.get('sort')) {
                        var sort = jQuery.query.get('sort');
                    } else {
                        var sort = $.trim($("#sort-div").html());
                    }
                    
                    var datastring = "category=" + category + "&offset=" + offset + "&price=" + price + "&region=" + region + "&status=" + status + '&sort=' + sort;
                    $.ajax({
                        type: "POST",
                        url: "zoek-ajax",
                        data: datastring,
                        //data: window.location.search.substring(1),
                        cache: false,
                        success: function(html){
                            $("#galerijzelf").append(html);
                            $("#"+ID).remove(); // removing old more button
                            //$(this).remove(); // removing old more button
                        }
                    });
                }
                else
                {
                    $(".morebox").remove();// no results
                }
                
                return false;
            //}
        //);
        }
        // Inside DOM-Loaded event
        $('.more')
           // Bind events to your handlers
           .bind('enterviewport', myHandler)
           //.bind('leaveviewport', myHandler)
           // Initialize the plug-in
           .bullseye();
           
        if ($("a[rel='vergroot']").length) {
            $("a[rel='vergroot']").colorbox();
            $("a.showthepicts").click(function(){
                    //alert(test);
                    $("ul.fotos li a:first-child").click();
            });
        }
        if ($("a#showmap").length) {
            $("a#showmap").colorbox({innerWidth:978, innerHeight:610, transition:"none", iframe:true});
        }

	$("form.jqtransform").jqTransform();
	$("select#form-status").change(function(){
		$("select#form-price option:first-child").attr("selected", true);
		//alert($("select#form-price option:first-child").text());
		$("select#form-price").prev().text($("select#form-price option:first-child").text());
	});
	$("div#topNav a").mouseover(function(){
		if($("div#"+ 'tehuur' +"Container").length && ($(this).attr("id") == 'menu-te huur')) {
			$("div#"+ 'tehuur' +"Container").fadeIn();
			$("div#"+ 'tehuur' +"Container div").fadeIn();
		}
	});
	$("div#topNav a.not, div#subnav a, div#contentMid, #wow-Wrap").mouseover(function(){
		//$("div#topNavSubs div").fadeOut();
	});
	$("div#contentMid").mouseover(function(){
		$("div#topNavSubs div").fadeOut();
	});

	$("div#subnav a").click(function(){
		if($("div#"+ $(this).attr("title") +"Container").length) {
			$("div#"+ $(this).attr("title") +"Container").fadeIn();
			$("div#"+ $(this).attr("title") +"Container div").fadeIn();
		}
	});
	$("a.close").click(function(){
		if($("div#"+ $(this).attr("title") +"Container").length) {
			$("div#"+ $(this).attr("title") +"Container").fadeOut();
		}
	});
	//var p = $("p:first");
	//var position = $("#mijnaccount").position();
	//alert( "left: " + position.left + ", top: " + position.top );
	//$("p:last").text( "left: " + position.left + ", top: " + position.top );
	//var stuff = $('#mijnaccount').css("left");
	//alert($('#mijnaccount').css("left"));

	$("div#subNavSubsMenu").css('width',$('a#mijnaccount').outerWidth()-2);
	/*
	slidemyaccount = true;
	$('a#mijnaccount').click(function(){
		if (slidemyaccount == true){
			$("div#subNavSubsMenu").slideDown();
			slidemyaccount = false;
		} else {
			$("div#subNavSubsMenu").slideUp();
			slidemyaccount = true;
		}
		return false;
	});
	*/
	$('a#mijnaccount').click(function(){
		//return false;
	});
	$('div#mijnaccountWrap').mouseover(function(){
		$("a#mijnaccount").addClass("mijnacount-h");
	});
	$('div#mijnaccountWrap').mouseout(function(){
		$("a#mijnaccount").removeClass("mijnacount-h");
	});
	
	$("div#mijnaccountWrap").hoverIntent(makeTall,makeShort);
	function makeTall(){ $("div#subNavSubsMenu").slideDown();}
	function makeShort(){ $("div#subNavSubsMenu").slideUp();}
	
	$("#demo2 li").hoverIntent(makeTall,makeShort);

	$("#mijnaccountWrap div").hoverIntent( makeTall, makeShort )
	/*
	$('div#mijnaccountWrap666').mouseout(function(e){
		$("a#mijnaccount").removeClass("mijnacount-h");
		alert(e.target.tagName);
		if(e.target.tagName != "A")	{
			$("div#subNavSubsMenu").slideUp();
			slidemyaccount = true;
		}
	});
	*/
});
$(function() {
    $("input.hint, textarea.hint").hint();
});

var cambier = {
    map: null,
    
    init : function() {
        
        //SimpleMaps
        this.bindOfficesSimpleMap();
        this.bindEstatesSimpleMap();
        this.bindOfficeSimpleMap();
        this.bindEstateSimpleMap();
        
        this.bindHintOnTextfieldsWithTitle();
        this.bindPopupOnReferenceLink();
        this.bindTargetBlankOnExternalLinks();
        this.bindLinkOnSubmitOfficeLink();
        this.bindEstatePictures();
        this.bindTab();
        this.bindCalculateMort();
        this.bindCalculateMortOnLOad();
        this.bindTwitterFeed();
        this.bindjqTransformOnOfficesSelect();
        this.bindOfficePeople();
        this.bindLinkOnSearchContact();
        this.bindjqTransformOnYearSelect();
        this.bindCycleSlideshowOnCycleDiv();
    },
    
    bindOfficesSimpleMap : function() {
        if($('div.kantorenMap').length && $('div#map').length) {
            this.map = new simpleMap({
                adres:"contact/kantorenjson",
                zoom: 9
            });
        }
    },
    
    bindEstatesSimpleMap : function() {
        if($('div.estatesMap').length && $('div.map').length) {
            this.map = new simpleMap({
                adres:'/nl/vastgoed/json' + window.location.search,
                clustering: false,
                zoom: 10
            });
        }
    },
    
    bindOfficeSimpleMap : function() {
        if($('div.kantoormap').length && $('div#map').length) {
            var self = this;
            self.map = new simpleMap({
                adres: '/kantoren/kantorenjson/locatie/' + $('span.kantoorid').html(),
                clustering: false,
                directions: true,
                zoom: 17
            });
            
            $('form').submit(function(e) {
                e.preventDefault();

                var ua = $('input[name="address"]').val()+" "+$('input[name="place"]').val();

                self.map.showDirections({
                    from:ua,
                    onSuccess:function() {
                        $('#printLink, #hideDirections').show();
                    }
                });
            });
            
            $('#hideDirections').click(function(e) {
                e.preventDefault();
                self.map.hideDirections();
                $('#printLink, #hideDirections').hide();
            });
            
            $('#printLink').click(function() {
                window.open('/printMap.html', 'Heeren &amp; Hillewaere', 'status=1,toolbar=0,width=600');
                return false;
            });
        }
    },
    
    bindEstateSimpleMap : function() {
        if($('div#regioplan').length && $('div#map').length) {
            var self = this;

            self.map = new simpleMap({
                adres: '/nl/vastgoed/detailjson/id/' + window.parent.document.getElementById('estateid').innerHTML,
                clustering: false,
                directions: true,
                zoom: 16
            });

            $('form').submit(function(e) {
                e.preventDefault();

                var ua = $('input[name="address"]').val()+" "+$('input[name="place"]').val();

                self.map.showDirections({
                    from:ua,
                    onSuccess:function() {
                        $('#printLink, #hideDirections').show();
                    }
                });
            });

            $('#hideDirections').click(function(e) {
                e.preventDefault();
                self.map.hideDirections();
                $('#printLink, #hideDirections').hide();
            });

            $('#printLink').click(function() {
                window.open('/printMap.html', 'Heeren &amp; Hillewaere', 'status=1,toolbar=0,width=600');
                return false;
            });
        }
    },

    bindHintOnTextfieldsWithTitle : function() {
        $('input[title!=""]').hint();
    },
    
    bindPopupOnReferenceLink : function() {
        if($('a.reference').length) {
            $('a.reference').click(function() {
                $('div.referencebox').slideToggle();
            });
            
            $('div.closePopup').click(function() {
                $('div.referencebox').slideToggle();
            });
            
            $('.submit').click(function() {
                window.location = '/vastgoed/' + $('input#referenceNumber').val() + '/referentie/';
            });
        }
    },
    
    bindTargetBlankOnExternalLinks : function() {
        /*
         * If the href of the link begins with http or https and has an external hostname, open new window.
         */
        $('a[href^=http], a[href^=https]').each(
            function(){
              if(this.href.indexOf(location.hostname) == -1) {
                $(this).attr('target', '_blank');
              }
            }
        )
    },
    
    bindLinkOnSubmitOfficeLink : function() {
        if($('a.submitOffice').length) {
            $('a.submitOffice').click(function() {
                window.location = $('select[name="office"]').val();
            })
        }
    },
    
    bindEstatePictures : function () {
        if($('.pikawrapitall').length) {
            $("#pikame").PikaChoose({autoPlay:true,transition:[1]});
            //$("#pikame").PikaChoose({autoPlay:true,/*speed:200,animationSpeed:0,carousel:true*/});
            $(".pikawrapitall").removeClass("DN");
			$('.pikawrapitall').clone().appendTo('#pict4print');
			$('#pict4print ul#pikame').attr('id','pikaPrint');
			$('#pikaPrint li div.clip img').removeAttr('style');
			$('#pikaPrint li div.clip').attr('style','text-align:center;');
			$('#pikaPrint li div.clip img').attr('style','height:100%;');
			
        }
    },

    bindTab : function() {
        if($("div#galFilterInside div.tab a").length) {
            var self = this;
            $("div#galFilterInside div.tab a").click(function(e){
                e.preventDefault();
                $("div#galFilterInside div.active").removeClass("active");
                $(this).parent().addClass("active");
                $("#variContent>div").addClass("DNIMP");
                $("div"+ $(this).attr('href') +"").removeClass("DNIMP").fadeIn();
                if ($(this).attr("title") == "regioplan") {
                    self.map.refresh();
                }
            });
        }
    },
    
    bindCalculateMort : function() {
        if($('div#financieel').length) {
            $('input#buttonLening').click(function() {
                
                var capital = $('input#amount').val();
                var interest = $('input#interest').val();
                var plazo = $('select#years').val();
                var ownMoney = $('input#ownMoney').val();
                var check = parseInt(plazo);
                
                if (!isNaN(check)){
                    $('select#years').val(check);
                } else {
                    alert("Aantal jaar: enkel cijfers.");
                    return false;
                }
                if (isNaN(capital)){
                    alert("Te lenen bedrag: enkel cijfers.");
                    return false;
                }
                if(interest <= 0) {
                    alert('Interest: vul een cijfer in dit groter is dan 0.0');
                    return false;
                }
                if (isNaN(interest)){
                    alert("Interest: enkel cijfers. Voor decimale waardes een punt gebruiken ipv een komma (bv: 4.3 ipv 4,3)");
                    return false;
                }
                if(isNaN(ownMoney)) {
                    alert('Eigen inbreng: enkel cijfers.');
                    return false;
                }
                var monthly = capital * (interest / 100) / 12;
                interest = interest / 12;
                plazo = plazo * 12 * (-1);
                var payment = ((capital - ownMoney) * interest)/(100 * (1 - Math.pow(1 + (interest/100),plazo)));
                payment = parseInt(payment);

                $('span#payment').html("&euro; "+payment);
                return true;
            })
        }
    },
    
    bindCalculateMortOnLOad : function() {
        if($('div#financieel').length) {
            $('input#buttonLening').click();
        }
    },
    
    bindTwitterFeed : function() {
        if (typeof $("testelement").tweet == "function") {
            $(".tweet").tweet({
                username: "HHvastgoed",
                join_text: null,
                avatar_size: 50,
                count: 2,
                auto_join_text_default: "deelden we ",
                auto_join_text_ed: "we ",
                auto_join_text_ing: "waren we ",
                auto_join_text_reply: "antwoorden we aan ",
                auto_join_text_url: "bekeken we ",
                loading_text: "tweets laden..."
            });
        }
    },
    
    bindjqTransformOnOfficesSelect : function() {
        if($('form#submitOffice').length) {
            $('form#submitOffice').jqTransform({imgPath:'jqtransformplugin/img/'});
        }
    },
    
    bindOfficePeople : function() {
        if($('.humanwrapper').length) {
            $('.humanwrapper').children().each(function(index, child) {
                if(child.className == 'human') {
                    var persoonid = $('span#persoonid', child).html();
                    $(child).colorbox({width:900, inline:true, href:"#persoon_" + persoonid});
                }
            });
        }
    },
    
    bindLinkOnSearchContact : function() {
        if($('.hoogte').length) {
            $('.hoogte').css('cursor', 'pointer');
            $('.hoogte').click(function() {
                window.location = $('.hoogtelink', '.hoogte').attr('href');
            });
        }
    },
    
    bindjqTransformOnYearSelect : function() {
        if($('.yearSelect').length) {
            $('#financialForm').jqTransform({imgPath:'jqtransformplugin/img/'});
        }
    },
    
    bindCycleSlideshowOnCycleDiv : function() {
        if($('div.cycle').length) {
            $('div.cycle').cycle({
                fx: 'fade'
            });
        }
    }
}

