/// <reference path="jQuery/jquery-1.4.1.min.js" />
/// <reference path="jQuery/plugins/jquery.inputhints.min.js" />
/// <reference path="jQuery/plugins/jquery.colorbox-min.js" />

//This is the site URL without the http:// (does not end in /)
siteURL = window.location.hostname;

//Add the http:// and closing slash
siteURL = "http://" + siteURL + "/";

var priceSliderValue = 10;
var sizeSliderValue  = 36;
var roomSliderValue = 2;

var buildingViewer = null;

/* -- jQuery when DOM is ready -- */
$(document).ready(function () {

    //Email Form Input Hints
    $("input[title]").inputHints();

    //Example of changing bottom section....
    $("#buildingViewer").click(function () {
        displayApartment(1196);
    });

    //Gallery links
    $("a.gallery").colorbox({ opacity: "0.5" });

    //Alt Table rows
    $("tr:odd").addClass("odd");

    // initialize contact us popup
    $(".contact_us").colorbox({ width: 520, height: 400, iframe: true });


    //Click on checkbox input
    $('.building input').click(function () {
        filterPriceList();
    });


    $('.viewAll button').click(function (event) {
        event.preventDefault();

        //URL = /prisliste.aspx
        var pageURL = window.location.pathname;

        //Redirect
        window.location.replace(pageURL);
    });


    //Homepage slider
    // Save  the jQuery objects for later use.
    var outer = $("#preview_outer");
    var arrow = $("#arrow");
    var thumbs = $("#thumbs span");

    var preview_pos;
    var preview_els = $("#preview_inner div.elem"); // Modded to support video
    var image_width = preview_els.eq(0).width(); // Get width of imaages

    // Hook up the click event
    thumbs.click(function () {
        // Get position of current image
        preview_pos = preview_els.eq(thumbs.index(this)).position();

        // Animate them!
        outer.stop().animate({ 'scrollLeft': preview_pos.left }, 500);
        arrow.stop().animate({ 'left': $(this).position().left }, 500);
        try {
            document.getElementById("playerID1").sendEvent('STOP');
        }
        catch (err) { }

        try {
            document.getElementById("playerID3").sendEvent('STOP');
        }
        catch (err) { }
    });

    // Reset positions on load
    //arrow.css({ 'left': thumbs.eq(0).position().left }).show();
    outer.animate({ 'scrollLeft': 0 }, 0);

    // Set initial width
    $("#preview_inner").css('width', preview_els.length * image_width);

    // Init the tablesorter on the pricelist
    $("#data").tablesorter({ sortList: [[0, 0]], widgets: ['zebra'] });

    $('#filter-available input:checkbox').click(function () {

        if ($(this).is(":checked")) {
            $(this).closest("li").addClass("selected");
        }
        else {
            $(this).closest("li").removeClass("selected");
        }

        filterByBuildingAndRooms();

    });

    $('#filter-rooms input:checkbox').click(function () {

        if ($(this).is(":checked")) {
            $(this).closest("li").addClass("selected");
        }
        else {
            $(this).closest("li").removeClass("selected");
        }

        filterByBuildingAndRooms();

    });

    // All
    $('#filter-rooms a.all').click(function () {
        $("#filter-rooms ul li").removeClass("selected");
        $("#filter-rooms ul li input:checkbox").attr("checked", false);
        filterByBuildingAndRooms();
        return false;
    });

    //Click on checkbox input
    $('#filter-buildings a.filter').click(function () {
        var building = $(this).attr("name");
        $(this).closest("li").siblings().removeClass("selected");
        $(this).closest("li").addClass("selected");
        $("#building-img").attr("src", $(this).attr("building"));
        filterByBuildingAndRooms();
        return false;
    });

    // All
    $('#filter-buildings a.all').click(function () {
        $("#filter-buildings ul li").removeClass("selected");
        $("#building-img").attr("src", $(this).attr("building"));
        filterByBuildingAndRooms();
        return false;
    });

    // Click on image map
    $('area').click(function () {
        var img = $(this).attr("building");
        var building = $(this).attr("name");
        $("#building-img").attr("src", img);
        $('a[building=' + img + ']').closest("li").siblings().removeClass("selected");
        $('a[building=' + img + ']').closest("li").addClass("selected");
        filterByBuildingAndRooms();
        return false;
    });

    // If rooms are specified in querystring
    if (getQuerystring("rooms", null) != null) {

        var rooms = getQuerystring("rooms", null);

        $("#filter-rooms input:checkbox").each(function () {
            if ($(this).attr("name") === rooms) {
                $(this).closest("li").addClass("selected");
                $(this).attr("checked", true);

                filterByBuildingAndRooms();
            }
        });
    }

    // If building is specified
    if (getQuerystring("bid", null) != null) {

        var bid = getQuerystring("bid", null);

        $("#filter-buildings ul li a").each(function () {

            if ($(this).attr("bid") === bid) {
                $(this).closest("li").addClass("selected");
                $("#building-img").attr("src", $(this).attr("building"));
                filterByBuildingAndRooms();
            }
        });
    }

    // Attempt to preload the builing overlays
    preload($('.filtersection ul li a'));

});

