var currentPageClass = "page-number page-current";
var pageClass = "page-number";
var prevClass = "prev";
var nextClass = "next";

function RequestInfo(status) {
    this.isAuthenticated = status;

    this.IsRequestAuthenticated = function () {
        return this.isAuthenticated;
    };
};

$.fn.setEqualBlocksHeight = function (count) {
    if (count == 'all' || count > this.length) count = this.length; count = parseInt(count); if (count > 1) {
        this.css({ height: 'auto', 'min-height': 0 });
        for (var i = 1; i <= this.length; i += count) {
            var sameH = 0; for (var j = 0; j <= count - 1; j++) {
                if (this.get(i + j - 1))
                { var blockH = this.eq(i + j - 1).height(); sameH = (blockH > sameH) ? (sameH = blockH) : sameH }
            }
            for (var j = 0; j <= count - 1; j++) {
                if (this.get(i + j - 1))
                { this.eq(i + j - 1).css({ 'min-height': sameH + 1 }); if ($.browser.msie && $.browser.version == '6.0') this.eq(i + j - 1).height(sameH) }
            }
        }
    }; if (count == 1) this.css({ height: 'auto', 'min-height': 0 }); return this;
};

jQuery.fn.limitMaxlength = function (options) {

    var settings = jQuery.extend({
        attribute: "maxlength",
        onLimit: function () { },
        onEdit: function () { }
    }, options);

    // Event handler to limit the textarea
    var onEdit = function () {
        var textarea = jQuery(this);
        var maxlength = parseInt(textarea.attr(settings.attribute));

        if (textarea.val().length > maxlength) {
            textarea.val(textarea.val().substr(0, maxlength));

            // Call the onlimit handler within the scope of the textarea
            jQuery.proxy(settings.onLimit, this)();
        }

        // Call the onEdit handler within the scope of the textarea
        jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
    }

    this.each(onEdit);

    return this.keyup(onEdit)
	                .keydown(onEdit)
	                .focus(onEdit)
	                .live('input paste', onEdit);
}

//Masonry
function orderingImg(el, ch, chw, cropEl, portrateElH, lanscapeElH) {
    $(el).wrap('<div class="b-wrap-overflow" />');
    var $albumsContainer = $(el);
    $albumsContainer.imagesLoaded(function () {
        CropImageByHeight(cropEl, portrateElH, lanscapeElH);
        if ($albumsContainer.data('masonry')) {
            $albumsContainer.data('masonry').reload();
        } else {
            $albumsContainer.masonry({
                itemSelector: ch,
                columnWidth: chw
            });
        }
        $(el).unwrap();
    });
}

// pager
function widthOfPager(el) {
    $(el).css('width', function () { var elW = null; $(this).children().each(function () { elW += $(this).outerWidth(true); }); return elW; });
}

function BlockRoomFilterChecking(id, checkbox) {
    if ($(id).attr('checked') == true) {
        ApplyRoomFilter();
    }
    else {
        $(checkbox).attr('checked', true);
        checkboxCheck(checkbox);
    }
}

function BlockSearchRoomFilterChecking(id, checkbox) {
    if ($(id).attr('checked') == true) {
        ApplySearchRoomFilter();
    }
    else {
        $(checkbox).attr('checked', true);
        checkboxCheck(checkbox);
    }
}

//list view
function viewItems(el) {
    $('.b-view > .i-grid').click(function () {
        $('.b-view span').removeClass('current');
        $(this).addClass('current');
        $(el).attr('class', 'grid-items');
        $('.grid-items li').setEqualBlocksHeight('3');
        ResizeImage('.b-home-stories_img-wrap');

    });
    $('.b-view > .i-list').click(function () {
        $('.b-view span').removeClass('current');
        $(this).addClass('current');
        $(el).attr('class', 'list-items');
        $(el).find('li').removeAttr('style');
        ResizeImage('.b-home-stories_img-wrap');
    });
}

function showAllItems(el, count) {
    var numb = $(el).find('li').length;
    if (numb >= count) {
        $(el).wrap('<div class="b-limit-items" />');
        var elHeight = 0;
        for (i = 0; i < count; i++) {
            elHeight += $(el).find('li').eq(i).outerHeight() - 2;
        }
        $('.b-limit-items').animate({ height: elHeight });
        var ShowAllText=$('.b-blog-show-all').val();
        $('.b-limit-items').parent().append('<a href="#" class="b-link-show-all">'+ShowAllText+'</a>');
        $('.b-link-show-all').click(function () {
            $(el).unwrap();
            $(this).remove();
            return false;
        });
    }
}


// Scrolbar
function hookEvent(element, eventName, callback) {
    if (typeof (element) == "string")
        element = document.getElementById(element);
    if (element == null)
        return;
    if (element.addEventListener) {
        if (eventName == 'mousewheel')
            element.addEventListener('DOMMouseScroll', callback, false);
        element.addEventListener(eventName, callback, false);
    }
    else if (element.attachEvent)
        element.attachEvent("on" + eventName, callback);
}
function cancelEvent(e) {
    e = e ? e : window.event;
    if (e.stopPropagation)
        e.stopPropagation();
    if (e.preventDefault)
        e.preventDefault();
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}
function MouseWheel(e) {
    e = e ? e : window.event;
    var wheelData = e.detail ? e.detail : e.wheelDelta;
    //do something
}

function checkboxCheck(el) {
    var eID = $(el).attr('id');
    $('.b-filter-viewing').hide();

    if ($(el).attr('checked') == true) {
        $(el).parent().addClass("checkboxOn");
        $(el).parents('li').find('label').addClass("checked");

        var eText = $(el).parents('li').find('label').text();
        if (eText == "") {
            var eText = $(el).parents('li').find('span').text();
        }
        $('.b-filter-viewing strong').after('<span class="' + eID + '">' + eText + '<i class="i-close">&nbsp;</i></span>');

        $('.b-filter-viewing').show();

    } else {
        $(el).parent().removeClass("checkboxOn");
        $(el).parents('li').find('label').removeClass("checked");
        $('.b-filter-viewing > span').remove('[class="' + eID + '"]');

        $('.b-filter-viewing').has("span").show();
    }
}

