﻿var GoogleDealerSearch = new Object();

GoogleDealerSearch.Frontend = function(pageID, paragraphID, containerID) {
    this.containerID = containerID;
    this._container = null;
    this._map = null;
    this._categories = [];
    this._pageID = pageID;
    this._paragraphID = paragraphID;
}

GoogleDealerSearch.Frontend.prototype.get_container = function() {
    if (!this._container) {
        this._container = $(this.containerID);
    }

    return this._container;
}

GoogleDealerSearch.Frontend.prototype.setMapType = function(mapType) {
    this._map.setMapType(mapType);
}

GoogleDealerSearch.Frontend.prototype.selectTab = function(index) {
    this.get_container().select('div.tabContent').each(function(elm, elmIndex) {
        if (elmIndex == index) {
            elm.show();
        } else {
            elm.hide();
        }
    });

    this.get_container().select('li.tabHeader').each(function(elm, elmIndex) {
        if (elmIndex == index) {
            if (!elm.hasClassName('tabActive')) {
                elm.addClassName('tabActive');
            }
        } else {
            elm.removeClassName('tabActive');
        }
    });
}

GoogleDealerSearch.Frontend.prototype.renderMap = function(container) {
    var obj = this;

    this._map = new DealersMap(container);
    this._map.add_dealerSelected(function(sender, args) {
        if (args.dealer) {
            obj._map.showDealerInfo(args.dealer, obj.getDealerInfoHtml(args.dealer.Information));
        }
    });

    this._map.draw();
}

GoogleDealerSearch.Frontend.prototype.setProgress = function(enabled) {
    var sp = this.get_container().select('span.gdsProgress');

    if (sp && sp.length > 0) {
        if (enabled) {
            $(sp[0]).show();
        } else {
            $(sp[0]).hide();
        }
    }
}

GoogleDealerSearch.Frontend.prototype.highlightCategory = function(id) {
    var className = 'cat' + id;

    this.get_container().select('div.mapTab ul li.dealerCategory').each(function(elm) {
        if (elm.hasClassName(className)) {
            if (!elm.hasClassName('dealerCategorySelected')) {
                elm.addClassName('dealerCategorySelected');
            }
        } else {
            elm.removeClassName('dealerCategorySelected');
        }
    });
}

GoogleDealerSearch.Frontend.prototype.clearSelection = function() {
    if (this._map) {
        this._map.clearDealers();
    }
}

GoogleDealerSearch.Frontend.prototype.selectAllCategories = function() {
    var elm = this.get_container().select('input.gdsCategories');

    if (elm && elm.length > 0) {
        this.highlightCategory(-1);
        this.selectCategories(elm[0].value.split(','), true);
    }
}

GoogleDealerSearch.Frontend.prototype.selectCategories = function(ids, showExclusive) {
    var c = null;
    var obj = this;
    var retrieveIDs = [];
    var categoryDealers = [];

    if (ids && ids.length > 0) {
        if (showExclusive) {
            this.clearSelection();
        }

        for (var i = 0; i < ids.length; i++) {
            c = this.getCategoryFromCache(ids[i]);

            if (c != null) {
                this.selectDealers(c.dealers);
            } else {
                retrieveIDs[retrieveIDs.length] = ids[i];
            }
        }

        if (retrieveIDs.length > 0) {
            this.setProgress(true);
            this.getDealers(retrieveIDs, function(dealers) {
                obj.setProgress(false);
                if (dealers != null && dealers.length > 0) {
                    for (var i = 0; i < retrieveIDs.length; i++) {
                        categoryDealers = obj.filterDealersByCategory(retrieveIDs[i], dealers);

                        if (categoryDealers.length > 0) {
                            obj.putCategoryToCache(retrieveIDs[i], categoryDealers);
                        }
                    }

                    obj.selectDealers(dealers);
                }
            });
        }
    }
}