$.address.change(function (event) {
    
    var bid = event.parameters.bid;
    var aid = event.parameters.aid;
    if (bid != null || aid != null) {

        var flash = document.getElementById('buildingViewer');

        try 
        {
            flash.setAptByID(bid, aid);       
        }
        catch (err) {
        }
    }
});

function getQuerystring(key, default_)
{
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}


function filterByBuildingAndRooms() {
    
    // Hide everything
    $('table#data tbody tr').hide();

    $($("#filter-rooms ul li input:checkbox:checked")).each(function () {
        var rooms = $(this).attr("name");

        if ($("#filter-buildings li.selected").length > 0) {

            var building = $("#filter-buildings li.selected a").attr("name");

            $('table#data tbody tr.' + building + ' td.rooms[name=' + rooms + ']').closest("tr").show();

        }
        else {
            $('table#data tbody tr td.rooms[name=' + rooms + ']').closest("tr").show();
        }
    });

    // If every checkbox is un-checked. Show all
    if ($("#filter-rooms ul li input:checkbox:checked").length == 0) {

        if ($("#filter-buildings li.selected").length > 0) {

            var building = $("#filter-buildings li.selected a").attr("name");

            $('table#data tbody tr.' + building).show();

        }
        else {
            $('table#data tbody tr').show();
        }
    }

    // If we are only showing available apartments, hide sold
    if ($("#filter-available ul li input:checkbox:checked").length > 0) {
        $('table#data tbody tr.sold').hide();
    }

    $("#data").trigger("appendCache");
}

// Used for preloading the building overlays
function preload(arrayOfImages) {
    $(arrayOfImages).each(function () {    
        (new Image()).src = $(this).attr('building');
    });
}

function checkboxFilter(checkBoxes, row) {
    var checked = false;
    $(checkBoxes).each(function () {
        if ($(row).hasClass($(this).val())) {
            checked = true;
        }
    });
    return checked;
}



function log(s) {
    if (window.console) { console.log(s); }
}

function displayTemplate(apartmentID) {
    
    if (apartmentID > -1) {

        $("#apartmentInfo").load("/" + apartmentID + ".aspx #apartmentInfo", function () {

            // remove the second apartmentId from the DOM completely.
            $(this).children().unwrap();

            //re-do links loaded inf
            $("a.gallery").colorbox({ opacity: "0.5" });
        });
    }

}


function displayApartment(apartmentID, bid, aid) {
        
    // Update address
    $.address.value("/?bid=" + bid + "&aid=" + aid);
}


function WriteBuildingViewer(flashURL, footURL, filterURL, bid_xml) {

    var flashvars               = {};
    flashvars.footprintUrl      = footURL;
    flashvars.filterUrl         = filterURL;
    flashvars.xmlSource         = "/flashxml.aspx";

    var bid = getQuerystring("bid", "");
    var aid = getQuerystring("aid", "");

    if (aid != "") {
        flashvars.aid = aid;
    }

    if (bid != "") {
        flashvars.bid = bid;
    }

    var params                  = {};
    params.menu                 = "false";
    params.allowScriptAccess    = "always";
    params.quality              = "high";
    params.wmode                = "transparent";

    var attributes              = {};

    //swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn)
    swfobject.embedSWF(flashURL, "buildingViewer", "926", "300", "9.0.0", false, flashvars, params, attributes);

}

function WriteBanner (flashURL, bannerHeading, bannerLead, bannerLink) {

    var flashvars = {};
    
    flashvars.header    = bannerHeading;
    flashvars.lead      = bannerLead;

    if (bannerLink != '') {
        flashvars.link = siteURL + bannerLink;
    }

    var params = {};
    params.menu = "false";
    params.allowScriptAccess = "always";
    params.quality = "high";
    params.wmode = "transparent";

    var attributes = {};

    swfobject.embedSWF(flashURL, "banner", "336", "311", "9.0.0", false, flashvars, params, attributes);
}


