﻿var areaInfoInited = false, mapInited = false, photocarousel = false;

function photoCarousel_initCallback(carousel) {
    $('.photoCarousel', $AreaInfoPanel).parents('li:eq(0)').removeClass("concertinaExpandDefault");
}

function AreaOnChange(expanded) {
    if (expanded) {
        if (!photocarousel) {
            var parent = $(this).parents("li:eq(0)");
            if (parent.attr("id").indexOf("Photos") > -1) {
                $('.photoCarouselList', $AreaInfoPanel).setUpPhotoCarousel().click(ViewMorePhotos);
                photocarousel = true;
            }
        }
    }
}

function ShowTab(e) {
    var panels = $('#TabPanels'), obj = $(this).parents('li:eq(0)');
    if (!panels.data('offsetTop')) { panels.data('offsetTop', Math.floor(panels.offset().top)); }
    var $window = $(window), winScroll = { top: $window.scrollTop(), left: $window.scrollLeft() };

    panels.removeClass().addClass(obj.attr('class'));
    if (panels.data('selectedtab')) { panels.data('selectedtab').removeClass('selected'); }
    else { obj.siblings().removeClass("selected"); };
    panels.data('selectedtab', obj.addClass('selected'));
    if (!areaInfoInited && obj.hasClass('btnAreaInfo')) {
        window.$AreaInfoPanel = $('#AreaInfoPanel');
        $('.concertina', $AreaInfoPanel).concertina({ onChange: AreaOnChange });
        areaInfoInited = true;
    }
    else if (obj.hasClass("btnMap") || obj.hasClass("btnStreetView")) {
    if (!mapInited && window.Maps) {
            Maps.prototype.handlePovChanged = function() { };
            FMAP.mapOptions.googleOptions = { disableDefaultUI: false, mapTypeControl: false };
            FMAP.streetview.panoOptions = {navigationControl: true}
            FMAP.InitMapWithStreetView();
            
          var shape = FMAP.plotShape(FMAP.mapOptions.center);
            mapInited = true;
        }
    
        if (FMAP) {
            if (obj.hasClass("btnStreetView")) {
                FMAP.setMapType(MapViewType.STREET, true, $('#streetviewbutton'));
            }
            else if (obj.hasClass("btnMap")) {
                               FMAP.setMapType(MapViewType.ROAD, true,$('#roadbutton'));
            }
        }

    }

    if (!arguments.callee.inProgress && (winScroll.top !== panels.data('offsetTop'))) {
        $('html, body').animate({ scrollLeft: winScroll.left, scrollTop: panels.data('offsetTop') - 30 }, 800, 'swing', function() { delete window.ShowTab.inProgress; });
        arguments.callee.inProgress = true;
    }

    return false;
}

if (Maps) {
    Maps.prototype.OverriddenSetMapType = Maps.prototype.setMapType;
    Maps.prototype.setMapType = function(map_type, showTypeView, target) {
        this.OverriddenSetMapType(map_type, showTypeView, target);

        var panels = $('#TabPanels'); obj = target;
        panels.removeClass();
 
        if (obj.attr("id") == 'streetviewbutton') {
            panels.addClass('btnStreetView');
        }
        else {
            panels.addClass('btnMap');
            this.SetCenterAndZoom(this.mapOptions.center, 15);
        }

        if (panels.data("selectedtab")) { panels.data("selectedtab").removeClass("selected") }
        else { $('li', '#MoreInfoButtons').removeClass("selected"); };
        panels.data("selectedtab", $('.' + panels.attr("class"), '#MoreInfoButtons').addClass("selected"));
    }
}



function ChangeImage(i) {
    $(this).mouseover(function(e) { DisplayImage(i, e); PrevNext(i); }).click(function() { return false; });
}

function ChangeImagePrevNext(i, e) {

    DisplayImage(i, e); 

    $('#PropertyThumbs').find('li:eq(' + i + ')').addClass("selected").siblings().removeClass("selected");
    
    PrevNext(i);
    return false;

}

