$(document).ready(function() {
    // Print page
    $("#print").click(function() {
        window.print();
        return false;
    });

    // All input fields assigned with the class 'default' will
    // get their default values hidden when clicked, and reset again
    // if the user leaves the field empty or hasnt changed anything
    // The searchfields needs an accompanying hidden input with the
    // same id but suffixed "-default" that contains the default value.
    $("input.default, textarea.default").each(function() {
        var defaultVal = $(this).next("#" + $(this).attr("id") + "-default").val();
        if (!$(this).val()) {
            $(this).val(defaultVal);
            $(this).addClass("defaulted");
        }
        $(this).focus(function() {
            if ($(this).val() == defaultVal) {
                $(this).val("");
                $(this).removeClass("defaulted");
            }
        });
        $(this).blur(function() {
            if ($(this).val() == "") {
                $(this).val(defaultVal);
                $(this).addClass("defaulted");
            }
        });
    });

    // Translation
    $("#service-menu li.first a").click(function() {
        $("#translate").slideToggle();
        return false;
    });
    $("#translate .button").click(function() {
        var url = "http://translate.google.com/translate";
        var values = { u: document.location.href, sl: "sv", tl: $("#translate-language").val() };
        response(url, values, "get");
    });

    // Page-search submit
    $("#pagesearch-button").click(function() {
        submitPageSearch($(this));
        return false;
    });
    // Trigger the search function when using the ENTER key
    $("#pagesearch-query").keydown(function(e) {
        if (e.keyCode == 13) {
            submitPageSearch();
            return false;
        }
    });

    // Login form validation
    $("#section-login-pass").keydown(function(e) {
        if (e.keyCode == 13) {
            submitLogin();
            return false;
        }
    });
    $("#section-login-form .button").click(function() {
        submitLogin();
        return false;
    });

    // Logout
    $("#section-mypages .button").click(function() {
        var url = $(this).attr("href");
        var values = { logout: "true" };
        response(url, values);
        return false;
    });

    // Startpage image-switcher
    var announceTimer = "announceTimer";
    $(".announce-tab").click(function() {
        announceSwitchSlide($(this));
        $(document).stopTime(announceTimer);
        return false;
    });
    // Auto-rotate startpage slides
    $(document).everyTime(5000, announceTimer, function(i) {
        var activate = $(".announce-tab.active").next("li");
        if (activate.length == 0)
            activate = $(".announce-tab:first");
        announceSwitchSlide(activate);
    });

    // Startpage suggestions
    $(".suggestion-tab").click(function() {
        var index = $(this).prevAll().length;
        $(".suggestion-tab, .suggestion-slide").removeClass("active");
        $(this).addClass("active");
        $(".suggestion-slide:eq(" + index + ")").addClass("active");
    });

    // Startpage suggestion-properties
    $(".suggest-properties-selection-paging li").click(function() {
        var index = $(this).prevAll().length;
        var slide = $(this).closest(".suggestion-slide");
        slide.find(".suggest-properties-selection-paging li, .suggest-properties").removeClass("active");
        $(this).addClass("active");
        slide.find(".suggest-properties:eq(" + index + ")").addClass("active");
    });

    // Gallery
    gallerySwitchImage(0);
    $("#gallery-prev, #gallery-next").click(function() {
        if ($(this).hasClass("unavailable"))
            return;
        var currentIndex = $("#gallery-images li.active").prevAll().length;
        var switchIndex = $(this).attr("id") == "gallery-prev" ? currentIndex - 1 : currentIndex + 1;
        gallerySwitchImage(switchIndex);
    });
    $("#gallery-thumbs li").click(function() {
        var index = $(this).prevAll().length;
        gallerySwitchImage(index);
    });

    // Flickr
    if ($("#section-flickr").length == 1) {
        var flickrData = "http://api.flickr.com/services/feeds/photos_public.gne?id=37168241@N07&format=json&jsoncallback=?";
        $.getJSON(flickrData, function(data) {
            $.each(data.items, function(i, item) {
                var imageId = null;
                var imageUrl = item.media.m;
                switch (i) {
                    case 0:
                        imageId = "section-flickr-main";
                        break;
                    case 1:
                        imageId = "section-flickr-prev";
                        imageUrl = imageUrl.replace("_m", "_s");
                        break;
                    case 2:
                        imageId = "section-flickr-next";
                        imageUrl = imageUrl.replace("_m", "_s");
                        break;
                    default:
                        return false;
                }
                var link = $("<a />").attr("href", item.link).attr("title", item.title);
                var image = $("<img />").attr("src", imageUrl).attr("alt", item.title).attr("id", imageId);
                link.append(image).insertBefore("#section-flickr-more");
            });
        });
    }

    // Show more property area descriptions
    $("#section-areadesc-seemore a").click(function() {
        $(this).hide();
        $(this).parent().prev("#section-areadesc-more").show();
        return false;
    });

    // Display form on comment-post-report
    $(".report-comment").click(function() {
        $(this).closest("li").next(".comment-post-report").slideToggle();
        return false;
    });

    // Search property
    $("#search-properties-buttons a.button").click(function() {
        var url = $(this).attr("href");
        url = addSearchPropertyFilters(url);
        document.location = url;
        return false;
    });
    $("#search-properties-results-list-sort a").click(function() {
        var url = $(this).attr("href");
        url += "&mode=list";
        url = addSearchPropertyFilters(url);
        document.location = url;
        return false;
    });
    $("#search-properties-results-list .paging a.button").click(function() {
        var url = $(this).attr("href");
        url += "&mode=list";
        url += "&sort=" + (getQueryString("sort") || "");
        url = addSearchPropertyFilters(url);
        document.location = url;
        return false;
    });


    // Register property-watch: Handlers for changing the current panel
    $("#property-button-register-panel").click(function() {
        $(".traderoom-action").hide();
        $("#property-register").show();
        hideInactivePropertyWatchPanels();
        return false;
    });
    $("#property-button-unregister-panel").click(function() {
        $(".traderoom-action").hide();
        $("#property-unregister").show();
        hideInactivePropertyWatchPanels();
        return false;
    });
    $("#property-button-help-panel").click(function() {
        $(".traderoom-action").hide();
        $("#property-help").show();
        hideInactivePropertyWatchPanels();
        return false;
    });

    function hideInactivePropertyWatchPanels() {
        $("#property-panel-error-message").hide();

        // This element is present only after a server-side event
        if ($("#property-panel-serverside-message") != null)
            $("#property-panel-serverside-message").hide();
    }

    // Register property-watch
    $("#property-register-controls a.button").click(function() {

        var url = $(this).attr("href");
        var email = $("#watch-register-email").val();
        var password = $("#watch-register-password").val();
        var passwordRepeat = $("#watch-register-password-repeat").val();

        // Validation
        var tmp = validateEmailAddress(email);
        if (tmp != null) {
            displayWatchError(tmp);
            return false;
        }
        tmp = validatePassword(password);
        if (tmp != null) {
            displayWatchError(tmp);
            return false;
        }
        if (jQuery.trim(password) != jQuery.trim(passwordRepeat)) {
            displayWatchError('L&ouml;senorden st&auml;mmer ej &ouml;verens. V&auml;nligen f&ouml;rs&ouml;k igen!');
            return false;
        }
        url = addSearchPropertyFilters(url);
        url += '&email=' + encodeURIComponent(email);
        url += '&pwd=' + encodeURIComponent(password);
        url += '&pwdrep=' + encodeURIComponent(passwordRepeat);
        document.location = url;

        return false;
    });

    // Unregister property-watch
    $("#property-unregister-controls a.button").click(function() {

        var url = $(this).attr("href");
        var email = $("#watch-unregister-email").val();
        var password = $("#watch-unregister-password").val();

        // Validation
        var tmp = validateEmailAddress(email);
        if (tmp != null) {
            displayWatchError(tmp);
            return false;
        }
        tmp = validatePassword(password);
        if (tmp != null) {
            displayWatchError(tmp);
            return false;
        }
        url = addSearchPropertyFilters(url);
        url += '&email=' + encodeURIComponent(email);
        url += '&pwd=' + encodeURIComponent(password);
        document.location = url;

        return false;
    });

    // Send forgotten password (property-watch)
    $("#property-help-controls a.button").click(function() {

        var url = $(this).attr("href");
        var email = $("#watch-help-email").val();

        // Validation
        var tmp = validateEmailAddress(email);
        if (tmp != null) {
            displayWatchError(tmp);
            return false;
        }
        url = addSearchPropertyFilters(url);
        url += '&email=' + encodeURIComponent(email);
        document.location = url;

        return false;
    });

    // Set the e-mail address for the property watch, if available in the QS
    $("#watch-email").ready(function() {
        var emailParam = null;
        if ((emailParam = getQueryString('email')) != null)
            $("#watch-email").val(decodeURIComponent(emailParam));
        return false;
    });

    function displayWatchError(errorMessage) {
        $("#property-panel-error-message").html('<p>' + errorMessage + '</p>');
        $("#property-panel-error-message").show();
    }

    function validateEmailAddress(email) {
        if (jQuery.trim(email).length == 0)
            return 'Du m&aring;ste ange en e-postadress.';

        var regExp = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
        if (regExp.exec(email) == null)
            return 'E-postadressen &auml;r felaktig. V&auml;nligen f&ouml;rs&ouml;k igen!';
        return null;
    }

    function validatePassword(password) {
        if (jQuery.trim(password).length == 0)
            return 'Ett l&ouml;senord m&aring;ste anges.';

        if (jQuery.trim(password).length < 6)
            return 'L&ouml;senordet m&aring;ste vara minst sex tecken l&aring;ngt.';
        return null;
    }


    // Traderoom search
    $(document).ready(function() {
        $('.nosearch').length > 0 ? $('.searchads').hide() : $('.searchads').show();
        $('.showad .button').hide();
        $('.myads li input').each(function() {
            $(this).click(function() {
                $(this).attr('checked') ? $('.showad .button').show() : $('.showad .button').hide();
            });
        });
    });
    $(".search-properties-buttons a.button").click(function() {
        if ($(this).hasClass('mysearch')) {
            $('.checkbox').each(function() {
                $(this).val($(this).attr('id'));
            });
        }
        var url = $(this).attr("href");
        url = addSearchPropertyFilters(url);
        document.location = url;
        return false;
    });
    $(".traderoom-searchresult-moreinfo").click(function() {
        $(this).next(".traderoom-searchresult-details").toggle();
        return false;
    });
    $(".multicheck-singlemode input").click(function() {
        if ($(this).attr("checked")) {
            $(this).closest("ul").find("input").attr("checked", false);
            $(this).attr("checked", true);
        }
    });

    // Vara fastigheter search
    $("#varafastigheter a.button").click(function() {
        var url = $(this).attr("href");
        url += url.indexOf("?") > -1 ? "&" : "?";
        url += $("#varafastigheter-form :input[value!=]").serialize();
        document.location = url;
        return false;
    });

    // Validate form on submit
    $(".validate-form-submit").click(function() {
        var formElement = $(this).closest(".validate-form");
        var submit = validateForm(formElement);
        if (submit) {
            // Send the form
            var responseElement = $("#" + formElement.attr("id") + "-response");
            $.ajax({
                type: "POST",
                url: $(this).attr("href"),
                data: formElement.find(":input").serialize(),
                success: function(msg) {
                    // Display server-message
                    responseElement.html(msg);
                    formElement.slideUp();
                    responseElement.slideDown();
                },
                error: function(response, status, error) {
                    // Display error
                    alert("An error occurred.")
                    responseElement.html("Status: " + response.status + "\nMessage: " + response.statusText);
                }
            });
        }
        return false;
    });
    // Clear graphical error on required fields when correcting it
    $("input.required, textarea.required").keyup(function() {
        if (formHasBeenValidated)
            validateForm($(this).closest(".validate-form"));
    });

    // Zone-dropdowns
    $(".zone-dropdown h2").click(function() {
        $(this).next(".zone-content").toggle();
        $(this).parent().toggleClass("up").toggleClass("down");
    });

    // Traderoom
    $("#traderoom-button-login").click(function() {
        $(".traderoom-action").hide();
        $("#traderoom-login").show();
        return false;
    });
    $("#traderoom-button-forgotpass").click(function() {
        $(".traderoom-action").hide();
        $("#traderoom-forgotpass").show();
        return false;
    });
    $("#traderoom-button-register").click(function() {
        $(".traderoom-action").hide();
        $("#traderoom-register").show();
        return false;
    });

    // Contact
    $("#contact-sokbovard-query").keydown(function(e) {
        if (e.keyCode == 13) {
            $("#contact-sokbovard-button").click();
            return false;
        }
    });
    $("#contact-sokbovard-button").click(function() {
        var input = $("#contact-sokbovard-query");
        document.location = $(this).attr("href") + "?" + input.serialize();
        return false;
    });
    $(".contact-section-tabs li").click(function() {
        $(this).siblings().removeClass("active").removeClass("beforeactive");
        $(this).prev().addClass("beforeactive");
        $(this).addClass("active");

        var currentIndex = $(this).prevAll().length;
        var container = $(this).closest(".contact-section");
        container.find(".contact-section-tabcontent").hide();
        container.find(".contact-section-tabcontent:eq(" + currentIndex + ")").show();
        return false;
    });
    $("#select-areaoffice").change(function() {
        $(".select-areaoffice").hide();
        $("#select-areaoffice-" + $(this).val()).show();
    });
    $("#lokaluthyrare-link").click(function() {
        $("#lokaluthyrare").toggle();
        return false;
    });
});

