﻿var itemCount = null;

$(document).ready(function () {
    $("#pop-wrong-password .pop-close").click(function () {
        $("#pop-wrong-password").hide();
        return false;
    });

    $("#pop-retrieve-password .pop-close").click(function () {
        $("#pop-retrieve-password").hide();
        return false;
    });

    $("#pop-retrieve-password-message-ok .pop-close, #pop-retrieve-password-message-error .pop-close").click(function () {
        $("#pop-retrieve-password-message-ok").hide();
        $("#pop-retrieve-password-message-error").hide();
        return false;
    });


    $('input[type=text], input[type=password]').keydown(function (event) {
        if (event.keyCode == '13') {
            //Logic to find the closest submitbutton
            if ($(this).get(0) != $(".user-links #nameTextBox").get(0))
                $(this).closest("fieldset").find("input[type=submit]").click();

            event.preventDefault();
        }
    });

    $('.filter .tags li.trade, .filter .tags li.titleTrade').click(function () {
        GuideShow(2);
    });
    $('.filter .tags li.sort, .filter .tags li.titleSort').click(function () {
        GuideShow(3);
    });

    /*
    $('.filter .tags li a').click(function () {
    var li = $(this).parent('li');
    var tag = $(this).text();
    var interestClass = li.hasClass("active") ? "" : "active"; // li.hasClass("inactive") ? "" : li.hasClass("active") ? "inactive" : "active";
    setTradeInterest(tag, interestClass, function () {
    li.removeClass("active");
    li.removeClass("inactive");
    li.addClass(interestClass);
    setFilterTitle(li);

    //Track klick
    RecordLink('Prioritet', li.hasClass("active") ? "Active" : "Inactive", tag, 0, '');

    window.document.location.reload(true); //reload the page so the changes will appear	
    });
    return false;
    });
    */

    $('.filter .tags li').each(function () {
        var li = $(this);
        //var tag = li.children('a').text();

        var tag = li.children('span').text();

        setFilterTitle(li, tag);
    });

    $(document).click(function () {
        if ($("#pop-profile").is(":visible"))
            $("#pop-profile").hide();
    });
    $(window).scroll(function () {
        $("#scrollPosition").val($(window).scrollLeft() + "," + $(window).scrollTop());
    });

    //Download spinner
    $('.article-related-material li a, li.pdf a').click(function () {
        var target = $(this).attr("target");

        if (target == undefined)
            $(this).spinner();
        else {
            //Dont show spinner if targt= blank
            if (target.toLowerCase() != '_blank')
                $(this).spinner();
        }

        return true;
    });



});

function setFilterTitle(li, tag) {

    if (tag != '') {


        if (li.hasClass("trade") && (tag == '. . .' || tag == '...'))
            li[0].title = "Välj fackområde";
        else if (li.hasClass("trade"))
            li[0].title = tag + ", prioritet: Hög";
        else if (li.hasClass("sort") && (tag == '. . .' || tag == '...'))
            li[0].title = "Sortera artiklar";
        else if (li.hasClass("sort"))
            li[0].title = tag + ", sortering: Hög";

    /*
        if (li.hasClass("active"))
            li[0].title = tag + ", prioritet: Hög";
        else if (li.hasClass("inactive"))
            li[0].title = tag + ", prioritet: Låg";
        else
            li[0].title = tag + ", prioritet: Neutral";
    */
    }
}

function showLockedContent() {
    //display overlay
    $("#main").addClass('blur');
    setTimeout('hideContent()', 100);
}

function hideContent() {
    var top = ($(window).height() - 400) / 2;
    var left = ($(window).width() - $('#pop-locked-page').width()) / 2;

    $.blockUI({
        message: $('#pop-locked-page'),
        css: {
            border: 'solid 0px #fff',
            top: top + 'px',
            left: left + 'px',
            cursor: 'default',
            width: $('#pop-locked-page').width() + 'px',
            height: 400 + 'px',
            textAlign: 'left',
            position: 'fixed'
        },
        overlayCSS: {
            opacity: '0.5',
            cursor: 'default'
        },
        fadeIn: 500,
        forceIframe: true,
        bindEvents: false
    });
}


function initializeGoogleMap(canvas, events) {
    var latlng = new google.maps.LatLng(62.622994, 15.073242); //Sthlm: 59.33279, 18.06449
    var myOptions = {
        zoom: 3,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false
    };
    var map = new google.maps.Map(canvas, myOptions);

    //automatically reset the zoom level if it becomes to high
    google.maps.event.addListener(map, 'zoom_changed', function () {
        zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function (event) {
            if (this.getZoom() > 15) // Change max/min zoom here
                this.setZoom(15);

            google.maps.event.removeListener(zoomChangeBoundsListener);
        });
    }); 

    //create markers
    var bounds = new google.maps.LatLngBounds();
    var HasCoords = false;
    for (i = events.length - 1; i > -1; i--) {
        var currentX = parseFloat(events[i].xcoord);
        var currentY = parseFloat(events[i].ycoord);

        if (currentX && currentX != '' && currentY && currentY != '') {
            HasCoords = true;
            latlng = new google.maps.LatLng(currentX, currentY);
            var marker = new google.maps.Marker({
                position: latlng,
                title: events[i].name,
                map: map,
                icon: events[i].icon
            });

            addGoogleMapInfoWindow(map, marker, events[i].date, events[i].location, events[i].address, events[i].zipCode, events[i].city, events[i].name, events[i].pagelink, events[i].pageId, currentX, currentY, events[i].accuracy);

            if (i == 0) {
                map.setCenter(latlng, 8);
            }

            bounds.extend(latlng);
        }
    }
    if (events.length == 0 || !HasCoords) {
        map.setCenter(latlng, 8);
    }
    else {   
        map.fitBounds(bounds);
    }
}