function thumbsCarousel_initCallback(carousel) {
    $('#NextPhoto').attr("href", "#1").click(function(e) {
        var i = parseInt(this.href.split('#')[1]);
        if (isNaN(i)) { return false };
        var x = (i + 1) - (i % 3);
        carousel.scroll($.jcarousel.intval(parseInt(x)));
        return ChangeImagePrevNext(i, e);

    });

    $('#PrevPhoto').click(function(e) {
        var i = parseInt(this.href.split('#')[1]);
        if (isNaN(i)) { return false };
        var x = (i + 1) - (i % 3);
        carousel.scroll($.jcarousel.intval(parseInt(x)));
        return ChangeImagePrevNext(i, e, carousel);
    });
}


function PrevNext(i) {
    var x = 0;
    if (i < (imagearray.length-1)) {
        x = parseInt(i) + 1;
        $('#NextPhoto').attr("href", "#" + x).removeClass("next_disabled");
    } else {
    $('#NextPhoto').addClass("next_disabled").attr("href", "#");
    };

    if (i > 0) {
        x = parseInt(i) - 1;
        $('#PrevPhoto').attr("href", "#" + x).removeClass("prev_disabled");
    } else {
    $('#PrevPhoto').addClass("prev_disabled").attr("href", "#");
    
    };
 }

function ShowLocalityToolTip() {
    var obj = $(this);
    if (obj.find('.tooltip').length == 0) {

        var tooltipContent = obj.prev(".tooltipTable:eq(0)"), toolTip = $('<div class="tooltip"><div class="closer"></div></div>');
        if (tooltipContent) {
            tooltipContent.appendTo(toolTip);
            toolTip.appendTo(obj);
        }

    }

	return window.FAP.UI.openToolTip(obj);
}

/* image swapping code */

function imagedata(url, title, height, width) {
	this.url = url; 				// url of image
	this.title = title; 			// image title (alt text)
	this.height = height;			// image height
	this.width = width; 			// image width
}

var currentimage = 0; 			// current displayed image
var imageresize = false; 		// if the main image will resize (PhotoAlbum sets in ASPX code)


// display image n (0-based) using image control ctl and optional label (title)
function DisplayImage(n, e) {
	var ctl = $(".defaultPhotoImage", '#PropertyGallery')[0];
	var labelctl = document.getElementById('labelMainPhoto');
	if (ctl != null) {
		// is image within imagedata range
		if ((n >= 0) && (n < imagearray.length)) 
		{
		
		    ctl.src = imagearray[n].url;
		    ctl.title = imagearray[n].title;
		    // optionally resize
		    if (imageresize) {
			    ctl.width = imagearray[n].width;
			    ctl.height = imagearray[n].height;
		    };
		    // optional label control
		    if (labelctl != null) {
		        labelctl.innerHTML = imagearray[n].title;
		        currentimage = n;
		    };
    	};
	};
	//UpdateNavigation();
	if (!e) {
		e = window.event;

	}
	if (e) {
		target = (e.target) ? e.target : e.srcElement;
		$(target).parents('li:eq(0)').addClass("selected").siblings().removeClass("selected");

	}

}