function addSearchPropertyFilters(querystring) {
	var filters = $(".search-properties-form :input[value!=]").serialize();
	if (filters.length > 0)
		return querystring + "&" + filters;
	return querystring;
}

function getQueryString(param) {
	var parts = document.location.href.split("?");
	if (parts.length < 2)
	    return null;
	var params = parts[1].split("&");
	for (var i = 0; i < params.length; i++) {
		var keyVal = params[i].split("=");
		if (keyVal[0] == param)
			return keyVal[1];
	}
	return null;
}

function submitLogin() {
	var formElement = $("#section-login-form");
	var submit = validateForm(formElement);
	if (submit) {
		var url = $("#section-login-form .button").attr("href");
		var values = { login: $("#section-login-user").val(), password: $("#section-login-pass").val() };
		response(url, values);
	}
}

function submitPageSearch() {
	var query = $("#pagesearch-query").val();
	if (query == $("#pagesearch-query-default").val() || query == "")
		return;
	var url = $("#pagesearch-button").attr("href");
	url += url.indexOf("?") > -1 ? "&" : "?";
	url += "q=" + encodeURIComponent(query);
	document.location = url;
}

function announceSwitchSlide(slideItemButton) {
	var index = slideItemButton.prevAll().length;
	var slideWidth = $("#announce").width();
	var scrollPos = -1 * index * slideWidth;
	$("#announce-slides").animate({ left: scrollPos }, { queue: false, duration: 500 });
	$(".announce-tab").removeClass("active");
	slideItemButton.addClass("active");
}