GoogleDealerSearch.Frontend.prototype.selectCategory = function(id, showExclusive) {
    var obj = this;
    var c = this.getCategoryFromCache(id);

    if (showExclusive) {
        this.clearSelection();
    }

    if (c != null) {
        this.selectDealers(c.dealers);
        this.highlightCategory(id);
    } else {
        this.setProgress(true);
        this.getDealers([id], function(dealers) {
            obj.setProgress(false);
            if (dealers != null && dealers.length > 0) {
                obj.putCategoryToCache(id, dealers);
                obj.selectDealers(dealers);
                obj.highlightCategory(id);
            }
        });
    }
}

GoogleDealerSearch.Frontend.prototype.getDealers = function(categories, onComplete) {
    var intID = 0;
    var dealers = [];
    var categoryIDs = '';

    if (categories && categories.length > 0) {
        for (var i = 0; i < categories.length; i++) {
            intID = parseInt(categories[i]);

            if (!isNaN(intID) && intID > 0) {
                categoryIDs += intID.toString();
                if (i < categories.length - 1) {
                    categoryIDs += ',';
                }
            }
        }

        if (categoryIDs.length > 0) {
            var filter = this.get_container().select('input.gdsFilter')
            new Ajax.Request(this.get_selfUrl() + filter[0].value + '&Action=GetDealers&Categories=' + categoryIDs + '&Output=json', {
                onComplete: function(response) {
                    if (response.responseJSON) {
                        dealers = response.responseJSON.Dealers;
                        if (typeof (onComplete) != 'undefined') {
                            onComplete(dealers);
                        }
                    }
                }
            });
        } else {
            if (typeof (onComplete) != 'undefined') {
                onComplete([]);
            }
        }
    } else {
        if (typeof (onComplete) != 'undefined') {
            onComplete([]);
        }
    }
}

GoogleDealerSearch.Frontend.prototype.selectDealers = function(dealers) {
    var minZoom = 99;
    var d = null;

    if (dealers != null && dealers.length > 0) {
        for (var i = 0; i < dealers.length; i++) {
            if (dealers[i].Location.ZoomLevel < minZoom) {
                minZoom = dealers[i].Location.ZoomLevel;
            }

            d = new Dealer(parseFloat(dealers[i].Location.Latitude), parseFloat(dealers[i].Location.Longitude),
                parseInt(dealers[i].Location.ZoomLevel));

            d.Information = dealers[i];

            this._map.addDealer(d, { image: dealers[i].Icon });
        }
        this._map.doScale();
    }
}

GoogleDealerSearch.Frontend.prototype.get_selfUrl = function() {
    var l = location;

    if (!l.protocol) {
        l.protocol = 'http:';
    }

    return l.protocol + '//' + l.hostname + '/Default.aspx?ID=' + 
        this._pageID + '&PID=' + this._paragraphID;
}

GoogleDealerSearch.Frontend.prototype.getCategoryFromCache = function(id) {
    var ret = null;

    if (this._categories && this._categories.length > 0) {
        for (var i = 0; i < this._categories.length; i++) {
            if (this._categories[i].id == id) {
                ret = this._categories[i];
                break;
            }
        }
    }

    return ret;
}

GoogleDealerSearch.Frontend.prototype.filterDealersByCategory = function(id, dealers) {
    var ret = [];

    if (dealers != null && dealers.length > 0) {
        id = parseInt(id);
        
        for (var i = 0; i < dealers.length; i++) {
            if (parseInt(dealers[i].CategoryID) == id || parseInt(dealers[i].categoryId) == id) {
                ret[ret.length] = dealers[i];
            }
        }
    }

    return ret;
}

GoogleDealerSearch.Frontend.prototype.putCategoryToCache = function(id, dealers) {
    if (this._categories) {
        this._categories[this._categories.length] = { id: parseInt(id), dealers: dealers };
    }
}