function ValidateEmailPageForm(subject, emailAddress) {
    var validationResult = true;

    if (!subject || subject == '') {
        $('#js-emailpage-subject-error').show();
        validationResult = false;
    }

    if (emailAddress) {
        if (emailAddress == '') {
            $('#js-emailpage-emailaddress-required-error').show();
            validationResult = false;
        }
        else {
            var expr = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            if (!expr.test(emailAddress)) {
                $('#js-emailpage-emailaddress-invalid-error').show();
                validationResult = false;
            }
        }
    }
    else {
        $('#js-emailpage-emailaddress-required-error').show();
        validationResult = false;
    }

    return validationResult;
}
function iconfirm(a) {

}
function ClearEmailPageValidationMessages() {
    $('#js-emailpage-subject-error').hide();
    $('#js-emailpage-emailaddress-required-error').hide();
    $('#js-emailpage-emailaddress-invalid-error').hide();
}

function chHeightImg(el, maxH) {
    $(el).each(function () {
        var elH = $(this).height();
        var elW = $(this).width();
        var maxW = $(this).parent().width();

        //if(elH > maxH){
        var posT = (elH - maxH) / 2;
        var posL = (elW - maxW) / 2;
        $(this).parent().css({ 'position': 'relative', 'height': maxH });
        $(this).css({
            'position': 'absolute',
            'left': -posL,
            'top': -posT
        });
        //}
    });
}

function CropImageByHeight(cropEl, portrateElH, lanscapeElH) {
    $(cropEl).each(function () {
        var widthEl = $(this).width();
        var imgH = $(this).find('img').height();
        var imgW = $(this).find('img').width();

        if (imgW < imgH) {
            imgW = (imgW * portrateElH) / imgH;
            if (imgW < widthEl) {
                imgW = widthEl;
            }
            $(this).css('height', portrateElH);
            $(this).find('img').attr('width', imgW);
        } else {
            imgW = (imgW * lanscapeElH) / imgH;
            if (imgW < widthEl) {
                imgW = widthEl;
            }
            $(this).css('height', lanscapeElH);
            $(this).find('img').attr('width', imgW);
        }
    });
}

function ResizeImage(el) {
    $(el).each(function () {
        $(this).imagesLoaded(function () {
            var el_width = $(this).outerWidth();
            var el_height = $(this).outerHeight();
            var image = $(this).find('img');
            var image_width = image.width();
            var image_height = image.height();

            if (image_width < image_height) {
                image_height = (el_width * image_height) / image_width;
                if (image_height < el_height) {
                    image_height = el_height;
                }
                image.css({
                    'position': 'absolute',
                    'left': 0,
                    'top': -(image_height - el_height) / 2
                });
                image.attr({ 'height': image_height });
            } else {
                image_width = (image_width * el_height) / image_height;
                if (image_width < el_width) {
                    image_width = el_width;
                }
                image.css({
                    'position': 'absolute',
                    'top': 0,
                    'left': -(image_width - el_width) / 2
                });
                image.attr({ 'width': image_width });
            };
        });
    });
}