var PropertyDetailsUI = {
    buttons: null,
    findButtons: function () { if (this.buttons == null) { this.buttons = $('#MoreInfoButtons'); } },

    InitTabs: function () {

        this.findButtons(); this.buttons.find('a').click(ShowTab);
    },
    InitScroll: function () {
        $('a.smoothScroll', '#PageBody').unbind('click').click(SmoothScroll);
    },
    InitStreetViewTab: function () {
        if (typeof FMAP !== 'undefined') {
            if (!FMAP.flash_support) {

                if (FMAP.mapOptions.center.toString() != "0,0") {

                    FMAP.PanoramaAvailable(FMAP.mapOptions.center, function (panoData, status) {
                        if (status !== 'OK') {
                            FMAP.streetview.hasStreetView = false;
                            PropertyDetailsUI.findButtons(); PropertyDetailsUI.buttons.find('.btnStreetView').empty().html('<span title="Street view not available">Street view</span>');
                        }
                    });
                }
            }
        }
    },
    InitModalUI: function () {
        PropertyDetailsUI.InitScroll();
        $('#PageMainContentFullWidth').click(function (e) {
            var $target = $(e.target);
            if ($target.hasClass('contactAgentModal')) { return ShowContactAgentModal.call(e.target); }
            else if ($target.parent().hasClass('contactAgentModal')) { return ShowContactAgentModal.call(e.target.parentNode); }
            else if ($target.hasClass("emailFriendModal")) { return ShowEmailFriendModal.call(e.target); }
            else if ($target.hasClass("emailAlert")) { return ShowEmailAlertModal.call(e.target); }
        })
    },
    InitCarouselDeselect: function () {
        $('#PageMainContentFullWidth').find('div.jcarousel-container').find('div.jcarousel-next, div.jcarousel-prev').bind('dblclick', window.FAP.UI.deselectAll);
    },
    InitThumbsCarousel: function () {
        $('#PropertyThumbs').find('a').each(ChangeImage).end().jcarousel({ scroll: 3, vertical: true, initCallback: thumbsCarousel_initCallback }).find('li:eq(0)').addClass('selected');
    },
    InitPropertyCarousel: function () {
        $('.propertyCarouselList').jcarousel({ scroll: 4 });
    }

}

var DevelopmentDetailsUI = {
    InitDevelopmentCarousel: function() {
       
        function showImageCount(e) {

            var $this = $(this);
            $this.find(".searchResultAgentLogo, .status").stop(true, true).fadeOut(500);
            $this.find(".photoCount").stop(true, true).fadeIn(500);

        }
        function hideImageCount(e) {

            var $this = $(this);
            $this.find(".searchResultAgentLogo, .status").stop(true, true).fadeIn(500);
            $this.find(".photoCount").stop(true, true).fadeOut(500);
        }

        function DeveloperItemFirstInCallback(carousel, item, idx, state) {
            var size = carousel.size(), scroll = carousel.options.scroll;
            if (size > scroll) {
                var devPage = 'Viewing ' + idx + ' to ' + (idx + scroll - 1) + ' of ' + size + ' properties',
                prevLink = $('#prev3Property'), nextLink = $('#next3Property'), developerPaging = $('#DeveloperPaging');

                developerPaging.html(devPage);
                if (idx == 1) {
                    prevLink.attr("disabled", true).addClass("prev_disabled");
                }
                else {
                    prevLink.removeAttr("disabled").removeClass("prev_disabled");
                    var j = scroll;
                    if (idx <= scroll) {
                         j = idx - 1;
                    }                   
                    prevLink.text("Previous " + j);

                }

                if (size <= (idx + scroll - 1)) {
                    nextLink.attr("disabled", true).addClass("next_disabled");
                }
                else {
                    nextLink.removeAttr("disabled").removeClass("next_disabled");
                    var i = size - idx - scroll + 1;
                    if (i > scroll) {
                        i = scroll;
                    }
                    nextLink.text("Next " + i);


                }
            } else {
                developerPaging.hide();
            }
        }
        function propertyCarousel_initCallback(carousel) {
            $('#next3Property').click(function(e) {
                carousel.next();
                return false;
            });

            $('#prev3Property').click(function(e) {
                carousel.prev();
                return false;
            });
        }



        $('#PageSubContent').find('ul.propertyCarouselList').jcarousel({ scroll: 3, itemFirstInCallback: DeveloperItemFirstInCallback, initCallback: propertyCarousel_initCallback }).find('.propImage').hover(showImageCount, hideImageCount);

    }
}
