// Installs hooks to add/remove placeholder text on given input element when focused/blurred
jQuery.fn.placeholder = function(text) {
    var waitingClass = 'waitingForInput';
    var waitingTextKey = 'waitingText';

    $(this).each(function() {
        var placeholder = text || $(this).val();
        $(this).data(waitingTextKey, placeholder);
        $(this).val(placeholder);
        $(this).addClass(waitingClass);
    });

    $(this).focus(function() {
        if ($(this).hasClass(waitingClass)) {
            $(this).removeClass(waitingClass);
            $(this).val('');
        }
    });

    $(this).blur(function() {
        if ($(this).val() == '') {
            $(this).addClass(waitingClass);
            $(this).val($(this).data(waitingTextKey));
        }
    });
};


function htmlEscape(value) {
    if (value == null) return "";
    return $("<div />").text(value).html();
}


$(document).ready(function () {

    $("a[rel=gallery]").fancybox({
        'cyclic': 'true',
        'titlePosition': 'outside',
        'overlayColor': '#000000',
        'overlayOpacity': 0.3
    });

    $(".economyThumbnail").fancybox({
        'overlayColor': '#000000',
        'overlayOpacity': 0.3
    });

    $(".endDate").datepicker({ dateFormat: 'dd.mm.yy' });

    $('.highlight ul').carousel({
        fluid: false,
        transition: 'fade',
        slideshow: 4,
        showArrows: false,
        showNavigation: true
    });

    $("#buildingAdditionalInfo").css("display", "none");
    $("#contactPhoneInfo").css("display", "none");

    showHideBuildingAdditionalInfo();

    $(".planningToBuild input").click(function () {
        showHideBuildingAdditionalInfo();
    });
    $(".notPlanningToBuild input").click(function () {
        showHideBuildingAdditionalInfo();
    });
    $(".currentlyBuilding input").click(function () {
        showHideBuildingAdditionalInfo();
    });

    $(".contactRequest input").click(function () {
        if ($(".contactRequest input").is(":checked")) {
            $("#contactPhoneInfo").show();
        }
        else {
            $("#contactPhoneInfo").hide();
        }
    });

    $("#houseModelSearch input").change(function () {
        updateResultCount("#houseModelSearch");
    });

    $("#villaModelSearch input").change(function () {
        updateResultCount("#villaModelSearch");
    });

    $("#outbuildingModelSearch input").change(function () {
        updateResultCount("#outbuildingModelSearch");
    });


    $('#mycarousel').jcarousel({
        wrap: 'circular'
    });
    createDropDown();

    $(".dropdown dt a").click(function () {
        $(".dropdown dd ul").toggle();
    });

    $(document).bind('click', function (e) {
        var $clicked = $(e.target);
        if (!$clicked.parents().hasClass("dropdown"))
            $(".dropdown dd ul").hide();
    });

    $(".dropdown dd ul li a").click(function () {
        var text = $(this).html();
        $(".dropdown dt a").html(text);
        $(".dropdown dd ul").hide();

        var source = $("#source");
        source.val($(this).find("span.value").html());
        selectLanguageSubmit($(this).find("span.value").html());
    });


    $('.toggleSubPages').click(function () {
        var $this = $(this);
        var subPages = $this.parent().children('.subPages');

        if ($this.hasClass('expand')) {
            $this.removeClass('expand');
            $this.addClass('contract');
        }
        else {
            $this.removeClass('contract');
            $this.addClass('expand');

        }

        subPages.slideToggle();

    });

    $('.infoContainer').hover(function () {
        $(this).children('.tooltip').toggle();
    });

    $('.searchphrase').placeholder();

    $('.floorPlan').click(function () {
        window.open($(this).attr('href'), 'floorPlanWindow', 'width=820, height=750, innerHeight=700, location=yes, menubar=no, status=no, titlebar=no, scrollbars=yes');
        return false;
    });

    $('.officeMapLink').click(function () {
        window.open($(this).attr('href'), 'officeMapWindow', 'width=820, height=750, innerHeight=700, location=yes, menubar=no, status=no, titlebar=no, scrollbars=yes');
        return false;
    });


    initPageGallery(".modelContent");
    initPageGallery(".modelCollectionContent");

    $("a[rel=carouselGallery]").fancybox({
        'title': $(this).attr(),
        'cyclic': 'true',
        'titlePosition': 'inside',
        'overlayColor': 'black',
        'overlayOpacity': 0.3
    });



    function submitSearch(form) {
        $(form).submit();
    }

    $("#upperPagination select").change(function () {
        $("#upperPagination").submit();
    });
    $("#lowerPagination select").change(function () {
        $("#lowerPagination").submit();
    });

    $("#showAdditionalInformation").click(function () {
        $("#modelCollectionAdditionalInformation").slideDown();
        $("#showAdditionalInformation").hide();
        $("#hideAdditionalInformation").show();
    });

    $("#hideAdditionalInformation").click(function () {
        $("#modelCollectionAdditionalInformation").slideUp();
        $("#showAdditionalInformation").show();
        $("#hideAdditionalInformation").hide();
    });


    $(".FAQcategoryHeader").click(function () {
        if ($(this).hasClass("hideAdditionalInformation")) {
            $(this).parent().children(".FAQlist").slideUp();
            $(this).addClass("showAdditionalInformation");
            $(this).removeClass("hideAdditionalInformation");
            selectedFAQCategory(null);
        }
        else if ($(this).hasClass("showAdditionalInformation")) {
            $(this).parent().children(".FAQlist").slideDown();
            $(this).addClass("hideAdditionalInformation");
            $(this).removeClass("showAdditionalInformation");
        }
    });

    $(".FAQLink").click(function () {
        selectedFAQCategory($(this).parent().attr('class'));
    });

    if (getSelectedFAQCategory() != null) {
        openFAQCategory($("[class*=" + getSelectedFAQCategory() + "]").parent().siblings(".FAQcategoryHeader"));
    }

    $(".accordionItem .accordionContent .searchResultHeader").click(function () {
        var parent = $(this).parents(".accordionItem").get(0);
        var id = $(".accordionId", parent).html();

        setReferringCollection(id);
    });

    $(".accordionHeader").click(function () {
        var thisAccordionContent = $(this).parent().children(".accordionContent");

        if ($(this).hasClass("openAccordionContent")) {
            $(".accordionContent").slideUp(500);
            thisAccordionContent.slideDown(500);
            $(".accordionHeader").addClass("openAccordionContent");
            $(this).removeClass("openAccordionContent");
            $(this).addClass("closeAccordionContent");
        }
        else {
            thisAccordionContent.slideUp();
            $(this).addClass("openAccordionContent");
            $(this).removeClass("closeAccordionContent");
        }
    });

    /* Front page mainArticle looping */

    var activeTab = 0;
    var amountOfTabs = $("#mainArticleList .mainArticle").length;
    var timer;
    startMainArticleLoop();

    $(".notActive").click(function () {
        activeTab = $(this).attr('id').substr(11, 1);
        changeArticle();
    });

    function changeArticle() {
        $("#mainArticleImages").children().fadeOut();
        $(".mainArticleBody").hide();
        $(".mainArticle").addClass("notActive");
        $("#mainArticle" + activeTab).removeClass("notActive");
        $("#mainArticleImage" + activeTab).fadeIn();
        $("#mainArticle" + activeTab).children(".mainArticleContainer").children(".mainArticleBody").show();


        if (activeTab == amountOfTabs - 1) {
            activeTab = 0;
        }
        else {
            activeTab++;
        }
        return true;
    }

    function startMainArticleLoop() {
        timer = setInterval(
            function () {
                changeArticle();
            }
        , 4000);
    }

    $("#mainArticleList").mouseover(function () {
        clearInterval(timer);
    });
    $("#mainArticleList").mouseout(function () {
        startMainArticleLoop();
    });

});