function gallerySwitchImage(imageIndex) {
	// Abort if there are no images
	var totalImages = $("#gallery-images li").length;
	if (totalImages == 0)
		return;

	// Display navigational elements if there are more than one image
	if (totalImages > 1)
		$("#gallery-prev, #gallery-next, #gallery-thumbs").show();

	// Set the current image, caption and thumbnail to active
	$("#gallery li").removeClass("active");
	$("#gallery-images li:eq(" + imageIndex + "), #gallery-captions li:eq(" + imageIndex + "), #gallery-thumbs li:eq(" + imageIndex + ")").addClass("active");

	// Make the previous-/next-buttons available depending on current image
	$("#gallery-prev, #gallery-next").removeClass("unavailable");
	if (imageIndex <= 0)
		$("#gallery-prev").addClass("unavailable");
	if (imageIndex >= totalImages - 1)
		$("#gallery-next").addClass("unavailable");
}

var formHasBeenValidated = false;
function validateForm(containerElement) {
	var validated = true;

	// Add a class if the field is required as not correctly filled.
	$(containerElement).find("input.required, textarea.required").each(function() {
		$(this).removeClass("invalid");
		var isEmpty = $(this).val() == "";
		var hasDefaultValue = $(this).hasClass("default") && $(this).val() == $(this).next(".defaultvalue").val()
		if (isEmpty || hasDefaultValue) {
			$(this).addClass("invalid");
			validated = false;
			formHasBeenValidated = true;
		}
	});

	// Display invalid message
	if (!validated)
		$(containerElement).find(".validate-form-invalid").show();

	return validated;
}