function LoadComments() {
    var totalPages = Math.ceil(cpagerInfo.TotalElements / cpageSize);
    if (cpagerInfo.CurrentPage < totalPages) {
        cpagerInfo.CurrentPage++;
        if (cpagerInfo.CurrentPage == totalPages) {
            $("#js-show-more-comments").hide();
        }
    }

    var homeStoryId = $("#js-entityid").val();
    var type = $("#js-type").val();
    $.ajax(
            {
                url: '/en/comments/getcomments',
                context: document.body,
                type: "post",
                dataType: "json",
                data: "{'itemId':'" + homeStoryId +
                        "','page':'" + cpagerInfo.CurrentPage +
                        "','type':'" + type + "'}",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                success: function (data) {
                    if (data != null) {
                        ProcessCommentsResponseResult(data);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                }
            });
}

function AddComment() {
    var entityId = $("#js-entityid").val();
    var type = $("#js-type").val();
    var comment = $("#js-comment").val();

    if (!entityId || !type) {
        return;
    }

    $.ajax(
    {
        url: '/en/comments/addcomment',
        context: document.body,
        type: "post",
        dataType: "json",
        data: $.toJSON({ entityId: entityId, t: type, comment: comment }),
        contentType: "application/json; charset=utf-8",
        timeout: 10000,
        success: function (data) {
            if (data != null) {
                if (data.status == 'success') {
                    AddCommentToList(data);
                    $("#js-comment").val('');
                    $("#js-field-validation-error").hide();
                    $("#js-comment-total").text(data.CommentsListInfo.TotalCount);

                    cpagerInfo.CurrentPage = 1;
                    cpagerInfo.TotalElements = data.CommentsListInfo.TotalCount;

                    if (cpagerInfo.TotalElements > cpageSize) {
                        $("#js-show-more-comments").show();
                    }
                    else {
                        $("#js-show-more-comments").hide();
                    }
                }
                else {
                    $("#js-field-validation-error").text(data.errorMessage);
                    $("#js-field-validation-error").show();
                }
            }
        }
    });
}

function AddCommentToList(data) {
    var commentsContainer = $("#js-comments");
    if (data.Comments) {
        commentsContainer.processTemplate({ Comments: data.Comments, Resources: data.LocalizedResources });
    }
}
function ProcessCommentsResponseResult(data) {
    var commentsContainer = $("#js-comments");
    var oldComments = commentsContainer.html();
    if (data.Comments.length > 0) {
        commentsContainer.processTemplate({ Comments: data.Comments, Resources: data.LocalizedResources });
        commentsContainer.prepend(oldComments);
    }
}

function UpdateListInfo() {
    var currentItems = pagerInfo.CurrentPage * pageSize > pagerInfo.TotalElements ? pagerInfo.TotalElements : pagerInfo.CurrentPage * pageSize;
    $(".js-currentItems").text(currentItems);
    $(".js-totalItems").text(pagerInfo.TotalElements);

    if (pagerInfo.TotalElements == 0) {
        $(".b-count-results").hide();
        $("#ddlSortOptions").hide();
       // $(".jNice.sort-opt").hide();
    }
    else {
        $(".b-count-results").show();
        $("#ddlSortOptions").show();
    }
}

function GetSelectedOptionsInSting(optionClassName) {
    var strSelectedOptions = "";
    $(optionClassName).each(function () {
        if ($(this).attr('checked')) {
            if (strSelectedOptions != "") {
                strSelectedOptions += ",";
            }
            strSelectedOptions += $(this).val();
        }
    });

    return strSelectedOptions;
}

function ClearSelectedOptions(optionClassName) {
    $(optionClassName).each(function () {
        $(this).attr('checked', false);
        checkboxCheck(this);
    });
}

function ApplyHomeStoriesFilter() {
    clearTimeout(filterTimer);
    filterTimer = setTimeout(function () {

        var selectedHomeTypes = GetSelectedOptionsInSting(".js-hometype");
        var selectedInterests = GetSelectedOptionsInSting(".js-interests");
        var selectedStyles = GetSelectedOptionsInSting(".js-style");
        var selectedCountries = GetSelectedOptionsInSting(".js-countries");
        var selectedThemes = GetSelectedOptionsInSting(".js-theme");
        var sortByValue = $("#ddlHomeStorySortOptions").val();

        $.ajax(
            {
                url: '/en/home-stories/applyfilter',
                context: document.body,
                type: "post",
                dataType: "json",
                data: "{'sortByValue':'" + sortByValue +
                        "','strSelectedHomeTypes':'" + selectedHomeTypes +
                        "','strSelectedInterests':'" + selectedInterests +
                        "','strSelectedStyles':'" + selectedStyles +
                        "','strSelectedCountries':'" + selectedCountries +
                        "','strSelectedThemes':'" + selectedThemes + "'}",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                success: function (data) {
                    if (data != null) {
                        pagerInfo.CurrentPage = 1;
                        ProcessHomeStoriesResponseResult(data);
                        BuildAjaxPager();
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                }
            });
    }, 1000);
}

function ApplyRoomFilter() {
    clearTimeout(filterTimer);
    filterTimer = setTimeout(function () {
        var selectedColours = GetSelectedOptionsInSting(".js-r-colours");
        var selectedStyles = GetSelectedOptionsInSting(".js-r-styles");
        var selectedCountries = GetSelectedOptionsInSting(".js-r-countries");
        var sortByValue = $("#ddlSortOptions").val();
        var ikeaLive = $("#IkeaLive").attr('checked');
        var members = $("#Member").attr('checked');
        var includeVideos = $("#IncludeVideos").attr('checked');

        $.ajax(
            {
                url: '/en/rooms/applyfilter',
                context: document.body,
                type: "post",
                dataType: "json",
                data: "{ 'colours':'" + selectedColours +
                        "', 'styles':'" + selectedStyles +
                        "', 'countries':'" + selectedCountries +
                        "', 'orderBy':'" + sortByValue +
                        "', 'ikeaLive':'" + ikeaLive +
                        "', 'member':'" + members +
                        "', 'includeVideo':'" + includeVideos +
                        "', 'roomCategoryId':'" + roomCategoryId + "' }",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                success: function (data) {
                    if (data != null) {
                        pagerInfo.CurrentPage = 1;
                        ProcessRoomsResponseResult(data);
                        BuildAjaxPager();
                        orderingImg('.b-rooms-albums', '.b-room-thumbnail', 320, '.b-room-thumbnail-wrap', 386, 233);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                }
            });
    }, 1000);
}

function ApplySearchRoomFilter() {
    clearTimeout(filterTimer);
    filterTimer = setTimeout(function () {

        var selectedColours = GetSelectedOptionsInSting(".js-s-r-colours");
        var selectedCategories = GetSelectedOptionsInSting(".js-s-r-categories");
        var selectedStyles = GetSelectedOptionsInSting(".js-s-r-styles");
        var selectedCountries = GetSelectedOptionsInSting(".js-s-r-countries");
        var sortByValue = $("#ddlSearchSortOptions").val();
        var ikeaLive = $("#chkSearchRoomIkeaLive").attr('checked');
        var members = $("#chkSearchRoomMembers").attr('checked');
        var includeVideos = $("#chkSearchRoomIncludeVideos").attr('checked');

        $.ajax(
            {
                url: '/en/search/applyfilter',
                context: document.body,
                type: "post",
                dataType: "json",
                data: "{ 'colours':'" + selectedColours +
                        "', 'categories':'" + selectedCategories +
                        "', 'styles':'" + selectedStyles +
                        "', 'countries':'" + selectedCountries +
                        "', 'orderBy':'" + sortByValue +
                        "', 'ikeaLive':'" + ikeaLive +
                        "', 'member':'" + members +
                        " ','includeVideo':'" + includeVideos + "' }",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                success: function (data) {
                    if (data != null) {
                        pagerInfo.CurrentPage = 1;
                        ProcessSearchRoomsResponseResult(data);
                        BuildAjaxPager();
                        orderingImg('.b-search-rooms-albums', '.b-search-room-thumbnail', 237, '.b-search-room-thumbnail-wrap', 291, 176);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                }
            });
    }, 1000);
}

function ClearHomeStoriesSelectedFields() {
    ClearSelectedOptions(".js-hometype");
    ClearSelectedOptions(".js-interests");
    ClearSelectedOptions(".js-style");
    ClearSelectedOptions(".js-countries");
    ClearSelectedOptions(".js-theme");
    ApplyHomeStoriesFilter();
}

function ClearRoomsSelectedFields() {
    ClearSelectedOptions(".js-r-colours");
    ClearSelectedOptions(".js-r-styles");
    ClearSelectedOptions(".js-r-countries");
    ApplyRoomFilter();
}

function ClearSearchRoomsSelectedFields() {
    ClearSelectedOptions(".js-s-r-colours");
    ClearSelectedOptions(".js-s-r-categories");
    ClearSelectedOptions(".js-s-r-styles");
    ClearSelectedOptions(".js-s-r-countries");
    ApplySearchRoomFilter();
}

function BuildAjaxPager() {
    var totalpages = Math.ceil(pagerInfo.TotalElements / pageSize);
    var pagesInGroup = 5;
    var currentGroup;
    if (pagerInfo.CurrentPage % pagesInGroup == 0) {
        currentGroup = Math.floor(pagerInfo.CurrentPage / pagesInGroup) - 1;
    }
    else {
        currentGroup = Math.floor(pagerInfo.CurrentPage / pagesInGroup);
    }

    var startPage = currentGroup * pagesInGroup + 1;
    var endPage = currentGroup * pagesInGroup + pagesInGroup;
    if (endPage > totalpages) {
        endPage = totalpages;
    }

    if (pagerInfo.CurrentPage > totalpages) {
        pagerInfo.CurrentPage = totalpages;
    }

    $(".b-pager").processTemplate({ CurrentPage: pagerInfo.CurrentPage, PagesCount: totalpages, start: startPage, end: endPage });
    widthOfPager('.b-pager');
}

function LoadHomeStories() {
    $.ajax(
        {
            url: '/en/home-stories/gethomestories',
            context: document.body,
            type: "post",
            dataType: "json",
            data: "{'page':'" + pagerInfo.CurrentPage + "'}",
            contentType: "application/json; charset=utf-8",
            timeout: 10000,
            success: function (data) {
                if (data != null) {
                    ProcessHomeStoriesResponseResult(data);
                    BuildAjaxPager();
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
            }
        });
}

function LoadRooms() {
    $.ajax(
        {
            url: '/en/rooms/getrooms',
            context: document.body,
            type: "post",
            dataType: "json",
            data: "{'page':'" + pagerInfo.CurrentPage + "', 'roomCategoryId':'" + roomCategoryId + "'}",
            contentType: "application/json; charset=utf-8",
            timeout: 10000,
            success: function (data) {
                if (data != null) {
                    ProcessRoomsResponseResult(data);
                    BuildAjaxPager();
                    orderingImg('.b-rooms-albums', '.b-room-thumbnail', 320, '.b-room-thumbnail-wrap', 386, 233);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
            }
        });
}

function LoadSearchRooms() {
    $.ajax(
        {
            url: '/en/search/getrooms',
            context: document.body,
            type: "post",
            dataType: "json",
            data: "{'page':'" + pagerInfo.CurrentPage + "'}",
            contentType: "application/json; charset=utf-8",
            timeout: 10000,
            success: function (data) {
                if (data != null) {
                    ProcessSearchRoomsResponseResult(data);
                    BuildAjaxPager();
                    orderingImg('.b-search-rooms-albums', '.b-search-room-thumbnail', 237, '.b-search-room-thumbnail-wrap', 291, 176);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
            }
        });
}

function ScrollToTop() {
    $("html, body").scrollTop($("h1").position().top);
}

function ProcessHomeStoriesResponseResult(result) {
    pagerInfo.TotalElements = result.ListInfo.TotalCount;

    $("#js-items").empty();

    if (result.HomeStories.length == 0) {
        $("#js-items").html("<li><p class='no-results'>" + result.LocalizedResources.NoResultsLabel + "</p></li>");
    }
    else {
        $("#js-items").processTemplate({ HomeStories: result.HomeStories, Resources: result.LocalizedResources });
    }
    $('.grid-items li').setEqualBlocksHeight('3');
    ResizeImage('.b-home-stories_img-wrap');

    UpdateListInfo();
    ScrollToTop();
}

function ProcessRoomsResponseResult(result) {
    pagerInfo.TotalElements = result.ListInfo.TotalCount;

    $(".b-rooms-albums").empty();

    if (result.Rooms.length == 0) {
        $(".b-rooms-albums").html("<p class='no-results'><span class='no-results'>" + result.LocalizedResources.NoResultsLabel + "</span></p>");
        $(".jNice.sort-opt").hide();
    }
    else {
        $(".b-rooms-albums").processTemplate({ Rooms: result.Rooms, Resources: result.LocalizedResources });
        $(".jNice.sort-opt").show();
    }

    UpdateListInfo(result.ListInfo);
    ScrollToTop();
}

function ProcessSearchRoomsResponseResult(result) {
    pagerInfo.TotalElements = result.ListInfo.TotalCount;

    $("#js-search-results-total-count").text(result.ListInfo.TotalCount);

    $(".b-search-rooms-albums").empty();

    if (result.Rooms.length == 0) {
        $(".b-search-rooms-albums").html("<p class='no-results'><span class='no-results'>" + result.LocalizedResources.NoResultsLabel + "</span></p>");
    }
    else {
        $(".b-search-rooms-albums").processTemplate({ Rooms: result.Rooms, Resources: result.LocalizedResources });
    }

    UpdateListInfo(result.ListInfo);
}

function pagerClick(pageLink) {
    if (pageLink.hasClass(prevClass)) {
        if (pagerInfo.CurrentPage > 1) {
            pagerInfo.CurrentPage--;
        }
    }
    else if (pageLink.hasClass(nextClass)) {
        if (pagerInfo.CurrentPage < Math.ceil(pagerInfo.TotalElements / pageSize)) {
            pagerInfo.CurrentPage++;
        }
    }
    else {
        pagerInfo.CurrentPage = parseInt(pageLink.text());
    }
}

function showConfirmation() {
    var el = $('.b-scrapbook-confirmation');
    el.stop(true, true).show();
    el.animate({ opacity: 0 }, 4000, function () {
        el.hide().css({ opacity: 1 });
    });
}

function AddToScrapbook() {
    var pid = $("#js-pid").val();
    var scrapbookId = $(this).parent().attr("id");
    if (scrapbookId && pid) {
        $.post("/en/scrapbook/addphototoscrapbook", { photoId: pid, scrapbookId: scrapbookId });
        $(".b-scrapbook-confirmation_album").text($(this).text());
        LoadScrapbooks(spSelectedScrapbook);
        var scrapbooksCount = $('#js-count-'+pid).html();
        if (scrapbooksCount == '') {
            $('#js-link-' + pid).addClass('i-scrapbook-withcount');
            scrapbooksCount = 1;
        }
        else {
            scrapbooksCount++;
        }
        $('#js-count-'+pid).html(scrapbooksCount);
        
        showConfirmation();
    }

    $(".b-scrapbook-box").hide();
}

function AddToNewScrapbook() {
    var pid = $("#js-pid").val();
    var scrapbookName = $("#js-scrapbook-name").val();
    if (scrapbookName && pid) {
        $.ajax(
            {
                url: '/en/scrapbook/addphototonewscrapbook',
                context: document.body,
                type: "post",
                dataType: "json",
                data: "{'photoId':'" + pid + "','scrapbookName':'" + escape(scrapbookName) + "'}",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                success: function (data) {
                    if (data != null) {
                        if (data > 0) {
                            var sbname = $('<div/>').text(scrapbookName).html();
                            $("#js-scrapbooks").prepend("<li id=\"" + data + "\"><span class=\"js-scrapbook-title\">" + sbname + "</span></li>");
                            $("#js-scrapbooks li.no-results").remove();
                            $("#js-scrapbook-name").val('');
                            $(".scrapbook-pane-no-images").remove();
                            $("#js-sp-scrapbooks").prepend('<li><a id="' + data + '" href="#" class="js-sp-scrapbook-title">' + sbname + '</a></li>');
                            $('.b-scrapbook-pane_nav_top ul').jScrollPane({ showArrows: true, scrollbarWidth: 12 });
                            $(".b-scrapbook-confirmation_album").text(sbname);
                            showConfirmation();

                            if ($("#js-scrapbooks li").length == 1) {
                                spSelectedScrapbook = data;
                                LoadScrapbooks(data);
                                $("#js-scrapbooks li").addClass("current");
                            }
                        }
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                }
            });
    }
}

function AddRoomToNewScrapbook() {
    if (RequaredFieldValidate($("#js-scrapbook-name").val(), '@Html.Resource("client-label-enter-scrapbook-name")')) {
        AddToNewScrapbook();
        $("#js-scrapbook-name-error-requared").hide();
        $.fancybox.close();
    }
    else {
        $("#js-scrapbook-name-error-requared").show();
    }
}

function LoadScrapbooks(scrapbookId) {
    $.ajax(
            {
                url: '/en/scrapbook/getscrapbookphotos',
                context: document.body,
                type: "post",
                dataType: "json",
                data: "{'scrapbookId':'" + scrapbookId + "'}",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                success: function (data) {

                    if (data != null) {
                        if (data.Status == "success") {
                            $("#js-sp-edit-scrapbook").attr('href', data.ScrapbookUrl + "#edit-albums");
                            $("#js-sp-view-all").attr('href', data.ScrapbookUrl);
                            $("#js-sp-photoscount").text(data.PhotosCount);

                            if (data.PhotosCount == 1) {
                                $("#js-sp-photoscount-label").text(lblImage);
                            }
                            else {
                                $("#js-sp-photoscount-label").text(lblImages);
                            }

                            if (data.PhotosCount == 0) {
                                $("#js-sp-links").hide();
                            }
                            else {
                                $("#js-sp-links").show();
                            }
                            $("#js-sp-photos").processTemplate({ Photos: data.Photos, Resources: data.LocalizedResources });
                            $("a.b-scrapbook-pane_lightbox").fancybox({
                                overlayColor: '#000',
                                overlayOpacity: 0.8,
                                autoScale: true,
                                autoDimensions: true,
                                scrolling: 'no',
                                titlePosition: 'outside',
                                titleFormat: function (title, currentArray, currentIndex, currentOpts) {
                                    return $('.b-scrapbook-pane_img').eq(currentIndex).find('.js-sp-details').html();
                                }
                            });
                        }
                    }
                }
            });
}

function CropingImgForPageDetails(el, elW) {
    //$('.b-room-det-img-wrap').imagesLoaded(function () {    	
        var imgW = $(el).delay(9000).find('img').width();
        var imgH = $(el).delay(9000).find('img').height();        
        $(el).find('img').hide();

        if (imgW < imgH) {        	
            var resizeImgH = ($(el).width() / imgW) * imgH;
            if (resizeImgH < $(el).height()) {
                $(el).find('img').show();
                $(el).find('img').css('height', $(el).height());
            }
            else {
                $(el).find('img').show();
                $(el).find('img').css('width', $(el).width());
            }
        } else {        	
            $(el).find('img').show();
            $(el).css({ 'width': elW });

            var resizeImgW = ($(el).height() / imgH) * imgW;
            if (resizeImgW < elW) {
                $(el).find('img').show();
                $(el).find('img').css({ 'width': elW });
            }
            else {
                $(el).find('img').show();
                $(el).find('img').css({ 'height': $(el).height() });
            }
        }
    //});
}
function HeightScrapLoadIMG() {
    var f = $('.b-upload-photo').size();

    if (f != 0) {
        var h = $('.b-profile-pr-column').height() - 20;
        $('.b-profile-sec-column').css({ 'min-height': h });
    }

}
function HeightLeftCol() {
    var h = $('.b-col-right').height() - $('.b-comments').outerHeight() - 80;
    if ($.browser.webkit) {
  		h+=76;
  		
  			}
    $('.b-col-left').css({ 'height': h });
}
function ReCallerCropingImg(){
	CropingImgForPageDetails('.b-room-det-img-wrap', 700)
}
$(document).ready(function () {
    $(window).resize(function () {
        if ($('.b-container').outerHeight() < $(window).height()) {
            var boxHeight = $(window).height() - $('.b-footer').height() - 66;
            $('.b-container').css('min-height', boxHeight);
        }
    });

    if ($('.b-container').outerHeight() < $(window).height()) {
        var boxHeight = $(window).height() - $('.b-footer').height() - 66;
        $('.b-container').css('min-height', boxHeight);
    }

    ResizeImage('.b-home-stories_img-wrap');
    ResizeImage('.b-home_img-wrap');
    ResizeImage('.b-wrap-img_83');
    ResizeImage('.b-wrap_latest-stories');
    ResizeImage('.latest-post-img');
    ResizeImage('.b-wrap_blog-item');
    ResizeImage('.b-wrap-img_63');
    ResizeImage('.bp-photo');
    HeightScrapLoadIMG();
    HeightLeftCol();

    $("#js-scrapbook-name").keydown(function (e) {
        if (e.keyCode == 13) {
            AddRoomToNewScrapbook();
        }
    });

    $('.l-sec-nav a').click(function () {
        $(this).parents('ul').find('li.current').removeClass('current'); $(this).parent().addClass('current');

        var link = $(this).attr('href');
        var pos = $(link).position();
        var pos1 = $('.b-column-primary').position();
        var posLink = pos.top;
        var posMenu = $('.l-sec-nav').position();
        var posCur = $('.l-sec-nav .current').position();
        var HeigToCur = posCur.top;
        var NewPosition = posLink - HeigToCur - 8;
        if ($.browser.webkit) {
            NewPosition -= 66;
        }
        $('body, html').animate({ scrollTop: NewPosition }, 600);
        return false;
    });

    TuneFbLikeButtonWidth(TuneFbLikeButtonWidthCallback);

    $("#js-items").setTemplateURL('/en/htmltemplates/homestory.html', [], { filter_data: false });
    $(".b-pager").setTemplateURL('/en/htmltemplates/pager.html');
    $(".b-rooms-albums").setTemplateURL("/en/htmltemplates/room.html");
    $(".b-search-rooms-albums").setTemplateURL("/en/htmltemplates/searchroom.html");
    $("#js-comments").setTemplateURL('/en/htmltemplates/comment.html');
    $("#js-sp-photos").setTemplateURL('/en/htmltemplates/scrapbookimage.html', [], { filter_data: false });

    $('.b-scrapbooks .b-inner-light').setEqualBlocksHeight('3');
    // CropingImgForPageDetails('.b-room-det-img-wrap', 700);
    setTimeout(ReCallerCropingImg, 200);
    showAllItems('.b-blogers', 7);

    $('textarea[maxlength]').limitMaxlength({});

    //show & hide editing on profile	
    $('a.b-profile-edit').click(function () {
        var elID = $(this).attr('href');
        if ($(this).attr('id') != '') { $(this).toggle(); } else { $(this).parent().toggle(); }
        $(elID).toggle();
        return false;
    });


    //filter viewing
    $('.b-filter-viewing .i-close').live("click", function () {
        var eID = $(this).parent().attr('class');
        $(this).parent().remove();
        $('#' + eID).click();
    });

    // show & hide the filter
    $('#show-filter').removeClass('hide');

    $('.bf-title > span.bf-switch').click(function () {
        $(this).parent().toggleClass('filter-open');
        $('.bf-details').slideToggle("slow");
        $('#show-filter, #hide-filter').toggleClass("hide");
    });

    //Link 'Load more'
    $('a.l-load-more').click(function () {
        $(this).parent().find('.b-countries-all').wrap('<div class="b-multiselect" />');
        $(this).parent().find('li').addClass('countries-visibl');
        $(this).parent().find('li.hide').removeClass('hide').removeClass('countries-visibl').addClass('future-hidden');
        $('.b-multiselect .b-countries-all').css('width', '180px').jScrollPane({ showArrows: true });
        $(this).hide();
        return false;
    });

    var checkExternalClick = function (event) {
        var target = $(event.target);
        if (target.hasClass('b-filter') || target.hasClass('bf-details') || target.hasClass('bf-title')) {
            if ($('.b-multiselect').size() == 1) {
                $('.b-countries-all').unwrap().unwrap();
                $('.b-countries-all').find('li.future-hidden').removeClass('future-hidden').addClass('hide');
                $('.jScrollCap, .jScrollArrowDown, .jScrollArrowUp, .jScrollPaneTrack').remove();
                $('.b-countries-all').removeAttr('style');

                var apis = [];
                if (apis.length) {
                    $.each(apis, function (i) { this.destroy(); })
                    apis = [];
                };

                $('.b-countries-all').find('ul').show();
                $('a.l-load-more').show();
                return false;
            }
        }
    };
    $(document).mousedown(checkExternalClick);

    //Home stories top gallery
    $('.l-hs-carousel').imagesLoaded(function () {
        chHeightImg('.bhs-img img', 318);
    });
    $('.l-hs-carousel').carouFredSel({
        prev: '.pg-prev',
        next: '.pg-next',
        scroll: {
            fx: "crossfade"
        },
        pagination: ".pg-pages",
        auto: true
    });
    $('.b-pager-gallery a').click(function () {
        $('.l-hs-carousel').trigger("pause");
    });

    //Featured rooms on home page

    $('.l-featured-rooms').imagesLoaded(function () {
        $(".l-featured-rooms img").each(function () {
            var imgWidth = $(this).width();
            if (imgWidth < 237) {
                $(this).parent().css({ 'width': '143px' });
            } else {
                $(this).parent().css({ 'width': '237px' });
            }
        });
        var wItem = $(".l-featured-rooms li").last().width();
        $(".l-featured-rooms li").last().css({
            'position': 'absolute',
            'left': -(wItem + 8)
        });
    });
    $(".l-featured-rooms").carouFredSel({
        auto: false,
        direction: "right",
        prev: '.bfr-prev',
        next: '.bfr-next',
        scroll: {
            duration: 800,
            onBefore: function (oldItems, newItems) {
                $(".l-featured-rooms li").removeAttr('style');
            },
            onAfter: function (oldItems, newItems) {
                var wItem = $(".l-featured-rooms li").last().width();
                $(".l-featured-rooms li").last().css({
                    'position': 'absolute',
                    'left': -(wItem + 8)
                });
            }
        }
    });

    //Home story on home page
    $(".l-hhs-items").carouFredSel({
        items: 1,
        scroll: {
            fx: "crossfade"
        },
        direction: "down",
        prev: '.phs-prev',
        next: '.phs-next',
        pagination: ".phs-pages",
        auto: false
    });

    orderingImg('.b-album-thumbnails', '.b-album-thumbnail', 216);
    orderingImg('.b-rooms-albums', '.b-room-thumbnail', 320, '.b-room-thumbnail-wrap', 386, 233);
    orderingImg('.b-search-rooms-albums', '.b-search-room-thumbnail', 237, '.b-search-room-thumbnail-wrap', 291, 176);

    widthOfPager('.b-pager-gallery');
    widthOfPager('.b-pager, .phs-pager-centr');
    viewItems('#js-items');

    $('ul.l-items-grid li').setEqualBlocksHeight('3');


    $('span.checkbox input:checkbox').change(function () { checkboxCheck(this); }).each(function () { checkboxCheck(this); });

    $('.i-email').click(function () {
        var $dataForm = $('#js-emailpage-form-inner').find('.js-emailpage-form-data');
        $dataForm.find('#js-emailpage-subject').val('');
        $dataForm.find('#js-emailpage-emailaddress').val('');
        $dataForm.find('#js-emailpage-message').val('');
        $dataForm.show();
        $('#js-emailpage-form-inner').find('.js-emailpage-form-thanks').hide();
    });
    $('#js-emailpage-send').click(function (event) {
        event.preventDefault();

        ClearEmailPageValidationMessages();
        var subject = $('#js-emailpage-subject').val().trim();
        var emailAddress = $('#js-emailpage-emailaddress').val().trim();
        var message = $('#js-emailpage-message').val();


        if (ValidateEmailPageForm(subject, emailAddress)) {
            $.ajax(
            {
                url: '/en/email-a-page',
                context: document.body,
                type: "post",
                dataType: "json",
                data: $.toJSON({ subject: subject, emailaddress: emailAddress, message: message }),
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                beforeSend: function () {
                    $.fancybox.showActivity();
                },
                complete: function () {
                    $.fancybox.hideActivity();
                },
                success: function (data) {
                    if (data != null) {
                        if (data.status == 'success') {
                            $('#js-emailpage-form-inner').find('.js-emailpage-form-data').hide();
                            //$('#js-emailpage-form-inner').html("<h2>" + data.localizedResources.Header + "</h2><p>" + data.result + "</p>");
                            var $thanks = $('#js-emailpage-form-inner').find('.js-emailpage-form-thanks');
                            $thanks.append("<p>" + data.result + "</p>");
                            $thanks.show();
                        }
                        else {
                            for (var i = 0; i < data.Errors.length; i++) {
                                if (data.Errors[i] == 'subjectRequired') {
                                    $('#js-emailpage-subject-error').show();
                                }
                                if (data.Errors[i] == 'emailRequired') {
                                    $('#js-emailpage-emailaddress-required-error').show();
                                }
                                if (data.Errors[i] == 'emailInvalid') {
                                    $('#js-emailpage-emailaddress-invalid-error').show();
                                }
                            }
                        }
                    }
                }

            });
        }
    });

    $("#js-show-more-comments").click(LoadComments);

    //homestories
    $(".js-hometype").change(ApplyHomeStoriesFilter);
    $(".js-interests").change(ApplyHomeStoriesFilter);
    $(".js-style").change(ApplyHomeStoriesFilter);
    $(".js-countries").change(ApplyHomeStoriesFilter);
    $(".js-theme").change(ApplyHomeStoriesFilter);
    $("#ddlHomeStorySortOptions").change(ApplyHomeStoriesFilter);
    $("#btnClearHomeStoriesFilter").click(function (event) {
        event.preventDefault();
        ClearHomeStoriesSelectedFields();
    });

    $(".b-pager-home-story > a").live("click", function (event) {
        event.preventDefault();
        pagerClick($(this));
        LoadHomeStories(pagerInfo.CurrentPage);
    });
    //end homestories

    //rooms

    $("#btnClearRoomsFilter").click(function (event) {
        event.preventDefault();
        ClearRoomsSelectedFields();
    });



    $("#ddlSortOptions").change(ApplyRoomFilter);
    $(".js-r-colours").change(ApplyRoomFilter);
    $(".js-r-styles").change(ApplyRoomFilter);
    $(".js-r-countries").change(ApplyRoomFilter);

    $("#IkeaLive").change(function () {
        BlockRoomFilterChecking('#Member', $(this));
    });

    $("#Member").change(function () {
        BlockRoomFilterChecking('#IkeaLive', $(this));
    });

    $("#IncludeVideos").change(ApplyRoomFilter);

    $(".b-pager-room > a").live("click", function (event) {
        event.preventDefault();
        pagerClick($(this));
        LoadRooms(pagerInfo.CurrentPage);
    });
    //endrooms

    //search rooms

    $("#btnClearSearchRoomsFilter").click(function (event) {
        event.preventDefault();
        ClearSearchRoomsSelectedFields();
    });

    $(".js-s-r-colours").change(ApplySearchRoomFilter);
    $(".js-s-r-categories").change(ApplySearchRoomFilter);
    $(".js-s-r-styles").change(ApplySearchRoomFilter);
    $(".js-s-r-countries").change(ApplySearchRoomFilter);
    $("#ddlSearchSortOptions").change(ApplySearchRoomFilter);

    $("#chkSearchRoomIkeaLive").change(function () {
        BlockSearchRoomFilterChecking('#chkSearchRoomMembers', $(this));
    });
    $("#chkSearchRoomMembers").change(function () {
        BlockSearchRoomFilterChecking('#chkSearchRoomIkeaLive', $(this));
    });

    $("#chkSearchRoomIncludeVideos").change(ApplySearchRoomFilter);

    $(".b-pager-search-room > a").live("click", function (event) {
        event.preventDefault();
        pagerClick($(this));
        LoadSearchRooms(pagerInfo.CurrentPage);
    });
    //endrooms

    $("#js-comment-submit").click(function (event) {
        event.preventDefault();
        AddComment();
    });

    $(".js-scrapbook-title").live('click', AddToScrapbook);


    $("#js-story-all").click(function () {
        $("#js-story-all").addClass("current");
        $("#js-story-blogs").removeClass("current");
        $("#js-story-homestories").removeClass("current");

        $(".js-homestory").show();
        $(".js-blog").show();

        $("#js-show-more-b").show();
        $("#js-show-more-hs").show();
        return false;
    });

    $("#js-story-homestories").click(function () {
        $("#js-story-homestories").addClass("current");
        $("#js-story-blogs").removeClass("current");
        $("#js-story-all").removeClass("current");

        $(".js-homestory").show();
        $(".js-blog").hide();

        $("#js-show-more-b").hide();
        $("#js-show-more-hs").show();
        return false;
    });

    $("#js-story-blogs").click(function () {
        $("#js-story-blogs").addClass("current");
        $("#js-story-all").removeClass("current");
        $("#js-story-homestories").removeClass("current");

        $(".js-homestory").hide();
        $(".js-blog").show();

        $("#js-show-more-b").show();
        $("#js-show-more-hs").hide();
        return false;
    });

    $('.b-scrapbook-pane_heading').click(function () {
        $('.b-scrapbook-pane_cont').slideToggle('slow');
        $('.b-scrapbook-pane_close').toggle();
        $('.b-scrapbook-pane_nav_top ul').jScrollPane({ showArrows: true, scrollbarWidth: 12 });
    });
    var checkExternalScrapbookClick = function (event) {
        var target = $(event.target);
        if ($('.b-scrapbook-pane_cont').css('display') == 'block') {
            if ((target.parents().hasClass('b-scrapbook-pane') != true) && (target.is('#fancybox-overlay') != true) && (target.parents().is('#fancybox-wrap') != true)) {
                $('.b-scrapbook-pane_cont').hide();
                $('.b-scrapbook-pane_close').hide();
                $('.b-scrapbook-pane_nav_top ul').jScrollPane({ showArrows: true, scrollbarWidth: 12 });
                return false;
            }
        }
    };
    $(document).mousedown(checkExternalScrapbookClick);

    $(".js-sp-edit-description").live("click", function () {
        $(this).find('.b-scrp-pane_ico-add-note').addClass('b-scrp-pane_ico-disable');
        $(this).find('.js-sp-add-note').hide();
        $(this).parent().find(".js-sp-edit-note").show();
        $(this).parent().find('.js-sp-description-content').hide();
    });

    $(".js-sp-submit").live("click", function () {
        var txtDescription = $(this).parent().find(".js-sp-description");
        var txtPid = $(this).parent().find(".js-sp-id");

        if (txtPid.val()) {
            $.post("/en/scrapbook/updatescrapbookphotodescription", { scrapbookPhotoId: txtPid.val(), description: escape(txtDescription.val()) });

            var lightBoxParent = $(this).parent().parent();
            var parent = $('#js-sp-photos input.js-sp-id[value="' + lightBoxParent.find(".js-sp-id").val() + '"]').parents('.js-sp-details');
            var descriptionContent = lightBoxParent.find(".js-sp-description-content");

            lightBoxParent.find(".js-sp-details").addClass("hide");
            parent.find(".js-sp-description-content").text(txtDescription.val());
            parent.find(".js-sp-description").text(txtDescription.val());

            descriptionContent.text(txtDescription.val());
            descriptionContent.show();
            lightBoxParent.find(".js-sp-edit-note").hide();
            lightBoxParent.find('.b-scrp-pane_ico-add-note').removeClass('b-scrp-pane_ico-disable');

            if (txtDescription.val()) {
                if (parent.parent().find(".b-scrp-pane_ico-edit-desc").length == 0) {
                    parent.parent().append('<span class="b-scrp-pane_ico-edit-desc">&nbsp;</span>');
                }
                parent.find(".js-sp-add-note").hide();
                lightBoxParent.find(".js-sp-add-note").hide();
                $(this).attr('value', lblUpdateBtn);
                parent.find(".js-sp-submit").attr('value', lblUpdateBtn);
            }
            else {
                parent.parent().find(".b-scrp-pane_ico-edit-desc").remove();
                parent.find(".js-sp-add-note").show();
                lightBoxParent.find(".js-sp-add-note").show();
                $(this).attr('value', lblSaveBtn);
                parent.find(".js-sp-submit").attr('value', lblSaveBtn);
            }
        }
    });

    $(".js-sp-scrapbook-title").live('click', function (event) {
        event.preventDefault();
        var selectedScrapbookId = $(this).attr('id');
        if (spSelectedScrapbook && spSelectedScrapbook != selectedScrapbookId) {
            $("#js-sp-scrapbooks li").removeClass('current');
            $(this).parent().addClass('current');
            spSelectedScrapbook = selectedScrapbookId;
            LoadScrapbooks(spSelectedScrapbook);
        }
    });

    $("#js-create-scrapbook-btn").click(AddRoomToNewScrapbook);
    $('.i-scrapbook, .i-scrapbook-add').hover(function () { $(this).find('.b-tooltip').show(); }, function () { $(this).find('.b-tooltip').hide(); });
    $('.i-scrapbook, .i-scrapbook-add').live("click", function () {
        if (requestInfo.IsRequestAuthenticated()) {
            var pos = $(this).offset();

            $('.b-scrapbook-box').css({
                'display': 'block',
                'top': pos.top + 32,
                'left': pos.left - 80
            });

            //$('.b-list-scrapbooks ul').jScrollPane({showArrows:true});

            if ($(this).hasClass('l-gallery')) {
                $("#js-pid").val($('.ad-active').find('img').attr("id"));
            } else {
                $("#js-pid").val($(this).parents(".img-id").find('img').attr("id"));
            }
            var CountOfLi = $('ul#js-scrapbooks').height();
            //CountOfLi=100;

            if (CountOfLi <= 125) {
                $('.b-list-scrapbooks ul').css('height', 'auto');
                $('.b-list-scrapbooks').css('height', 'auto');
            }
            else {
                $('.b-list-scrapbooks ul').css('height', 125);
                $('.b-list-scrapbooks').css('height', 125);
                $('.b-list-scrapbooks ul').jScrollPane({ showArrows: true });
            }
        }
        else {
            $.fancybox({
                href: '#login',
                overlayColor: '#000',
                overlayOpacity: 0.6,
                autoScale: true,
                autoDimensions: true,
                showCloseButton: false,
                scrolling: 'no',
                titleShow: false
            });
        }
        return false;
    });

    $('.b-scrapbook-cont').mouseleave(function () { $('.b-scrapbook-box').hide(); var CountOfLi = $('ul#js-scrapbooks').height(); });
});

function LikeHomeStory(homeStoryId) {
    $.post('/en/facebook/likehomestory', { homeStoryId: homeStoryId });
}

function LikeRoom(roomId) {
    $.post('/en/facebook/likeroom', { roomId: roomId });
}

function UnlikeHomeStory(homeStoryId) {
    $.post('/en/facebook/unlikehomestory', { homeStoryId: homeStoryId });
}

function UnlikeRoom(roomId) {
    $.post('/en/facebook/unlikeroom', { roomId: roomId });
}

function LikeBlog(blogId) {
    $.post('/en/facebook/likeblog', { blogId: blogId });
}

function UnlikeBlog(blogId) {
    $.post('/en/facebook/unlikeblog', { blogId: blogId });
}

function LikeScrapbook(scrapbookId) {
    $.post('/en/facebook/likescrapbook', { scrapbookId: scrapbookId });
}

function UnlikeScrapbook(scrapbookId) {
    $.post('/en/facebook/unlikescrapbook', { scrapbookId: scrapbookId });
}

function OnFocus(object, value) {
    if (object.value == value) {
        object.value = '';
    }
}
function OnBlur(object, value) {
    if (object.value == '') {
        object.value = value;
    }
}

function RequaredFieldValidate(object, value) {
    if (!object) {
        return false;
    }
    return (stripspaces(object) != '' && object != value);
}

function stripspaces(value) {
    return value.replace(/\s/gi, "");
}

function TuneFbLikeButtonWidth(callback) {

    var url = window.location.protocol + "//" + window.location.host + window.location.pathname;

    $.ajax(
                {
                    type: "POST",
                    url: '/en/facebook/getlikes',
                    data: { url: url },
                    dateType: 'json',
                    success: function (likes) {
                        if (callback) {
                            callback(likes);
                        }
                    }
                }
        );
}
function TuneFbLikeButtonWidthCallback(likes) {
    var count = likes;
    if (count <= 0) {
        $('.b-facebook-like').css({ 'width': '48px' });
    } else if ((count > 0) && (count < 100)) {
        $('.b-facebook-like').css({ 'width': '76px' });
    } else {
        $('.b-facebook-like').css({ 'width': '90px' });
    }
}

function ContinueWelcomeScreenClick() {
    if ($('#chkCancelShowing').attr('checked') == true) {
        $.ajax(
                {
                    type: "POST",
                    url: '/en/my-live/cancelshowingwelcomescreen',
                    async: false
                }
        );
    }
}