function openFAQCategory(category) {
    if (category.hasClass("showAdditionalInformation")) {
        category.parent().children(".FAQlist").slideDown();
        category.addClass("hideAdditionalInformation");
        category.removeClass("showAdditionalInformation");
    }
}




function showHideBuildingAdditionalInfo() {
    if ($(".planningToBuild input").is(":checked")) {
        $("#buildingAdditionalInfo").show();
    }
    else {
        $("#buildingAdditionalInfo").hide();
    }
}

function updateResultCount(formId) {
    var data = $(formId).serialize();
    data += "&count=true";
    $.post($(formId).attr("action"), data, function (resp) {
        $(formId + " .totalGreen").text(resp + " kpl");
    });
}

function addToFavourities(id) {
    var modelIds = $.cookie("ModelFavourites");
    if (modelIds == null) {
        ids = id;
    }
    else {
            ids = $.makeArray(modelIds);
            if (modelIds.indexOf(id) == -1) {
                ids.push(id);
            }        
    }
    $.cookie("ModelFavourites", ids, { expires: 365, path: '/' });
}

function selectLocation(location) {
    $.cookie("selectedLocation", location, { expires: 365, path: '/' });
}

function selectedFAQCategory(category) {
    $.cookie("selectedFAQCategory", category, { expires: 365, path: '/' });
}

function getSelectedFAQCategory() {
    return $.cookie("selectedFAQCategory");
}