function addGoogleMapInfoWindow(map, marker, date, location, address, zipcode, city, name, pagelink, pageid, xcoord, ycoord, accuracy) {

    var warning = "";
    if (accuracy < 5) {
        warning = 'Markeringen på kartan stämmer<br>inte riktigt med adressen.';
    }
    var htmlContent = "<div class='google-event'>" + date + "<br/><a href=" + pagelink + ">" + name + "</a></b><br/>" + location + "<br/>" + address + ", <nobr>" + zipcode + " " + city + "</nobr><div class='warning'>" + warning + "</div></div>";

    var infowindow = new google.maps.InfoWindow({
        content: htmlContent
    });

    google.maps.event.addListener(marker, "click", function () {
        infowindow.open(map, this);
        scrollToEvent("#" + pageid);
    });
}

function isScrolledIntoView(elem, heightFromTopOfElement) {
    if (!heightFromTopOfElement)
        heightFromTopOfElement = $(elem).height();

    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + heightFromTopOfElement;
    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
function removeNotification(notificationId, baseUrl, control, showEarlierNotifications, count, lastNotificationDate) {
$.ajax({
    type: 'GET',
        data: { notificationId: notificationId },
        url: baseUrl + "Service/Bygginfo.asmx/RemoveNotification",
        success: function (msg, textStatus, request) {
            renderEarlierNotifications(baseUrl, control, showEarlierNotifications, count, lastNotificationDate);
        }
    });
    return false;
}


function renderEarlierNotifications(baseUrl, control, showEarlierNotifications, count, lastNotificationDate) {
    if (itemCount != null)
        count = itemCount;

    $.ajax({
        type: 'GET',
        data: { control: 'NotificationList' },
        url: baseUrl + "Service/Bygginfo.asmx/GetControl?ShowEarlierNotifications=" + showEarlierNotifications + "&EarlierNotificationCount=" + count + "&LastNotificationDate=" + lastNotificationDate,
        success: function (msg, textStatus, request) {
            var returnedContent = $(msg).find("string").text();

            var notificationContainer = $(control).find(".notifications");
            var earlierNotificationContainer = $(control).find(".earliernotifications");
            var showmoreContainer = $(control).find(".showmore");

            var earlierNotificationContent = getContentPart(control, returnedContent, "earliernotifications");
            var showMoreContent = getContentPart(control, returnedContent, "showmore");
            var notificationContent = getContentPart(control, returnedContent, "notifications");

            var earlierNotificationsHeight = getHeight(control, earlierNotificationContent);
            var notificationsHeight = getHeight(control, notificationContent);

            //set a fixed height to the earlier notifications container while the new content is being added
            earlierNotificationContainer.css('height', earlierNotificationsHeight);
            earlierNotificationContainer.css('overflow', 'hidden');
            /*
            //set a fixed height to the notifications container while the new content is being added
            notificationContainer.css('height', getHeight(notificationContent));
            notificationContainer.css('overflow', 'hidden');
            */

            //append the new content 
            earlierNotificationContainer.html(earlierNotificationContent);
            showmoreContainer.html(showMoreContent);
            notificationContainer.html(notificationContent);

            //remove the showmore container if it's not present in the new result
            if (showmoreContainer.html() == '')
                showmoreContainer.remove();
                /*
            //animate the earliernotification container
            notificationContainer.animate({
                height: notificationsHeight + 'px'
            }, 500, function () {
            */
                earlierNotificationContainer.animate({
                    height: earlierNotificationsHeight + 'px'
                }, 500, function () {
                    location.hash = "#" + count;
                });
            /*});*/
        }
    });
    return false;
}

/*
function renderEarlierNotifications(baseUrl, control, showEarlierNotifications, count, lastNotificationDate) {
    $.ajax({
        type: 'POST',
        data: { control: 'NotificationList' },
        url: baseUrl + "Service/Bygginfo.asmx/GetControl?ShowEarlierNotifications=" + showEarlierNotifications + "&EarlierNotificationCount=" + count + "&LastNotificationDate=" + lastNotificationDate,
        success: function (msg, textStatus, request) {
            var returnedContent = $(msg).find("string").text();

            var showmorePart = new part(control, returnedContent, "showmore");
            if (showmorePart.content == '')
                showmorePart.container.remove();

            var notificationsPart = new part(control, returnedContent, "notifications");
            var earlierNotificationsPart = new part(control, returnedContent, "earliernotifications");

            var parts = new Array();
            parts[0] = notificationsPart;
            parts[1] = earlierNotificationsPart;

            for (i = 0; i < parts.length; i++) {
                console.log(parts[i].height);
                parts[i].container.css('height', parts[i].height);
                parts[i].container.css('overflow', 'hidden');

                parts[i].container.html(parts[i].content);

                parts[i].animate();
            }
        }
    });
    return false;
}
*/

function animate() {
    this.container.animate({
        height: this.height + 'px'
    }, 500, function () {
    });
}

function part(parentControl, fullContent, partName) {
    var container = $(parentControl).find("." + partName);
    var content = getContentPart(parentControl, fullContent, partName);
    var height = getHeight(parentControl, content);

    this.container = container;
    this.content = content;
    this.height = height;
    this.animate = animate;
}

function getContentPart(parentControl, content, partDiv) {
    //create a temporary div in order to retrieve the different parts of the content
    $("<div><div>").attr('id', 'tmpDiv').css('display', 'none').appendTo($(parentControl));
    $("#tmpDiv").html(content);

    var partContent = $("#tmpDiv").find("." + partDiv).html();

    //cleanup
    $("#tmpDiv").remove();

    return partContent;
}
function getHeight(parentControl, content) {
    $("<div><div>").attr('id', 'tmpDiv').css('display', 'none').appendTo($(parentControl));
    $("#tmpDiv").html(content);

    var height = $("#tmpDiv").height();
    $("#tmpDiv").remove();

    return height;
}

//Remove a prospect and rerender the list
function removeProspect(control, prospectId) {
    var query = "?removeProspect=" + prospectId;
    renderProspectList(control, query);
}

//Check or uncheck site notification on a prospect
function siteNotificationForProspect(control, prospectId, checked) {
    var query = "?siteNotificationForProspect=" + prospectId + "&checked=" + checked; ;
    renderProspectList(control, query);
}

//Check or uncheck email notification on a prospect
function emailNotificationForProspect(control, prospectId, checked) {
    var query = "?emailNotificationForProspect=" + prospectId + "&checked=" + checked; ;
    renderProspectList(control, query);
}

//Render the prospect list
function renderProspectList(control, query) {
    $.ajax({
        type: 'GET',
        data: { control: 'ProspectList' },
        url: baseUrl + "Service/Bygginfo.asmx/GetControl" + query,
        success: function (msg, textStatus, request) {
            $(control).html($(msg).find("string").text());
        }
    });
}
function addEventProspect(pageId, span) {
    $.ajax({
        type: 'GET',
        data: { eventId: pageId },
        url: baseUrl + "Service/Bygginfo.asmx/AddEventAsProspect",
        success: function (msg, textStatus, request) {
            $(span).removeClass("addProspect");
            $(span).addClass("removeProspect");
        }
    });
}
function removeEventProspect(pageId, span) {
    $.ajax({
        type: 'GET',
        data: { eventId: pageId },
        url: baseUrl + "Service/Bygginfo.asmx/RemoveEventProspect",
        success: function (msg, textStatus, request) {
            $(span).removeClass("removeProspect");
            $(span).addClass("addProspect");
        }
    });
}
function addForumProspect(topicId, span, commentPageId) {
    var hasCommentPageId = (!!commentPageId);
    var url = !hasCommentPageId ? 'Service/Bygginfo.asmx/AddForumAsProspect'
        : 'Service/Bygginfo.asmx/AddPageCommentAsProspect';
    var data = !hasCommentPageId ? { topicId: topicId }
        : { topicId: topicId, commentPageId: commentPageId };

    $.ajax({
        type: 'GET',
        data: data,
        url: baseUrl + url,
        success: function (msg, textStatus, request) {
            if (!!span) {
                $(span).removeClass("addProspect");
                $(span).addClass("removeProspect");
            } else {
                $('.prospect-functions').removeClass("addProspect");
                $('.prospect-functions').addClass("removeProspect");
            }
        }
    });
}
function removeForumProspect(topicId, span) {
    $.ajax({
        type: 'GET',
        data: { topicId: topicId },
        url: baseUrl + "Service/Bygginfo.asmx/RemoveForumProspect",
        success: function (msg, textStatus, request) {
            if (!!span) {
                $(span).removeClass("removeProspect");
                $(span).addClass("addProspect");
            } else {
                $('.prospect-functions').removeClass("removeProspect");
                $('.prospect-functions').addClass("addProspect");
            }
        }
    });
}

function setTradeInterest(trade, interestClass, successCallback) {
    $.ajax({
        type: 'GET',
        data: { tag: trade, interesting: interestClass == "active" ? 1 : interestClass == "" ? 0 : -1 },
        url: baseUrl + "Service/Bygginfo.asmx/SetTradeInterest",
        success: successCallback
    });
}

function scrollToLastPosition() {
    var x = 0;
    var y = 0;
    var positions = $("#scrollPosition").val().split(',');
    if (positions.length > 0)
        x = positions[0];
    if (positions.length > 1)
        y = positions[1];
    scrollTo(x, y);
}

function renderArticles(baseUrl, control, parentPage, displayType, startIndex, count, enableShowMore, articleIdToHide, themePage) {
    if (itemCount != null && itemCount > 0)
        count = itemCount;
    $.ajax({
        type: 'GET',
        data: { control: 'ArticleList' },
        url: baseUrl + "Service/Bygginfo.asmx/GetControl?ParentPage=" + parentPage + "&DisplayType=" + displayType + "&StartIndex=" + startIndex + "&Count=" + count + "&EnableShowMore=" + enableShowMore + "&ArticleIdToHide=" + articleIdToHide + "&ThemePage=" + themePage,
        success: function (msg, textStatus, request) {
            var articleContainer = $(control).find(".articles");
            var showmoreContainer = $(control).find(".showmore");

            //create a temporary div in order to retrieve the different parts of the result
            $("<div><div>").attr('id', 'tmpDiv').css('display', 'none').appendTo($(control));
            $("#tmpDiv").html($(msg).find("string").text());

            var articleContent = $("#tmpDiv").find(".articles").html();
            var showMoreContent = $("#tmpDiv").find(".showmore").html();

            //create a temporary div in order to retrieve the corrent height of the new article container
            var newArticleHeight = 0;
            $("<div><div>").attr('id', 'tmpDivArticles').css('display', 'none').addClass("articles").appendTo($(control));
            $("#tmpDivArticles").html(articleContent);

            newArticleHeight = $("#tmpDivArticles").height();

            //set a fixed height to the articles container while the new content is being added
            articleContainer.css('height', articleContainer.height());
            articleContainer.css('overflow', 'hidden');

            //append the new content 
            articleContainer.html(articleContent);
            showmoreContainer.html(showMoreContent);

            //remove the showmore container if it's not present in the new result
            if (showmoreContainer.html() == '')
                showmoreContainer.remove();

            //cleanup
            $("#tmpDiv").remove();
            $("#tmpDivArticles").remove();

            //animate the article container
            articleContainer.animate({
                height: newArticleHeight + 'px'
            }, 500, function () {
                location.hash = "#" + count;
                if (itemCount != null) {
                    scrollToLastPosition();
                    itemCount = null;
                }
            });
        }
    });
    return false;
}

function renderProducts(baseUrl, control, parentPage, displayType, startIndex, count, enableShowMore) {
    if (itemCount != null)
        count = itemCount;
    $.ajax({
        type: 'GET',
        data: { control: 'ProductList' },
        url: baseUrl + "Service/Bygginfo.asmx/GetControl?ParentPage=" + parentPage + "&DisplayType=" + displayType + "&StartIndex=" + startIndex + "&Count=" + count + "&EnableShowMore=" + enableShowMore,
        success: function (msg, textStatus, request) {

            var container = $(control).find(".products");
            var showmoreContainer = $(control).find(".showmore");

            //create a temporary div in order to retrieve the different parts of the result
            $("<div><div>").attr('id', 'tmpDiv').css('display', 'none').appendTo($(control));
            $("#tmpDiv").html($(msg).find("string").text());

            var content = $("#tmpDiv").find(".products").html();
            var showMoreContent = $("#tmpDiv").find(".showmore").html();

            //create a temporary div in order to retrieve the corrent height of the new article container
            var newHeight = 0;
            $("<div><div>").attr('id', 'tmpDivArticles').css('display', 'none').addClass("products").appendTo($(control));
            $("#tmpDivArticles").html(content);

            newHeight = $("#tmpDivArticles").height();

            //set a fixed height to the articles container while the new content is being added
            container.css('height', container.height());
            container.css('overflow', 'hidden');

            //append the new content 
            container.html(content);
            showmoreContainer.html(showMoreContent);

            //remove the showmore container if it's not present in the new result
            if (showmoreContainer.html() == '')
                showmoreContainer.remove();

            //cleanup
            $("#tmpDiv").remove();
            $("#tmpDivArticles").remove();

            //animate the article container
            container.animate({
                height: newHeight + 'px'
            }, 500, function () {
                location.hash = "#" + count;
                if (itemCount != null) {
                    scrollToLastPosition();
                    itemCount = null;
                }
            });
        }
    });
    return false;
}


function renderComments(baseUrl, control, count, topicId) {
    if (itemCount != null)
        count = itemCount;
    $.ajax({
        type: 'GET',
        data: { control: 'CommentList' },
        url: baseUrl + "Service/Bygginfo.asmx/GetControl?Count=" + count + "&TopicId=" + topicId,
        success: function (msg, textStatus, request) {

            var commentContainer = $(control).find(".pagecomments");
            var showmoreContainer = $(control).find(".showmore");

            //create a temporary div in order to retrieve the different parts of the result
            $("<div><div>").attr('id', 'tmpDiv').css('display', 'none').appendTo($(control));
            $("#tmpDiv").html($(msg).find("string").text());

            var commentContent = $("#tmpDiv").find(".pagecomments").html();
            var showMoreContent = $("#tmpDiv").find(".showmore").html();

            //create a temporary div in order to retrieve the corrent height of the new article container
            var newHeight = 0;
            $("<div><div>").attr('id', 'tmpDivArticles').css('display', 'none').addClass("pagecomments").appendTo($(control));
            $("#tmpDivArticles").html(commentContent);

            newHeight = $("#tmpDivArticles").height();
            //set a fixed height to the articles container while the new content is being added
            commentContainer.css('height', commentContainer.height());
            commentContainer.css('overflow', 'hidden');

            //append the new content 
            commentContainer.html(commentContent);
            showmoreContainer.html(showMoreContent);


            //remove the showmore container if it's not present in the new result
            if (showmoreContainer.html() == '')
                showmoreContainer.remove();

            //cleanup
            $("#tmpDiv").remove();
            $("#tmpDivArticles").remove();

            //animate the article container
            commentContainer.animate({
                height: newHeight + 'px'
            }, 500, function () {
                location.hash = "#" + count;
                if (itemCount != null) {
                    scrollToLastPosition();
                    itemCount = null;
                }
            });
        }
    });
        return false;
}


function displayLoginError() {
    var pos = $("#nameTextBox").position();
    $("#pop-wrong-password").css({ "left": (pos.left - 10) + "px", "top": (pos.top - 7) + "px" });
    $("#pop-wrong-password").show();
    $(this).addClass("expanded");
    return false;
}

function displayRetrievePasswordMessageError() {
    var pos = $("#ForgottenPasswordTextBox").position();
    $("#pop-retrieve-password-message-error").css({ "left": (pos.left - 10) + "px", "top": (pos.top - 7) + "px" });
    $("#pop-retrieve-password-message-error").show();
    $(this).addClass("expanded");
    return false;
}

function displayRetrievePasswordMessageOk() {
    var pos = $("#ForgottenPasswordTextBox").position();
    $("#pop-retrieve-password-message-ok").css({ "left": (pos.left - 10) + "px", "top": (pos.top - 7) + "px" });
    $("#pop-retrieve-password-message-ok").show();
    $(this).addClass("expanded");
    return false;
}

/*Shopping basket functions*/

//Get the basket
function getBasket() {
    $.ajax({
        type: 'GET',
        data: { control: "Basket" },
        url: baseUrl + "Service/Bygginfo.asmx/GetControl",
        success: function (msg, textStatus, request) {
            renderCart($(msg).find("string").text());
        }
    });
}

//Add an item to the basket
function addToBasket(productId, name, priceIncVat, priceExVat, image) {
    $.ajax({
        type: 'GET',
        data: { productId: productId, name: name, priceIncVat: priceIncVat, priceExVat: priceExVat, image: image },
        url: baseUrl + "Service/Bygginfo.asmx/AddToBasket",
        success: function (msg, textStatus, request) {
            renderCart($(msg).find("string").text());
        }
    });
}

//Remove single item and redraws the basket
function removeItemFromBasket(basketItemId) {
    $.ajax({
        type: 'GET',
        data: { basketItemId: basketItemId},
        url: baseUrl + "Service/Bygginfo.asmx/RemoveFromBasket",
        success: function (msg, textStatus, request) {
            renderCart($(msg).find("string").text());
        }
    });
}

//Update the amount for a single item and redraws the basket
function updateAmountForBasketItem(basketItemId, amount) {
    $.ajax({
        type: 'GET',
        data: { basketItemId: basketItemId, amount:amount },
        url: baseUrl + "Service/Bygginfo.asmx/UpdateAmountForBasketItem",
        success: function (msg, textStatus, request) {
            renderCart($(msg).find("string").text());
        }
    });
}

//Render the html string into the basket (the div is called cart) with some fancy animations when appropriate
function renderCart(html) {
    $("#basketItems").html(html);
    if ($("#basketCount").length > 0) {
        var count = $("#basketCount").val();
        $("#view-cart .product-count").html("(" + count + ")");
    } else {
        $("#view-cart .product-count").html("(0)");
    }

    if (count > 0) {
        // $("#cart").css('visibility', 'visible');

        //Flash the cart slightly to give som feedback
        var viewCart = $("#view-cart");
        viewCart.fadeTo(100, 0.3, function () {
            viewCart.fadeTo(400, 1);
        });

        //if the cart is outside the visible area of the window, show it briefly and scroll it back to the top so it gives a visible cue that something happened
        if (!isScrolledIntoView($("#cart"))) {
            $("#cart").css('position', 'fixed');
            setTimeout(function () {
                $("#cart").animate({
                    marginTop: '-50px'
                }, 900, function () {
                    $("#cart").css('margin-top', '0');
                    $("#cart").css('position', 'absolute');

                });
            }, 800);
        }
    }
//    else {
//        var cart = $("#cart");
//        cart.fadeTo(250, 0, function () {
//           // $("#cart").css('visibility', 'hidden'); //If there is no items the cart should be hidden
//            $("#cart").fadeTo(0, 1); //Reset the opacity
//        });

//    }
}

//Helper function that checks if an element is visible in the window
/*function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
*/
//Go to checkout with the items in the current basket
function checkout(prefix) {
    var checkoutUrl = $("#" + prefix + "checkoutUrl").val();
    var url = checkoutUrl + $("#" + prefix + "basketString").val();

    openModalDialogue(url, true, 605, 800, false);
}

//open question form dialogue
function openQuestionForm(email) {
    if (email == undefined)
        email = '';
    openModalDialogue(questionFormUrl + "?RecipientEmail=" + email, false, 745, 690, true);
}

//opens a dialog with an iframe displaying the provided url
function openModalDialogue(url, showTitle, width, height, showCloseButton) {
    $("#dialog-modal iframe").attr('src', url);
    $("#dialog-modal iframe").attr('width', (width-25));
    $("#dialog-modal iframe").attr('height', (height - 75));

    if (showCloseButton)
        $("#dialog-modal .button").show();
    else
        $("#dialog-modal .button").hide();

    $("#dialog-modal").dialog("destroy");

    $("#dialog-modal").dialog({
        height: height,
        width: width,
        modal: true
    });
    if (!showTitle)
        $(".ui-dialog-titlebar").hide();
}

function closeModalDialog() {
    $("#dialog-modal").hide();
    $("#dialog-modal").dialog("destroy");
   }

   $(document).ready(function () {
    $('#searchText, #searchTextHeader').keydown(function (event) {
        if (event.keyCode == '13') {
            event.preventDefault();
            $(this).next(".button").click();
        }
    });

    if (document.location.hash.length > 0 && document.location.pathname == searchPageUrl) {
        var searchUrl = baseUrl + "Service/Bygginfo.asmx/Search?q=";
        var searchText = "";
        if (document.location.hash.indexOf('&') > 0)
            searchText = decodeURIComponent(document.location.hash.toString().substring(1, document.location.hash.indexOf('&')));
        else
            searchText = decodeURIComponent(document.location.hash.toString().substring(1, document.location.hash.length));

        $("#searchTextHeader, #searchText").val(searchText);
        $("#searchIndicator").show();
        $.ajax({
            type: 'GET',
            data: {},
            url: searchUrl + document.location.hash.toString().substring(1, document.location.hash.length),
            success: function (msg, textStatus, request) {
                var searchResultContainer = $("#searchResultContainer");
                searchResultContainer.html($(msg).find("string").text());
            }
        });
    }
   });


//Search by text, count(optional) and searchIndex (optional, will default to previous search)
var currentSearchIndex = "bygginfo";
var currentSort = false;
function ajaxsearch(text, count, searchIndex, searchByDate) {
    $("#loader").show();

    if (!count) count = 20;

    if (!searchIndex)
        searchIndex = currentSearchIndex;
    else
        currentSearchIndex = searchIndex;
    var searchUrl = baseUrl + "Service/Bygginfo.asmx/Search?q=";

    var searchUrlQuery = encodeURIComponent(text) + "&count=" + count.toString() + "&searchIndex=" + searchIndex;

    if (searchByDate!=null) {
        currentSort = searchByDate;
    }
    if (currentSort)
        searchUrlQuery += "&sortby=date"

	$("#searchTextHeader, #searchText").val(text);

	//Google track
	if (count == 20 && text != '') {
	    RecordLink('Sok', searchIndex, text, 0, '');
	}

	if (document.location.pathname != searchPageUrl)
	{
	 document.location.href = searchPageUrl+"#"+ searchUrlQuery;
	}
	else {

        $.ajax({
            type: 'GET',
            data: {},
            url: searchUrl + searchUrlQuery,
            success: function (msg, textStatus, request) {
                var searchResultContainer = $("#searchResultContainer");
                searchResultContainer.html($(msg).find("string").text());
                document.location.hash = searchUrlQuery;

                $("#loader").hide();
            }
        });
    }
}

function addCssAdjustments() {
    /* Odd, first, last, align
    ___________________________________________________*/

    /* Om det ar mojligt att skriva ut de har klasserna direkt i HTML-koden ar det att foredra */

    $(".contact:nth-child(even), .block-forum ul li:odd, .mainInfoBox ul li:nth-child(even)").addClass("odd");

    $(".blocks .block:last-child, .playlist li:last-child, .block-comments .col:last-child, .post-hierarchy-3 .post:last-child, .result-dept li:last-child, .block-poll fieldset:last-child, .block-current-account .row:last-child, #cart-products li:last-child, .user-links .col:last-child").addClass("last");

    $(".external-links li:first-child, #breadcrumbs a:first-child, .block-comments .col:first-child").addClass("first");

    $(".primary-nav li:first-child a").addClass("first");

    $(".article-content img[align='right']").addClass("align-right");
    $(".article-content img[align='left']").addClass("align-left");
}

$(document).ready(function () {
    init();
});


function init() {

    addCssAdjustments();
    /* Forms
    ___________________________________________________*/

    $("input:checkbox").addClass("checkbox");
    $("input:radio").addClass("radio");

    /* Clear default value
    ___________________________________________________*/

    $("input.clear, textarea.clear").focus(function () {
        var defaultVal = $(this).attr("title");
        if (defaultVal == $(this).val()) {
            $(this).val("");
        }
    });

    /* Clear default value password special
    ___________________________________________________*/

    //Hide textbox and show passwordbox on startup, its because if Javascript is not enabled or there's a Javascript error.
    $('input.clearjquerytext').show();
    $('input.clearjquerypassword').hide();

    $("input.clearjquerytext").focus(function () {
        
        //fetch password element
        var InputPassword = $(this).attr("show");   

        if (InputPassword != undefined) {

            //Show passwordbox hide textbox
            $(this).hide();
            $('#' + InputPassword).show();

            //Set focus on password element
            $('#' + InputPassword).focus();

            var defaultVal = $(this).attr("title");
            if (defaultVal == $(this).val()) {
                $(this).val("");
            }

        }
    });


    /* Autocomplete list
    ___________________________________________________*/

    $("#search-autocomplete li").mouseenter(function () {
        $(this).css("background", "#ebebeb").css("cursor", "pointer");
    });
    $("#search-autocomplete li").mouseleave(function () {
        $(this).css("background", "#fff").css("cursor", "default");
    });

    /* Set height of footer
    ___________________________________________________*/

    var browserHeight = $(window).height();
    var documentHeight = $("body").height();
    if (browserHeight > documentHeight) {
        var diff = browserHeight - documentHeight;
        var footer = $("#footer");
        var footerHeight = footer.height();
        footer.height(footerHeight + diff);
    }

    /* View cart
    ___________________________________________________*/

    var timerCart;

    $("#view-cart").mouseenter(function () {
        $("#cart-products").show();
        clearTimeout(timerCart);
    });
    $("#view-cart").mouseleave(function () {
        timerCart = setTimeout(function () { $("#cart-products").hide() }, 500);
    });
    $("#cart-products").mouseenter(function () {
        clearTimeout(timerCart);
    });
    $("#cart-products").mouseleave(function () {
        timerCart = setTimeout(function () { $("#cart-products").hide() }, 500);
    });

    /* Popup
    ___________________________________________________*/
    /*
    $(".pop-close").click(function () {
        $(this).parent().hide();
        return false;
    });
    */

    /* -- Retrieve password -- */

    if (document.location.hash.indexOf('retrievepassword') > 0) {
        //Show retrieve password at startup if #retrievepassword exist
        $("#pop-retrieve-password-message-ok").hide();
        $("#pop-retrieve-password-message-error").hide();

        var pos = $("#forgotten-password").position();
        $("#pop-retrieve-password").css({ "left": (pos.left - 4) + "px", "top": (pos.top + 8) + "px" });
        $("#pop-retrieve-password").show();
        $("#forgotten-password").addClass("expanded");
    }

    $("#forgotten-password, #forgotten-password-showagain, #forgotten-password-login-error").click(function () {        
        
        $("#pop-retrieve-password-message-ok").hide();
        $("#pop-retrieve-password-message-error").hide();

        var pos = $(this).position();
        $("#pop-retrieve-password").css({ "left": (pos.left - 4) + "px", "top": (pos.top + 8) + "px" });
        $("#pop-retrieve-password").show();
        $(this).addClass("expanded");
        return false;
    });
//    $("#pop-retrieve-password .pop-close").click(function () {
//        $("#forgotten-password").removeClass("expanded");
//        return false;
//    });

    /* -- Tips -- */

    /*
    $("a.tip").click(function () {
        var pos = $(this).position();
        $("#pop-send-tips").css({ "left": (pos.left - 16) + "px", "top": (pos.top + 14) + "px" });
        $("#pop-send-tips").show();
        return false;
    });
    */

    /* -- Write note -- */

    $("a.write-note").click(function () {
        var pos = $(this).position();
        $("#pop-write-note").css({ "left": (pos.left - 148) + "px", "top": (pos.top + 14) + "px" });
        $("#pop-write-note textarea").val("");
        $("#pop-write-note").show();
        return false;
    });

    /* -- User profile -- */

    $("#news-list").scrollable({
        vertical: true,
        size: 1,
        clickable: false
    }).autoscroll(5500).circular(); // Interval 




    /* Rating
    ___________________________________________________*/

    $(".star-rating-control a").removeAttr("title");

    $("a.profileLink").live("click", function () {
        showProfile($(this).attr("href").substr(2), this);
        return false;
    });
}


function showProfile(profilename, source) {
    //Load profile from ajax
    if (profilename.length > 0) {
        query = "?username=" + profilename;
        $.ajax({
            type: 'POST',
            data: { control: 'ProfilePopup' },
            url: baseUrl + "Service/Bygginfo.asmx/GetControl" + query,
            success: function (msg, textStatus, request) {
                $("#pop-profile").html($(msg).find("string").text());
                var pos = $(source).position();
                $("#pop-profile").css({ "left": (pos.left + 6) + "px", "top": (pos.top - 70) + "px" });
                $("#pop-profile").show();


                $("#pop-profile .pop-close").click(function () {
                    $(this).parent().hide();
                    return false;
                });

                return false;

            }
        });
    } else {
        alert("Användaren är anonym.");
        return false;
    }
}


//Delete Bookmark
function BookmarkDelete(BookmarkId) {
    $.ajax({
        type: 'GET',
        data: { BookmarkId: BookmarkId },
        url: baseUrl + "Service/Bygginfo.asmx/BookmarkDelete",
        success: function (msg, textStatus, request) {
        }
    });
}

//Save Bookmark
function BookmarkSave(BookmarkId, ParentId, Type, Service, Url, Title) {
    $.ajax({
        type: 'GET',
        data: { BookmarkId: BookmarkId, ParentId: ParentId, Type: Type, Service: Service, Url: Url, Title: Title },
        url: baseUrl + "Service/Bygginfo.asmx/BookmarkSave",
        success: function (msg, textStatus, request) {
           
        }
    });
}

function BookmarkPopup(Eid) {
    openModalDialogue(baseUrl + 'Bookmarks/Bookmarks.aspx?Eid=' + Eid, false, 765, 550, true);
}

/* Webpoll */
function WebPollShow(Form) {
    if (Form) {
        $(".WebPollForm").show("slow");
        $(".WebPollStatistics").hide("slow");
    }
    else {
        $(".WebPollForm").hide("slow");
        $(".WebPollStatistics").show("slow");
    }
}


//Record links for G-A
function RecordLink(category, action, label, reload, link) {
    //alert(category + ' - ' + action + ' - ' + label);
    try {
        //alert(category + ' - ' + action + ' - ' + label + ' - ' + reload + ' - ' + link);
        var pageTracker = _gat._getTracker("UA-5482766-1");
        pageTracker._trackEvent(category, action, label)
        if (reload)
            setTimeout('document.location = "' + link.href + '"', 100);
        else
            setTimeout('', 100);
    } catch (err) {
    }
}


/* Guide */
function GuideShow(Type) {
    var width = 520;
    var height = 500;
    var url = '';

    if (Type == 1 || Type == 4) {
        //Track klick - 4=from autopopup
        var auto = '';
        if (Type == 4) {
            auto = '&a=true';
            RecordLink('Guide', 'open', 'Hela guiden autopop', 0, '');
        }
        else
            RecordLink('Guide', 'open', 'Hela guiden', 0, '');

        width = 520;
        height = 450;
        url = baseUrl + 'Guide/?d=' + (new Date()).valueOf() + auto;
    }
    else if (Type == 2) {
        //Track klick
        RecordLink('Guide', 'open', 'Fackomrade', 0, '');
        width = 500;
        height = 270;
        url = baseUrl + 'Guide/Trade.aspx?guide=false&d=' + (new Date()).valueOf();
    }
    else if (Type == 3) {
        //Track klick
        RecordLink('Guide', 'open', 'Sortering', 0, '');
        width = 500;
        height = 270;
        url = baseUrl + 'Guide/Sort.aspx?d=' + (new Date()).valueOf();
    }

    if (Type >= 1 && Type <= 4) {
        $("#dialog-modal iframe").attr('src', url);
        $("#dialog-modal iframe").attr('width', (width - 25));
        $("#dialog-modal iframe").attr('height', (height - 30));
        $("#dialog-modal .button").hide();
        $("#dialog-modal").dialog("destroy");

        $("#dialog-modal").dialog({
            height: height,
            width: width,
            modal: true
        });
    }
}

function GuideReload() {
    closeModalDialog();
    window.location.reload(true);
}

function TradeGoogle(obj, type) {
    //var name = '';

    $(obj).find('input').each(function () {
        
        if (this.checked) {
            //name = name + type +' - Active -' + $(this).parent('span').attr("title") + '\n';

            RecordLink(type, 'Active', $(this).parent('span').attr("title"), 0, '');
        }
        else {
            RecordLink(type, 'Inactive', $(this).parent('span').attr("title"), 0, '');
            //name = name + type + ' - Inactive -' + $(this).parent('span').attr("title") + '\n';        
        }

    });
    //alert(name);    
}


$(document).ready(function () {

    $('.guide-trade span input').click(function () {

        var checked = $(this).is(':checked');
        var tag = $(this).parent().attr('title');
        var active = 'Inactive';
        if (checked)
            active = 'Active';
        //alert('1: - ' + tag + ' - ' + checked + ' - ' + active);

        //Track klick
        RecordLink('Prioritet', active, tag, 0, '');

    });
});