function response(path, params, method) {
	method = method || "post";

	var form = document.createElement("form");
	form.setAttribute("method", method);
	form.setAttribute("action", path);

	for (var key in params) {
		var field = document.createElement("input");
		field.setAttribute("type", "hidden");
		field.setAttribute("name", key);
		field.setAttribute("value", params[key]);

		form.appendChild(field);
	}

	document.body.appendChild(form);
	form.submit();
}

$(document).ready(function() {
    var xf = $('#id_matrix');
    var submit = $('#id_matrix input[type="submit"]').hide();
    if (typeof (submit.val()) != 'undefined') {
        var a = $('<a />').addClass('button').click(function(event) {
            event.preventDefault();
            submit.click();
        });
        var span = $('<span />').text(submit.val()).click(function(event) {
            event.stopPropagation();
            submit.click();
        });
        submit.after(a.append(span));
    }
});

$(document).ready(function() {
    $('.entrance').each(function() {
        var lastLink = $(this).find('a').last();
        if (lastLink.text() == '.') {
            lastLink.text('');
        }
        if (lastLink != null && typeof (lastLink) != 'undefined' && lastLink.text() != '') {
            $(this).find('div').first().addClass('entrance-link').click(function() {
                document.location = lastLink.attr('href');
            });
        }
    });
});
