$(document).ready(function () {

    /*****************************************************/
    /******* Process any page startup stuff here *********/
    /*****************************************************/

    $(window).unload(function () {
        $("embed[id^='jwvideo_']").each(function () {

            var id = $(this).attr("id");
            var ieFixElement = document.getElementById(id);
            ieFixElement.parentNode.removeNode(ieFixElement);

        });
    });

    // Turn all containers with the class "tab_container" into tabs
    //$(".tab_container").tabs({
    //    select: function (event, ui) {
    //        $("#hdnSelectedTab").val(ui.index);
    //    },
    //    selected: $("#hdnSelectedTab").val()
    //});

    // Show / Hide 'My Romans' login
    $("#myromans_login").click(function () {
        $("#login_panel").slideToggle();
    });

    // Show / Hide 'My Romans' login
    $("#mysurvey_login").click(function () {
        $("#login_panel").slideToggle();
    });

    // Show / Hide 'My Romans' login
    $("#mysurvey_page").click(function () {
        $("#login_panel").slideToggle();
    });

    // Hide the quick search panel if we click outside it
    $(document).click(function (event) {
        if ($(event.target).closest("#quick_search_container").get(0) == null) { $("#quick_search_panel").slideUp(); }
    });

    // Change all anchor links to smooth scroll
    $('a[href*=#]').bind("click", smoothAnchorJump);

    // If the user is using Chrome or Safari, turn on autobuffer = false for videos.
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;

    if (is_chrome == true || is_safari == true) {
        $(".video-js").attr("autobuffer", false);
    }

    //nextNews();

    // Setup the info buttons
    $(".info").live("mouseover mouseout", function (event) {
        if (event.type == 'mouseover') {
            $(this).find("span").show();
        } else {
            $(this).find("span").hide();
        }
    });

    // Hover effect on buttons and cross sells
    $(".priority_cross_sell, double_cross_sell").hover(function () {
        $(this).fadeTo(100, 0.8);
    }, function () {
        $(this).fadeTo(100, 1);
    });

    // Fade out Tnc images.
    $(".sold_container").hover(function () {
        $("img", this).fadeOut(300);
    }, function () {
        $("img", this).fadeIn(300);
    });
});

// Clear search box on homepage focus.
function searchFocus() {
    if ($('#txtQuickSearchBuying').val() == "Enter a location or postcode here") {
        $('#txtQuickSearchBuying').val("");
    }
    else if ($('#txtQuickSearchBuying').val() == "") {
        $('#txtQuickSearchBuying').val("Enter a location or postcode here");
    }   
}

// Manipulate and animate news reel items.
var news = new Array();
var anchors = new Array();

var i = 0;

function loopNews() {

    $("#news_reel").fadeOut(1000, function () {
        $("#news_reel_link").html(news[i]);
    });

    $("#news_reel_link").attr("href", anchors[i]);
    $("#news_reel").fadeIn(1000);

    if (i < 9) {
        i++;
    }
    else {
        i = 0;
    }
}

//function nextNews() {
//    setInterval(function () { loopNews(); }, 5500);
//}

// Fade in and out the update notification <--- NOT USED ANYMORE?
$(".trigger_notification").live('click', function () {
    $("#update_message").fadeIn(600).delay(3000).fadeOut(500);
});

function showNotification(delay) {
    $("#update_message").fadeIn(500).delay(delay).fadeOut(400);
    this.focus();
}

function animateClip(sender) {
    options = { to: "#save_clip_effect" };
    $("#" + sender).effect('transfer', options, 1000);
}

function swapVideo(id, seed, width, height, file, image, container) {
    //alert("Swapping video");
    
    // Hide image.
    //$("#" + container).hide();

    // Inject Jquery code.
    $("#test_video_container").after("<embed style='position: absolute;' src='/Video/player.swf' name='jwvideo_" + seed + "' id='jwvideo_{0}' width='" + width + "' height='" + height + "' allowfullscreen='true' allowscriptaccess='always' wmode='opaque' flashvars='file=/Video/" + file + ".flv&image=" + image + "&controlbar=over&id=jwvideo_" + seed + "&enablejs=true&autostart=true&icons=false' class='romansvideo' <input type='hidden' id='jwvideoid_" + seed + "' name='jwvideoid_" + seed + "' value='" + id + "' /></embed>");

    //alert("Recording viewing");
    TrackVideoPlayed(id);
}