GoogleDealerSearch.Frontend.prototype.getDealerInfoHtml = function(dealer) {
    var html = '';
    var addr = this.buildAddress(dealer);
    var imagePath = dealer.Image;

    if (imagePath.length > 0) {
        if (imagePath.indexOf('://') < 0) {
            imagePath = '/Files/Billeder/' + imagePath;
        }
    } else {
        imagePath = '/Admin/Images/Nothing.gif';
    }

    html += '<table border="0">';
    html += '<tr><td style="width: 32px" valign="top">';
    html += '<img alt="" src="' + imagePath + '" width="32" border="0" style="margin-top: 5px;" /></td>';
    html += '<td><table border="0"><tr><td><strong>' + dealer.Name + '</strong></td></tr>';
    html += '<tr><td>' + addr.address + '</td></tr>';
    html += '<tr><td>' + addr.phone + '</td></tr>';
    html += '<tr><td><a href="mailto:' + dealer.Email + '">' + dealer.Email + '</a></td></tr>';
    html += '<tr><td><a target="_blank" href="' + dealer.Web + '">' + dealer.Web + '</a></td></tr>';
var localpageLinkID = 'dealerpage-' + dealer.ID;
if(document.getElementById(localpageLinkID))
{
	    html += '<tr><td>' + document.getElementById(localpageLinkID).innerHTML + '</td></tr>';
}
    html += '</table></td></tr></table>';    

    return html;
}

GoogleDealerSearch.Frontend.prototype.buildAddress = function(dealer) {
    var addr = '', phone = '';

    if (dealer) {
        var ar = new Array();
        
        if (dealer.Address.length > 0)
            ar[ar.length] = dealer.Address;
        else if (dealer.Address2.length > 0)
            ar[ar.length] = dealer.Address;
        
        if (ar.length == 1 && dealer.Zip.length > 0)
            ar[0] = dealer.Zip + ' ' + ar[0];

        if (dealer.City.length > 0)
            ar[ar.length] = dealer.City;

        if (dealer.Country.length > 0)
            ar[ar.length] = dealer.Country;

        if (ar.length > 0)
            addr = ar.join(", ");        
            
        if (dealer.Phone.length > 0) {
            phone = dealer.Phone;

            if (dealer.Phone2.length > 0) {
                phone += (' (' + dealer.Phone2 + ')');
            }
        } else {
            phone = dealer.Phone2;
        }
    }

    return { address: addr, phone: phone };
}

GoogleDealerSearch.Frontend.prototype.searchDealers = function() {
    if ($('SearchDistance') && $('SearchZip')) {
        var distance = parseInt($('SearchDistance').value);
        var country = "DK";
        if ($('SearchCountry')) country = $('SearchCountry').value;
        var zip = $('SearchZip').value;
        var address = country + " " + zip;
        GoogleDealerSearch.Frontend.showSearchProgress();
        if (distance > 0 && address.length > 0 && this._map._dealers.length > 0) {
            this._map.getLocationByAddress(address, GoogleDealerSearch.Frontend.filterLocationByZip);
        }
        else {
            GoogleDealerSearch.Frontend.displaySearchResults(true, 0);
            GoogleDealerSearch.Frontend.hideSearchProgress();
        }
    }
}

GoogleDealerSearch.Frontend.showSearchProgress = function(){
    if ($('SearchProgress'))
        $('SearchProgress').show();
}

GoogleDealerSearch.Frontend.hideSearchProgress = function() {
    if ($('SearchProgress'))
        $('SearchProgress').hide();
}

GoogleDealerSearch.Frontend.getInstance = function() {
    return eval($('MapInstance').value);
}

GoogleDealerSearch.Frontend.filterLocationByZip = function(point) {
    var count = 0;
    var that = GoogleDealerSearch.Frontend.getInstance();
    var distance = parseInt($('SearchDistance').value);
    for (var i = 0; i < that._map._dealers.length; i++) {
        var dealer = that._map._dealers[i];
        var km = DealersMap.getDistance({ y: point.x, x: point.y }, dealer.place);
        if (km <= distance) {
            dealer._marker.show();
            count++;
        }
        else
            dealer._marker.hide();
    }
    that._map.doScale();
    GoogleDealerSearch.Frontend.displaySearchResults(true, count);
    GoogleDealerSearch.Frontend.hideSearchProgress();
}

GoogleDealerSearch.Frontend.displaySearchResults = function(display, count) {
    var result = $('SearchResult');
    if (!result)
        return;

    if ($('SearchCount'))
        $('SearchCount').innerHTML = count;

    if (display)
        result.show();
    else
        result.hide();
}