function setReferringCollection(collection) {
    $.cookie("ReferringCollection", collection, { expires: 365, path: '/' });
}


/**
 * Setup the jQuery carousel and hook carousel images to show the bigger photo.
 */
function initPageGallery(container) {

    var THUMBS_PER_PAGE = 5;
    var carousel = $(container + ' .carousel ul');

    if (!carousel.length) {
        return;
    }

    var currentIndex = 0;
    var updateCarouselPosition = function (index) { };

    var wrapMode = 'circular';
    if (carousel.children().length < THUMBS_PER_PAGE) {
        wrapMode = null;
    }
    
    carousel.jcarousel({
        wrap: wrapMode,
        initCallback: function (jcarouselInstance) {
            updateCarouselPosition = function () {
                // TODO: scroll to new position
            };
        }
    });

    var previewImages = $(container + ' .gallery > .image');
    
    carousel.find('a').click(function () {
        var link = $(this);
        var id = link.parent().attr('data-id');

        $(container + ' .carousel a').removeClass('act');
        carousel.find('[data-id="' + id + '"] a').addClass('act');

        previewImages.children().hide().removeClass('act');
        previewImages.find('[data-id="' + id + '"]').show().addClass('act');
        
        currentIndex = link.parent().index();
        
        return false;
    });

    // show the first image
    carousel.children().first().children('a').click();
    
    var imageNavNext = $(container + ' .next');
    var imageNavPrev = $(container + ' .prev');

    imageNavNext.click(function () {
        showNextImage(1);
        return false;
    });

    imageNavPrev.click(function () {
        showNextImage(-1);
        return false;
    });
    
    function showNextImage(direction) {
        var activeThumb = $(carousel.children()[currentIndex]);
        var nextThumb = null;

        if (direction == -1) {
            nextThumb = activeThumb.prev();
            if (!nextThumb.length) {
                nextThumb = carousel.children().last();
            }
        }
        else {
            nextThumb = activeThumb.next();
            if (!nextThumb.length) {
                nextThumb = carousel.children().first();
            }
        }

        nextThumb.find('a').click();
        updateCarouselPosition();

        return false;
    }
}

         
function initializeMap(lat,lng,id,zoom,parameters) {
    var myLatlng = new google.maps.LatLng(lat,lng);
    var myOptions = {
        zoom: zoom,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    if (typeof parameters != "undefined") {
        for (var item in parameters) {
            myOptions[item] = parameters[item];
        }
    }

    return new google.maps.Map(document.getElementById("map_" + id),myOptions);
}

function addMarker(map,lat,lng,title) {
   return new google.maps.Marker({ position: new google.maps.LatLng(lat,lng),
                                   map: map,
                                   title: title});
}

function createDropDown() {
    var source = $("#source");
    var selected = source.find("option:selected");
    var options = $("option", source);
    
    $("#language-select").append('<dl id="target" class="dropdown"></dl>')
    $("#target").append('<dt><a href="#">' + selected.text() +
                '<span class="value">' + selected.val() +
                '</span></a></dt>')
    $("#target").append('<dd><ul></ul></dd>')

    options.each(function() {
        $("#target dd ul").append('<li><a href="#">' +
                    $(this).text() + '<span class="value">' +
                    $(this).val() + '</span></a></li>');
    });
}

function selectLanguageSubmit(redirectUrl) {
    window.location = redirectUrl;
}

function setUserLocation() {
    var selection = $("#LocationSelect").val();
    selectLocation(selection);
    location.reload();
}


/* ------------------ ASETETAAN HAKUIKKUNAN TABSIT ------------ */
	
			$(function(){	
				$('#searchTabs').tabs();				
			});
/* ------------------ ASETETAAN HAKUIKKUNAN SLIDERIT ------------ */

			$(function () {
			    $("#slider-ala").slider({
			        range: true,
			        min: 0,
			        max: 400,
			        step: 5,
			        values: [0, 400],
			        slide: function (event, ui) {

			            $("#minKoko").val(ui.values[0]);
			            $("#maxKoko").val(ui.values[1]);

			        },
			        stop: function () {
			            updateResultCount("#houseModelSearch");
			        }
			    });
			    $("#minKoko").val($("#slider-ala").slider("values", 0));
			    $("#maxKoko").val($("#slider-ala").slider("values", 1));
			});

			$(function () {
			    $("#slider-ala-villa").slider({
			        range: true,
			        min: 0,
			        max: 400,
			        step: 5,
			        values: [0, 400],
			        slide: function (event, ui) {

			            $("#minKokoVilla").val(ui.values[0]);
			            $("#maxKokoVilla").val(ui.values[1]);

			        },
			        stop: function () {
			            updateResultCount("#villaModelSearch");
			        }
			    });
			    $("#minKokoVilla").val($("#slider-ala-villa").slider("values", 0));
			    $("#maxKokoVilla").val($("#slider-ala-villa").slider("values", 1));
			});


			
	
		$(function() {
		$( "#slider-hinta" ).slider({
			range: true,
			min: 0,
			max: 400000,
			step: 1000,
			values: [ 0, 400000 ],
			slide: function( event, ui ) {
				
				$( "#minHinta" ).val( ui.values[ 0 ]);
				$( "#maxHinta" ).val( ui.values[ 1 ]);
			},
            stop: function () {
                updateResultCount("#houseModelSearch");
            }
		});		
		$( "#minHinta" ).val($("#slider-hinta").slider("values", 0));
		$( "#maxHinta" ).val($("#slider-hinta").slider("values", 1));
	});


$(function () {
    $("#slider-hinta-villa").slider({
        range: true,
        min: 0,
        max: 400000,
        step: 1000,
        values: [0, 400000],
        slide: function (event, ui) {

            $("#minHintaVilla").val(ui.values[0]);
            $("#maxHintaVilla").val(ui.values[1]);
        },
        stop: function () {
            updateResultCount("#villaModelSearch");
        }
    });
    $("#minHintaVilla").val($("#slider-hinta-villa").slider("values", 0));
    $("#maxHintaVilla").val($("#slider-hinta-villa").slider("values", 1));
});

$(function () {
    $("#slider-hinta-outbuilding").slider({
        range: true,
        min: 0,
        max: 400000,
        step: 1000,
        values: [0, 400000],
        slide: function (event, ui) {

            $("#minHintaOutbuilding").val(ui.values[0]);
            $("#maxHintaOutbuilding").val(ui.values[1]);
        },
        stop: function () {
            updateResultCount("#outbuildingModelSearch");
        }
    });
    $("#minHintaOutbuilding").val($("#slider-hinta-outbuilding").slider("values", 0));
    $("#maxHintaOutbuilding").val($("#slider-hinta-outbuilding").slider("values", 1));
});


/* ------------------ ASETETAAN (HAKUIKKUNAN) CHECKBOXES JA RADIOBUTTONS ------------ */

$(document).ready(function () {

    $('input[type=checkbox],input[type=radio]').prettyCheckboxes();

    $('.houseToggle').click(function () {
        $('.houseShowHide').toggle("blind", {}, 200);
    });
    $('.houseShowHide').hide();


    $('.villaToggle').click(function () {
        $('.villaShowHide').toggle("blind", {}, 200);
    });
    $('.villaShowHide').hide();

    $("#closeSearchWindowBtn").click(function () {
        $("#searchWindow").dialog("close");
        return false;
    });

    $(".closeAreaWindowBtn").click(function () {
        $("#areaWindow").dialog("close");
        return false;
    });

    $("#selectButton").click(function () {
        setUserLocation();
    });

    $("#LocationSelect").change(function () {
        setUserLocation();
    });

    $("#areaWindow").jqm({
        modal: false,
        trigger: '#areaOpener, .changeLocationInList',
        closeClass: 'closeAreaWindowBtn',
        overlay: 30,
        toTop: true

    });

    $("a.videoOpenLink").fancybox({
        'titleShow': false,
        'type': 'swf',
        'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' }

    });

    $("#searchWindow").jqm({
        modal: false,
        trigger: '#searchOpener',
        closeClass: 'closeSearchWindowBtn',
        overlay: 30,
        toTop: true
    });

    $("#searchOpener").click(function () {
        if ($.trim($("#houseModelSearch .totalGreen").text()).length == 0) {
            updateResultCount("#houseModelSearch");
        }

        if ($.trim($("#villaModelSearch .totalGreen").text()).length == 0) {
            updateResultCount("#villaModelSearch");
        }

        if ($.trim($("#outbuildingModelSearch .totalGreen").text()).length == 0) {
            updateResultCount("#outbuildingModelSearch");
        }
    });

    if ($.cookie("selectedLocation") == null) {
        $("#areaWindow").jqmShow();
        var selection = $("#LocationSelect").val();
        selectLocation(selection);
    }


    $('.eventHouseToggle').click(function () {
        $('.eventHouseShowHide').toggle("blind", {}, 200);
    });
    $('.eventVillaToggle').click(function () {
        $('.eventVillaShowHide').toggle("blind", {}, 200);
    });
    $(".eventHouseShowHide").hide();
    $(".eventVillaShowHide").hide();

    $(".toggleBtn").click(function () {
        if($(this).hasClass("toggleClose")) {
            $(this).removeClass("toggleClose");
        }
        else
            $(this).addClass("toggleClose");
    });
});
