﻿(function($) {
    
    var widgets = [];
    
    $(document).ready(function() {

        var advertType = {
            Sale: 0,
            Rent: 1        
        };
        
        var base = "fap_app_w";
        
        var baseUrls = {
            SearchResultsUrl: 'http://www.findaproperty.com/searchresults.aspx?',
            StyleUrl: 'http://widgets.findaproperty.com/widgets/avgpropertyprice/standard.css',
            WebServicesBaseUrl: 'http://widgets.findaproperty.com/',
            WebsiteBaseUrl: 'http://www.findaproperty.com/'
        };
        
        var locationType = {
            Area: 'area',
            Region: 'region'
        };
            
        var referrer = encodeURIComponent(escape(window.location));
            
        var screen = {
            One: 0,
            Two: 1,
            Three: 2,
            Width: 260
        };
        
        var style = {
            BaseClass: '.fap_app_w',
            Deselected: 'pos0',
            Rent: 'rent',
            RentHover: 'pos3',
            Sale: 'sale',
            SaleHover: 'pos2',
            Selected: 'pos1'
        };
        
        Widget = function(index){
            var WidgetType = 1;
            
            //the widget Id
            this.Id = WidgetId_Init(index);
            
            var areaId = (parseInt($(this.Id + ' .fap_app_areaid:first').val(), 10));
            var regionId = parseInt($(this.Id + ' .fap_app_regionid:first').val(), 10);
            
            //the parameter values            
            this.LocationId = (areaId > 0) ? areaId : regionId;
            this.LocationType = (areaId > 0) ? locationType.Area : locationType.Region;
            this.EditionId = parseInt($(this.Id + ' .fap_app_editionid:first').val(), 10);
            this.SaleOrRent = parseInt($(this.Id + ' .fap_app_salerent:first').val(), 10); 
            this.ScreenCount = parseInt($(this.Id + ' .fap_app_screens:first').val(), 10); 
            this.CurrentScreen = screen.One;
            
            //the controls
            this.Graph = $(this.Id + ' .fap_app_wb_grp:first');
            this.AveragePropertyPrice = $(this.Id + ' .fap_app_wb_grp_g:first');            
            this.Content = $(this.Id + ' .fap_app_wb_ws:first'); 
            this.FlatsTable = $(this.Id + ' .fap_app_wb_tbl_f:first');
            this.FlatsHeader = $(this.Id + ' .fap_app_wb_tbl_f th');
            this.FlatsRow = $(this.Id + ' .fap_app_wb_tbl_f td');
            this.Footer = $(this.Id + ' .fap_app_wf:first, ' + this.Id + ' .fap_app_wf:first a');
            this.HousesTable = $(this.Id + ' .fap_app_wb_tbl_h:first');
            this.HousesHeader = $(this.Id + ' .fap_app_wb_tbl_h th');
            this.HousesRow = $(this.Id + ' .fap_app_wb_tbl_h td');
            this.LegendId = $(this.Id + ' .fap_app_wb_grp_l:first');
            this.Loader = $(this.Id + ' .fap_app_wb_grp_a:first');
            this.NextButton = $(this.Id + ' .fap_app_rn:first');
            this.PreviousButton = $(this.Id + ' .fap_app_ln:first');
            this.SEOText = $(this.Id + ' .fap_app_wb_txt:first, ' + this.Id + ' .fap_app_wb_txt:first a');
            this.Title = $(this.Id +  ' .fap_app_wh, ' + this.Id + ' .fap_app_wh a');
            
            //the urls       
            this.AvgPropPriceGraphUrl = baseUrls.WebServicesBaseUrl + 'averagepropertypriceservice.svc/v1/avgpropprice/' + this.LocationType;
            this.AvgPropPriceTableUrl = baseUrls.WebServicesBaseUrl + 'averagepropertypriceservice.svc/v1/avgpropprice/beds/' + this.LocationType;
            this.LogVisitUrl = baseUrls.WebServicesBaseUrl + 'widgetloggingservice.svc/v1/' + WidgetType + '/log';
            
            //the colours
            this.Colour1 = $(this.Id + ' .fap_app_colour1:first').val();
            this.Colour2 = $(this.Id + ' .fap_app_colour2:first').val();
            this.Colour3 = $(this.Id + ' .fap_app_colour3:first').val();
            this.Colour4 = $(this.Id + ' .fap_app_colour4:first').val();
            this.Colour5 = $(this.Id + ' .fap_app_colour5:first').val();
            
	    //initialise widget
            this.WidgetId_Init(index)
	    this.Styles_Init(index);
            this.Navigation_Init(index);
            this.Graph_Init(index);
            this.Table_Init(index);
            this.Widget_Log(index);
        };
            
        Widget.prototype.WidgetId_Init = WidgetId_Init;
        Widget.prototype.Styles_Init = Styles_Init;
        Widget.prototype.Navigation_Init = Navigation_Init;
        Widget.prototype.Graph_Init = Graph_Init;
        Widget.prototype.Table_Init = Table_Init;
        Widget.prototype.Widget_Log = Widget_Log;
        
            
        //set the widget id to each widget
        function WidgetId_Init(index){
            var id = base + index;
            $(style.BaseClass + ':eq(' + index + ')').attr('id', id);
            return GetId(index);
        };     
        
        //this function is called when we need to get the parent
        function GetId(index){
            return '#' + base + index;
        }
        
        //add a stylesheet to the page (on first widget) and set css styles to widgets
        function Styles_Init(index) {
            if(index == 0){
                if (document.createStyleSheet) {
                    document.createStyleSheet(baseUrls.StyleUrl);
                }
                else {
                    var styles = "@import url('" + baseUrls.StyleUrl + "');";
                    var stylesheet = document.createElement('link');
                    stylesheet.rel = 'stylesheet';
                    stylesheet.href = baseUrls.StyleUrl;
                    document.getElementsByTagName("head")[0].appendChild(stylesheet);
                }
            }
            
            //set the border-color
            $(style.BaseClass + ':eq(' + index + ')').css('border-color', this.Colour5);
            
            //set the table header colours
            this.HousesHeader.css('background-color', this.Colour3);
            this.FlatsHeader.css('background-color', this.Colour4);
            this.Footer.css('color', this.Colour2);            
            this.SEOText.css('color', this.Colour1);
            this.Title.css('color', this.Colour1);
        };
        
        //add the navigation buttons 
        function Navigation_Init(index){
            Navigation_Update(this);
                    
            this.PreviousButton.click(function() { 
                var widget = widgets[index];
                if (widget.CurrentScreen != screen.One) {
                    widget.Content.animate({ marginLeft: (widget.CurrentScreen * screen.Width * -1) + screen.Width + 'px' }, 1000)
                    widget.CurrentScreen--;
                    Navigation_Update(widget);
                };
            });
            
            this.NextButton.click(function() {
                var widget = widgets[index];
                if (widget.CurrentScreen < widget.ScreenCount -1) {
                    widget.Content.animate({ marginLeft: (widget.CurrentScreen * screen.Width * -1) - screen.Width + 'px' }, 1000)
                    widget.CurrentScreen++;
                    Navigation_Update(widget);
                };
            });
        };
        
        
        function Navigation_Update(widget){
            widget.PreviousButton.css('background-color', widget.Colour5);
            widget.PreviousButton.hover(function(){$(this).css('background-color', widget.Colour1);}, function(){$(this).css('background-color', widget.Colour5);});
            widget.NextButton.css('background-color', widget.Colour5);
            widget.NextButton.hover(function(){$(this).css('background-color', widget.Colour1);}, function(){$(this).css('background-color', widget.Colour5);});
            
            if(widget.ScreenCount == 1){
                widget.PreviousButton.unbind('mouseenter mouseleave');
                widget.NextButton.unbind('mouseenter mouseleave'); 
                widget.PreviousButton.addClass('disabled'); 
                widget.NextButton.addClass('disabled');  
            }
            else if(widget.CurrentScreen == screen.One){
                widget.PreviousButton.unbind('mouseenter mouseleave');
                widget.PreviousButton.addClass('disabled');
                widget.NextButton.removeClass('disabled');
            }
            else if(widget.CurrentScreen == widget.ScreenCount-1){
                widget.PreviousButton.removeClass('disabled');
                widget.NextButton.addClass('disabled');
                widget.NextButton.unbind('mouseenter mouseleave');                    
            }            
            else {
                widget.PreviousButton.removeClass('disabled');
                widget.NextButton.removeClass('disabled');                    
            }
        };
          
          
        function Graph_Init(index){
            var houses = [];
            var flats = [];
            
            this.Loader.ajaxStart(function() { $(this).show(); })
            this.Loader.ajaxComplete(function() { $(this).hide(); })

            $.getJSON(this.AvgPropPriceGraphUrl + '/' + this.EditionId + '/' + this.SaleOrRent + '/' + this.LocationId + '?method=?',
                function(data) {
                    var widget = widgets[index];
                    
                    for (var i in data) {
                        if (data[i].PropertyTypeId == 1) {
                            houses[houses.length] = [data[i].DateCreated, data[i].AveragePrice];
                        }
                        else {
                            flats[flats.length] = [data[i].DateCreated, data[i].AveragePrice];
                        }
                    }
		   
                    $.plot(widget.AveragePropertyPrice,
                        [{ color: widget.Colour3, data: houses, label: 'Houses' },
                         { color: widget.Colour4, data: flats, yaxis: 2, label: 'Flats'}],
                         { series: { lines: { show: true }, points: { show: false} },
                             grid: { color: "black", tickColor: 'white', borderColor: 'white)', backgroundColor: { colors: ["rgb(255, 255, 255)", "rgb(243, 240, 231)"] }, hoverable: true, clickable: true, autoHighlight: true },
                             xaxis: { mode: 'time', ticks: 3, timeformat: '%b' },
                             yaxis: { ticks: 1, tickFormatter: function(v, axis) {
                                 var val = (widget.SaleOrRent == advertType.Sale) ? v / 1000 : v;
                                 return '<span style="color: ' + widget.Colour3 + '">' + val + '</span>'
                             }
                             },
                             y2axis: { ticks: 1, tickFormatter: function(v, axis) {
                                 var val = (widget.SaleOrRent == advertType.Sale) ? v / 1000 : v;
                                 return '<span style="color: ' + widget.Colour4 + '">' + val + '</span>'
                             }
                             },
                             legend: { show: true,
                                 container: widget.LegendId, noColumns: 2,
                                 labelFormatter: function(label, series) {
                                     // series is the series object for the label
                                     return (widget.SaleOrRent == style.Sale) ? label + ' (£K)' : label + ' (£)';
                                 }
                             },
                             height: 155,
                             width: 260
                         });

                    var previousPoint = null;
                    widget.AveragePropertyPrice.bind("plotclick", function(event, pos, item) {
                        if (item && new Date(pos.x) <= new Date()) {
                            var message
                            if (item.seriesIndex == 0) {
                                message = (widget.SaleOrRent == advertType.Sale) ? 'The average house price on ' : 'The average house rental price on ';
                                alert(message + new Date(pos.x).toDateString() + ' was £' + pos.y.toFixed(0));
                            }
                            else {
                                message = (widget.SaleOrRent == advertType.Sale) ? 'The average flat price on ' : 'The average flat rental price on ';
                                alert(message + new Date(pos.x).toDateString() + ' was £' + pos.y2.toFixed(0));
                            }
                        }
                    });
                    
                    if(data.length == 0)
                    {
                        widget.Graph.append('<div class="nodata">No data available</div>');
                        widget.ScreenCount = 1;
                        Navigation_Update(widget)
                    }
                });
            
        };
        
        function Table_Init(index){
	    
	    var houses = [];
            var flats = [];
            
            $.getJSON(this.AvgPropPriceTableUrl + '/' + this.EditionId + '/' + this.SaleOrRent + '/' + this.LocationId + '?method=?',
                 function(data) {
                     for (var i in data) {
                         if (data[i].PropertyTypeId == 1) {
                             houses[houses.length] = [data[i].Bedrooms, data[i].AveragePrice, data[i].PriceComparison];
                         }
                         else {
                             flats[flats.length] = [data[i].Bedrooms, data[i].AveragePrice, data[i].PriceComparison];
                         }
                     }

		     
                     var widget= widgets[index];
                     var MAXRESULT = (houses.length < 3) ? houses.length : 3;
		     var i = 0;
		     while(widget.HousesTable.children('tr').length <= MAXRESULT){
		         var beds = (houses[i][0] == 0) ? "Studio" : houses[i][0] + ' Beds';
                         widget.HousesTable.append('<tr><td style="color:' + widget.Colour3 + '">' + beds + '</td><td style="color:' + widget.Colour3 + '">£' + houses[i][1].toFixed(0) + '</td><td style="color:' + widget.Colour3 + '">' + houses[i][2].toFixed(2) + '%</td></tr>');
			 i++;
                     };

                     MAXRESULT = (flats.length < 3) ? flats.length : 3;
                     i = 0;
		     while (widget.FlatsTable.children('tr').length <= MAXRESULT) {
                         beds = (flats[i][0] == 0) ? "Studio" : flats[i][0] + ' Beds';
                         widget.FlatsTable.append('<tr><td style="color:' + widget.Colour4 + '">' + beds + '</td><td style="color:' + widget.Colour4 + '">£' + flats[i][1].toFixed(0) + '</td><td style="color:' + widget.Colour4 + '">' + flats[i][2].toFixed(2) + '%</td></tr>')
                         i++;
		     };
                 });

        };
        
        function Widget_Log(index){
            if(index > 0) return;
            
            $.getJSON(this.LogVisitUrl +'?method=?');
        
        }
        
        $(style.BaseClass).each(function(i, v){
            widgets[i] = new Widget(i);
        });
        
    });

})(jQuery);  