//Anonymous function that is applied to all internal-links
var smoothAnchorJump = function (e) {
    //Get the target
    var target = $(this).attr("href");

    // Set an offset if the anchor tag is a tab
    var offset = 0;
    if ($(this).parent().attr("class").toString().indexOf("ui-state-default") != -1) {
        offset = -50;
    }

    //perform animated scrolling
    try {
        var top = $(target).offset().top;

        // This check is to stop the tabs sometimes jumping to the top as the 
        // offset is sometimes -40000 (due to the way we hide hidden tabs). Needs a permanent fix.
        if (top >= 0) 
        {
            $('html,body').animate(
            {
                //get top-position of target-element and set it as scroll target
                scrollTop: $(target).offset().top + offset
            }, 500, function () {
                //attach the hash (#jumptarget) to the pageurl

                if (offset == 0) {
                    location.hash = target;
                }
            });

            //prevent the "normal" behaviour which would be a "hard" jump
            e.preventDefault();
        }
    }
    catch (e) {
    }
}

/*****************************************************/
/*******           Property Details          *********/
/*****************************************************/
var currentVisiblePhoto = "1";
var currentThumbnailScroll = 0;
function InitPropertyDetailsPage() {
    InitScrollableImages(5, 531);

    $("#button_book_viewing").click(function () {
        try {
            $("#book_viewing_form").show();
            $("#make_offer_form").hide();
            $("#booking_goalRegister").attr("src", "");
        } catch (e) { }
    });

    $("#button_make_offer").live("click", function () {
        try {
            $("#make_offer_form").show();
            $("#book_viewing_form").hide();
        } catch (e) { }
    });

    var anchorValue;
    var url = document.location;
    var strippedUrl = url.toString().split("#");
    if (strippedUrl.length > 1) {
        anchorvalue = strippedUrl[1];

        if (anchorvalue == "maptab") {
            $("#hdnFromMapTab").val("1");
        }
    }

}

function InitScrollableImages(maxThumbs, width) {
    // Hide all the photos except the first/main
    $("#photos > li:not(:first-child)").hide();
    $("#photos > li:first-child").show();

    // Setup the thumbnail image hover effect
    $("#photo_thumbnails > li > img").hover(function () {
        var srcImageId = $(this).attr("id");
        var id = srcImageId.replace("property_thumbnail_", "");

        if (currentVisiblePhoto != id) {
            $("#property_photo_" + currentVisiblePhoto).css("z-index", "0");
            $("#property_photo_" + id).css("z-index", "1");

            $("#property_photo_" + id).fadeIn(400);
            $("#property_photo_" + currentVisiblePhoto).fadeOut(400);

            currentVisiblePhoto = id;
        }
    });

    // Setup the thumbnail image scroller
    var listItems = $("#photo_thumbnails > li");
    var numImages = parseInt(listItems.length);
    var itemsPerPage = maxThumbs;
    var totalPages = Math.ceil(numImages / itemsPerPage);

    if (numImages > itemsPerPage + 1) {
        $("#photo_thumbnails_innercontainer").addClass("photo_thumbnails_paged");
        $("#photo_thumbnails_container").prepend("<div id='thumbnails_right'>&nbsp;</div><div id='thumbnails_left'>&nbsp;</div>");

        $("#thumbnails_left").live("click", function () {
            if (currentThumbnailScroll < totalPages - 1) {
                currentThumbnailScroll++;
                $("#photo_thumbnails").animate({
                    "left": "-=" + width + "px"
                }, "200");
            }
        });

        $("#thumbnails_right").live("click", function () {
            if (currentThumbnailScroll > 0) {
                currentThumbnailScroll--;
                $("#photo_thumbnails").animate({
                    "left": "+=" + width + "px"
                }, "200");
            }
        });
    }
}

function searchThumbHover() {

    // Setup the thumbnail image hover effect
    $(".premium_property_images > img").hover(function () {
        var srcImageId = $(this).attr("id");
        var id = srcImageId.replace("property_thumbnail_", "");

        if (currentVisiblePhoto != id) {
            $("#property_" + currentVisiblePhoto).css("z-index", "0");
            $("#property_" + id).css("z-index", "1");

            $("#property_" + id).fadeIn(400);
            $("#property_" + currentVisiblePhoto).fadeOut(400);

            currentVisiblePhoto = id;
        }
    });
}
