﻿var $lightBoxDialog;

$(document).ready(function () {

    $("#searchText").autocomplete('/Address/SuburbWithStateAndPostcode', {
        minChars: 1,
        width: 300,
        mustMatch: false
    });

    $("#frmSearch").submit(function () {
        sendReqest('#frmSearch', 'action');
    });

    $("#fireSearch").click(function () {
        sendReqest('#searchMain', 'href');
    });

    function sendReqest(sourceId, attr) {
        var searchUrl = getSearchUrl();
        $(sourceId).attr(attr, searchUrl);
    }

    $().ready(function () {
        $('.jqmWindow').jqm();
        $('#takeATour').click(function () {
            $('#dialog').jqmShow();
        });
        $('#takeATourOwner,#takeATourOwner2').click(function () {
            closeFancyBoxExplicitly();
            $('#dialogPropertyOwner').jqmShow();
        });
        $('#takeATourAgent').click(function () {
            closeFancyBoxExplicitly();
            $('#dialogPropertyAgent').jqmShow();
        });
        $('#takeATourBuyers').click(function () {
            closeFancyBoxExplicitly();
            $('#dialogPropertyBuyer').jqmShow();
        });
    });

    initLightBoxMovieTrailer();
    initSearchWatermark();

    showTagline();

    showRecentActivity();
    $(document).everyTime(10000, showRecentActivity, 0);

    if ($.url.param("query") == "siteTour") {
        $('#takeATour').click();
    }

});

function initSearchWatermark() {
    $("#searchText").watermark('watermark', 'Listing ID, Suburb or Postcode');
}

function initLightBoxMovieTrailer() {
    $lightBoxDialog = $('<div id="lightBoxTrailer"></div>')        
		.dialog({
		    autoOpen: false,
		    title: '',
		    width: 510,
		    height: 350,
		    modal: true
		});
}

function showTrailer(movieTrailer, movieTitle) {    
    var htmlText ='';
    htmlText = htmlText + '<object width="480" height="280">'; 
    htmlText = htmlText + '<param name="movie" value="' + movieTrailer + '&amp;hl=en&amp;fs=1&amp;rel=0&amp;autoplay=1"></param>';
    htmlText = htmlText + '<param name="allowFullScreen" value="true"></param>';
    htmlText = htmlText + '<param name="allowscriptaccess" value="always"></param>';
    htmlText = htmlText + '<embed src="' + movieTrailer + '&amp;hl=en&amp;fs=1&amp;rel=0&amp;autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="280">';
    htmlText = htmlText + '</embed>';
    htmlText = htmlText + '</object>';
    htmlText = htmlText + '<input id="movieTitle" type="hidden" value="' + movieTitle + '"/>';    
    $("#lightBoxTrailer").html(htmlText);    
    $lightBoxDialog.dialog({ title: $('#movieTitle').val() });
    $lightBoxDialog.dialog('open');

    return false;
}

function loadMarketActions(categoryId) {
    $.getJSON('/Catalog/GetMarketActions/', { categoryId: categoryId },
        function (data) {
            var select = $("#selectAction");
            select.empty();
            $.each(data, function (index, item) {
                select.append($('<option/>', {
                    value: item.Value,
                    text: item.Text
                }));
            });
            if (data.length == 1) {
                select.hide();
            } else {
                select.show();
            }
            updateSearchUrl();
        });
}

function marketCategorySelect(event, ui) {
    loadMarketActions(ui.index + 1);
}

var $marketCategories = new Array("residential", "commercial", "rural", "share");
function getSearchUrl() {
    var categoryId = $("#marketCategoryTabs").tabs('option', 'selected');
    var marketCategory = $marketCategories[categoryId];
    var marketAction = $("#selectAction").val();

    var searchUrl = "/" + marketCategory + "/" + marketAction;
    var searchTextVal = !$("#searchText").hasClass('watermark') ? $("#searchText").val() : "";
    if (searchUrl && searchTextVal) {
        searchUrl += "?SearchText=" + searchTextVal;
    }

    return searchUrl;
}

function updateSearchUrl() {
    var searchUrl = getSearchUrl();
    $("#moreOptions").attr("href", searchUrl);
    $("#searchMain").attr("href", searchUrl);
}

var whoIsJoiningTemplate = '<div class="whoIsItem"><p class="text">{0} in {1}, {2}</p><p class="text action">joined iPostcodes</p><p class="text">({3})</p></div>';
var whoIsPostingTemplate = '<div class="whoIsItem"><p class="text">{0} in {1}, {2}</p><p class="text action">posted a listing, ID: {3}</p><p class="text">({4})</p></div>';

function getRecentActivity(container, c) {
    $.getJSON("/Home/RecentActivity", { count: c },
    function (data) {
        var recentActivity = "";
        $.each(data.data, function (index, item) {
            var activity = item.data;
            if (item.type == 0) {
                recentActivity += whoIsJoiningTemplate.format(activity.AgencyName, activity.Suburb, activity.State, 
                    jQuery.timeago(activity.JoinedOn.parseJSONDate(), data.serverTime.parseJSONDate()));
            } else if (item.type == 1) {
                recentActivity += whoIsPostingTemplate.format(activity.Poster, activity.Suburb, activity.State, activity.ListingID, 
                    jQuery.timeago(activity.PostedOn.parseJSONDate(), data.serverTime.parseJSONDate()));
            }
        });
        $(container).html(recentActivity);
    });
}

function showRecentActivity() {
    getRecentActivity("#recentActivity", 2);
}

var taglineTemplate = '<p>&ldquo; <span class="bold">iPostcodes</span><span> - {0}</span> &rdquo;</p>';
var webinarPromotionTemplate = '<p>&ldquo;<span>{0}</span>&rdquo;</p>';
var taglineTimerActive = false;
function getTagline(container) {
    var jContainer = $(container);

    var currentId = jContainer.data('currentId');

    $.getJSON("/Home/NextTagline", { currentId: currentId },
    function (data) {
        var tagline = "";
        if (data.type == 0) {
            tagline = taglineTemplate.format(data.tagline);
            jContainer.next('.buttons').hide();

            if (taglineTimerActive) {
                taglineTimerActive = false;
                $(document).stopTime('taglineTimer');
            }
            
        } else if (data.type == 1) {
            tagline = webinarPromotionTemplate.format(data.tagline);
            jContainer.next('.buttons').show();
            jContainer.data('currentId', data.currentId);

            if (!taglineTimerActive) {
                taglineTimerActive = true;
                $(document).everyTime(10000, 'taglineTimer', showTagline, 0);
            }
        }
        jContainer.toggleClass('webinar', data.type == 1);
        jContainer.html(tagline);
    });
}

function showTagline() {
    getTagline("#taglineText");
}

