/*!
 * @name        
 * @author      Ifeanyi Isitor (ify.iyo@gmail.com) <https://github.com/ifyio/angular-delivery-preference-manager.git>
 * @modified    Thursday, June 5th, 2014, 17:29:55
 * @version     1.0.0
 */

angular.module("duk.dpm", [ "ngCookies", "pascalprecht.translate" ]), angular.module("duk.dpm").service("duk.dpm.buckets.countryBucket", [ "duk.dpm.settings", "duk.dpm.buckets.currencyBucket", "duk.dpm.entities.Country", function(settings, currencyBucket, Country) {
    function populate() {
        angular.forEach(settings.supportedCountries, function(rawCountry) {
            var country = assembledCountryOf(rawCountry);
            self.countries.push(country), self.countriesByCode[country.code] = country, country.code === settings.defaultCountryCode && (self.defaultCountry = country);
        });
    }
    function assembledCountryOf(rawCountry) {
        var country = new Country();
        return country.code = rawCountry.code, country.name = rawCountry.name, country.defaultCurrency = currencyBucket.currenciesByCode[rawCountry.defaultCurrencyCode], 
        angular.forEach(rawCountry.supportedCurrencyCodes, function(currencyCode) {
            country.currencies.push(currencyBucket.currenciesByCode[currencyCode]);
        }), country;
    }
    var self = this;
    return this.countries = [], this.countriesByCode = {}, this.defaultCountry = null, 
    populate(), this;
} ]), angular.module("duk.dpm").service("duk.dpm.buckets.currencyBucket", [ "duk.dpm.settings", "duk.dpm.entities.Currency", function(settings, Currency) {
    function populate() {
        angular.forEach(settings.supportedCurrencies, function(rawCurrency) {
            var currency = new Currency();
            currency.name = rawCurrency.name, currency.code = rawCurrency.code, currency.symbol = rawCurrency.symbol, 
            self.currencies.push(currency), self.currenciesByCode[currency.code] = currency;
        });
    }
    var self = this;
    return this.currencies = [], this.currenciesByCode = {}, populate(), this;
} ]), angular.module("duk.dpm").service("duk.dpm.buckets.languageBucket", [ "duk.dpm.settings", "duk.dpm.entities.Language", function(settings, Language) {
    function populate() {
        return self.hasBeenPopulated || (angular.forEach(settings.supportedSelectorLanguages, function(rawLanguage) {
            var language = new Language().constructedFromRaw(rawLanguage);
            self.languages.push(language), language.code === settings.defaultSelectorLanguageCode && (self.defaultLanguage = language), 
            language.code === settings.selectedSelectorLanguageCode && (self.remotelySelectedlanguage = language);
        }), self.hasBeenPopulated = !0), self;
    }
    var self = this;
    return this.languages = [], this.defaultLanguage = {}, this.remotelySelectedlanguage = void 0, 
    populate(), this;
} ]), angular.module("duk.dpm").factory("duk.dpm.common.deferredOutcomeOf", [ "$q", function($q) {
    function deferredOutcomeOf(action) {
        var deferred = $q.defer();
        return action(deferred), deferred.promise;
    }
    return deferredOutcomeOf;
} ]), angular.module("duk.dpm").factory("duk.dpm.common.extend", [ function() {
    function extend(dest) {
        return this._with = function(src) {
            angular.extend(dest, src);
        }, this;
    }
    return extend;
} ]), angular.module("duk.dpm").factory("duk.dpm.common.stringOf", [ function() {
    function stringOf(string) {
        return {
            replacedWith: function(params) {
                return string.replace(/{([^{}]*)}/g, function(a, b) {
                    var r = params[b];
                    return "string" == typeof r || "number" == typeof r ? r : a;
                });
            }
        };
    }
    return stringOf;
} ]), angular.module("duk.dpm").controller("duk.dpm.Controller", [ "$scope", "duk.dpm.view", "duk.dpm.services.preferencesCookie", "duk.dpm.services.selector", "duk.dpm.services.delivery", "duk.dpm.services.browser", "duk.dpm.services.remoteServiceDelegate", "duk.dpm.common.extend", function($scope, view, preferencesCookie, selector, delivery, browser, remoteServiceDelegate, extend) {
    function _reloadBrowserWithDefaultPreferences() {
        preferencesCookie.updateWithPreferenceOf(delivery.defaultPreference()), preferencesCookie.flagAsNotCreatedWithDefaultPreference(), 
        preferencesCookie.persistToBrowser(), browser.reload();
    }
    $scope.deliveryApp = view.model, this.initialise = function() {
        var defaultDeliveryCountry = delivery.defaultCountry();
        if (view.updateSelectorCountriesWith(delivery.countries()), view.setSelectedSelectorCountryTo(defaultDeliveryCountry), 
        view.updateSelectorCurrenciesWith(defaultDeliveryCountry.currencies), view.setSelectedSelectorCurrencyTo(defaultDeliveryCountry.defaultCurrency), 
        view.updateSupportedLanguagesDisplayInSelectorWith(selector.languages()), selector.languageHasBeenRemotelySelected() && selector.remotelySelectedLanguageIsSupported()) {
            var remotelySelectedLanguage = selector.remotelySelectedLanguage();
            view.translateSelectorTo(remotelySelectedLanguage), view.setStoreFinderLinkLanguageTo(remotelySelectedLanguage);
        } else selector.supportsLanguageOf(browser.language) ? (view.translateSelectorTo(browser.language), 
        view.setStoreFinderLinkLanguageTo(browser.language)) : (view.translateSelectorTo(selector.defaultLanguage()), 
        view.setStoreFinderLinkLanguageTo(selector.defaultLanguage()));
        if (preferencesCookie.isAvailable()) {
            var cookie = preferencesCookie.data(), usersPreference = delivery.preferenceForCodesOf(cookie.countryCode, cookie.currencyCode);
            view.updatePreferenceDisplayWith(usersPreference), view.setSelectedSelectorCountryTo(usersPreference.country), 
            view.updateSelectorCurrenciesWith(usersPreference.country.currencies), view.updateSelectorCurrenciesWith(usersPreference.country.currencies), 
            view.setSelectedSelectorCurrencyTo(usersPreference.currency), preferencesCookie.wasCreatedWithDefaultPreferences() && (view.displayTheBanner(), 
            preferencesCookie.flagAsNotCreatedWithDefaultPreference(), preferencesCookie.persistToBrowser());
        } else view.updatePreferenceDisplayWith(delivery.defaultPreference()), remoteServiceDelegate.loadGeoIpDetails().then(function(geoIP) {
            geoIP.didntSuccessfullyLoad ? _reloadBrowserWithDefaultPreferences() : delivery.networkSupportsCountryWithCodeOf(geoIP.country.code) ? (preferencesCookie.updateWithPreferenceOf(delivery.preferenceForCountryWithCodeOf(geoIP.country.code)), 
            preferencesCookie.flagAsCreatedWithDefaultPreference(), preferencesCookie.persistToBrowser(), 
            browser.reload()) : view.displayTheSelector();
        });
    }, this.deliveryPreferenceIndicatorClicked = function() {
        view.displayTheSelector();
    }, this.selectedCountryChangedInSelector = function() {
        var selectedCountry = view.selectedCountry();
        view.updateSelectorCurrenciesWith(selectedCountry.currencies), view.setSelectedSelectorCurrencyTo(selectedCountry.defaultCurrency);
    }, this.selectorSubmitButtonClicked = function() {
        preferencesCookie.updateWithPreferenceOf(view.selectedDeliveryPreference()), preferencesCookie.flagAsNotCreatedWithDefaultPreference(), 
        preferencesCookie.persistToBrowser(), browser.reload();
    }, this.selectorLanguageButtonClicked = function(selectedLanguage) {
        view.translateSelectorTo(selectedLanguage), view.setStoreFinderLinkLanguageTo(selectedLanguage);
    }, this.selectorCloseButtonClicked = function() {
        preferencesCookie.isNotAvailable() ? _reloadBrowserWithDefaultPreferences() : view.hideTheSelector();
    }, this.bannerCloseButtonClicked = function() {
        view.hideTheBanner();
    }, extend($scope.deliveryApp)._with(this), this.initialise();
} ]), angular.module("duk.dpm").factory("duk.dpm.entities.Country", [ function() {
    function Country() {
        this.name = void 0, this.code = void 0, this.defaultCurrency = void 0, this.currencies = [];
    }
    return Country;
} ]), angular.module("duk.dpm").factory("duk.dpm.entities.Currency", [ "duk.dpm.common.extend", function() {
    function Currency() {
        this.name = void 0, this.code = void 0, this.symbol = void 0;
    }
    return Currency;
} ]), angular.module("duk.dpm").factory("duk.dpm.entities.DeliveryPreference", [ function() {
    function DeliveryPreference() {
        this.country = null, this.currency = null;
    }
    return DeliveryPreference.prototype = {
        constructedFrom: function(country, currency) {
            return this.country = country, this.currency = currency, this;
        }
    }, DeliveryPreference;
} ]), angular.module("duk.dpm").factory("duk.dpm.entities.GeoIP", [ function() {
    function GeoIP() {
        this.country = {
            code: null
        };
    }
    return GeoIP.prototype = {
        constructedFromRaw: function(geo) {
            return this.didntSuccessfullyLoad = !1, this.country.code = geo.countryCode, this;
        },
        constructedFromLoadFailure: function() {
            return this.didntSuccessfullyLoad = !0, this;
        }
    }, GeoIP;
} ]), angular.module("duk.dpm").factory("duk.dpm.entities.Language", [ "duk.dpm.common.extend", function(extend) {
    function Language() {
        this.name = void 0, this.code = void 0;
    }
    return Language.prototype = {
        constructedFromRaw: function(language) {
            return extend(this)._with(language), this;
        }
    }, Language;
} ]), angular.module("duk.dpm").service("duk.dpm.services.browser", [ function() {
    var language = navigator.language ? navigator.language : navigator.userLanguage;
    return this.language = {
        code: language.split("-")[0]
    }, this.reload = function() {
        location.reload();
    }, this;
} ]), angular.module("duk.dpm").service("duk.dpm.services.cookieService", [ function() {
    return this.getCookie = function(sName) {
        sName = sName.toLowerCase();
        for (var oCrumbles = document.cookie.split(";"), i = 0; i < oCrumbles.length; i++) {
            var oPair = oCrumbles[i].split("="), sKey = decodeURIComponent(oPair[0].trim().toLowerCase()), sValue = oPair.length > 1 ? oPair[1] : "";
            if (sKey == sName) return decodeURIComponent(sValue);
        }
        return "";
    }, this.setCookie = function(sName, sValue) {
        var oDate = new Date();
        oDate.setYear(oDate.getFullYear() + 1);
        var sCookie = encodeURIComponent(sName) + "=" + encodeURIComponent(sValue) + ";expires=" + oDate.toGMTString() + ";path=/";
        document.cookie = sCookie;
    }, this.clearCookie = function(sName) {
        this.setCookie(sName, "");
    }, this;
} ]), angular.module("duk.dpm").service("duk.dpm.services.delivery", [ "duk.dpm.buckets.countryBucket", "duk.dpm.buckets.currencyBucket", "duk.dpm.entities.DeliveryPreference", function(countryBucket, currencyBucket, DeliveryPreference) {
    return this.countries = function() {
        return countryBucket.countries;
    }, this.defaultCountry = function() {
        return countryBucket.defaultCountry;
    }, this.countryWithCodeOf = function(countryCode) {
        return countryBucket.countriesByCode[countryCode];
    }, this.currencyWithCodeOf = function(currencyCode) {
        return currencyBucket.currenciesByCode[currencyCode];
    }, this.defaultPreference = function() {
        var defaultCountry = countryBucket.defaultCountry;
        return new DeliveryPreference().constructedFrom(defaultCountry, defaultCountry.defaultCurrency);
    }, this.preferenceForCountryWithCodeOf = function(countryCode) {
        var country = countryBucket.countriesByCode[countryCode];
        return new DeliveryPreference().constructedFrom(country, country.defaultCurrency);
    }, this.preferenceForCodesOf = function(countryCode, currencyCode) {
        var country = this.countryWithCodeOf(countryCode), currency = this.currencyWithCodeOf(currencyCode);
        return new DeliveryPreference().constructedFrom(country, currency);
    }, this.networkSupportsCountryWithCodeOf = function(countryCode) {
        var result = !1, countries = countryBucket.countries;
        for (var i in countries) {
            var country = countries[i];
            if (country.code === countryCode) {
                result = !0;
                break;
            }
        }
        return result;
    }, this;
} ]), angular.module("duk.dpm").service("duk.dpm.services.preferencesCookie", [ "$cookies", "duk.dpm.services.cookieService", "duk.dpm.settings", function($cookies, cookieService, settings) {
    var _rawCookie = {
        isDefaultPreference: !1,
        countryCode: void 0,
        currencyCode: void 0
    };
    return this.isAvailable = function() {
        return void 0 !== this.data();
    }, this.isNotAvailable = function() {
        return !this.isAvailable();
    }, this.wasCreatedWithDefaultPreferences = function() {
        return _rawCookie.isDefaultPreference;
    }, this.flagAsCreatedWithDefaultPreference = function() {
        _rawCookie.isDefaultPreference = !0;
    }, this.flagAsNotCreatedWithDefaultPreference = function() {
        _rawCookie.isDefaultPreference = !1;
    }, this.data = function() {
        if (void 0 === _rawCookie.countryCode && void 0 === _rawCookie.currencyCode) {
            var cookie = $cookies[settings.cookieName];
            if (void 0 === cookie) return;
            _rawCookie = JSON.parse(cookie);
        }
        return _rawCookie;
    }, this.updateWithPreferenceOf = function(preference) {
        _rawCookie.countryCode = preference.country.code, _rawCookie.currencyCode = preference.currency.code;
    }, this.persistToBrowser = function() {
        var cookie = {
            isDefaultPreference: _rawCookie.isDefaultPreference,
            countryCode: _rawCookie.countryCode,
            currencyCode: _rawCookie.currencyCode
        };
        cookieService.setCookie(settings.cookieName, JSON.stringify(cookie));
    }, this;
} ]), angular.module("duk.dpm").service("duk.dpm.services.remoteServiceDelegate", [ "$http", "duk.dpm.settings", "duk.dpm.entities.GeoIP", "duk.dpm.common.deferredOutcomeOf", function($http, settings, GeoIP, deferredOutcomeOf) {
    return this.loadGeoIpDetails = function() {
        return deferredOutcomeOf(function(deferred) {
            var httpResult = $http({
                method: "GET",
                url: settings.remoteGeoIpLookupUrl
            });
            httpResult.success(function(result) {
                deferred.resolve(new GeoIP().constructedFromRaw(result));
            }), httpResult.error(function() {
                deferred.resolve(new GeoIP().constructedFromLoadFailure());
            });
        });
    }, this;
} ]), angular.module("duk.dpm").service("duk.dpm.services.selector", [ "duk.dpm.settings", "duk.dpm.buckets.languageBucket", function(settings, languageBucket) {
    return this.languages = function() {
        return languageBucket.languages;
    }, this.languageHasBeenRemotelySelected = function() {
        return angular.isDefined(languageBucket.remotelySelectedlanguage);
    }, this.remotelySelectedLanguageIsSupported = function() {
        return this.supportsLanguageOf(languageBucket.remotelySelectedlanguage);
    }, this.remotelySelectedLanguage = function() {
        return languageBucket.remotelySelectedlanguage;
    }, this.supportsLanguageOf = function(language) {
        var languages = languageBucket.languages;
        for (var i in languages) {
            var result = !1, existingLanguage = languages[i];
            if (existingLanguage.code === language.code) {
                result = !0;
                break;
            }
        }
        return result;
    }, this.defaultLanguage = function() {
        return languageBucket.defaultLanguage;
    }, this;
} ]), angular.module("duk.dpm").provider("duk.dpm.settings", [ function settings() {
    this.remoteLanguageTranslationsUrl = "", this.remoteGeoIpLookupUrl = "", this.supportedCountries = [], 
    this.supportedCurrencies = [], this.supportedSelectorLanguages = [], this.selectedSelectorLanguageCode = void 0, 
    this.defaultCountryCode = "", this.defaultCurrencyCode = "", this.defaultSelectorLanguageCode = "", 
    this.cookieName = "";
    var settings = this;
    return {
        settings: settings,
        $get: function() {
            return settings;
        }
    };
} ]), angular.module("duk.dpm").service("duk.dpm.view", [ "$rootScope", "$translate", "duk.dpm.entities.DeliveryPreference", "duk.dpm.services.delivery", function($rootScope, $translate, DeliveryPreference, delivery) {
    function _selectorCountryWithCodeOf(countryCode) {
        for (var i in model.selectorCountries) {
            var selectorCountry = model.selectorCountries[i];
            if (selectorCountry.code == countryCode) return selectorCountry;
        }
    }
    function _selectorCurrencyWithCodeOf(currencyCode) {
        for (var i in model.selectorCurrencies) {
            var selectorCurrency = model.selectorCurrencies[i];
            if (selectorCurrency.code == currencyCode) return selectorCurrency;
        }
    }
    function _displaySpecificCountryFor(domainSpecificCountry) {
        return {
            name: domainSpecificCountry.name,
            code: domainSpecificCountry.code
        };
    }
    function _displaySpecificLanguageFor(domainSpecificLanguage) {
        return {
            name: domainSpecificLanguage.name,
            code: domainSpecificLanguage.code,
            isSelected: !1
        };
    }
    function _displaySpecificCurrencyFor(domainSpecificCurrency) {
        return {
            name: domainSpecificCurrency.name,
            code: domainSpecificCurrency.code,
            symbol: domainSpecificCurrency.symbol,
            label: domainSpecificCurrency.symbol + " " + domainSpecificCurrency.name
        };
    }
    var model = {
        bannerIsVisible: !1,
        bannerCountryName: "",
        bannerCurrencyCode: "",
        preferenceIndicatorCountryCode: "",
        preferenceIndicatorCurrencySymbol: "",
        preferenceIndicatorCurrencyCode: "",
        selectedCountry: {},
        selectedCurrency: {},
        selectorIsVisible: !1,
        selectorCountries: [],
        selectorCurrencies: [],
        selectorLanguages: [],
        storeFinderLinkLanguageCode: ""
    };
    return this.model = model, this.updatePreferenceDisplayWith = function(deliveryPreference) {
        model.bannerCountryName = deliveryPreference.country.name, model.bannerCountryCode = deliveryPreference.country.code, 
        model.bannerCurrencyCode = deliveryPreference.currency.code, model.preferenceIndicatorCountryCode = deliveryPreference.country.code.toLowerCase(), 
        model.preferenceIndicatorCurrencyCode = deliveryPreference.currency.code, model.preferenceIndicatorCurrencySymbol = deliveryPreference.currency.symbol;
    }, this.updateSupportedLanguagesDisplayInSelectorWith = function(languages) {
        angular.forEach(languages, function(domainSpecificLanguage) {
            var languageToDisplay = _displaySpecificLanguageFor(domainSpecificLanguage);
            model.selectorLanguages.push(languageToDisplay);
        });
    }, this.updateSelectorCountriesWith = function(countries) {
        angular.forEach(countries, function(domainSpecificCountry) {
            var countryToDisplay = _displaySpecificCountryFor(domainSpecificCountry);
            model.selectorCountries.push(countryToDisplay);
        });
    }, this.setSelectedSelectorCountryTo = function(country) {
        model.selectedCountry = _selectorCountryWithCodeOf(country.code);
    }, this.updateSelectorCurrenciesWith = function(currencies) {
        model.selectorCurrencies = [], angular.forEach(currencies, function(domainSpecificCurrency) {
            var currencyToDisplay = _displaySpecificCurrencyFor(domainSpecificCurrency);
            model.selectorCurrencies.push(currencyToDisplay);
        });
    }, this.setSelectedSelectorCurrencyTo = function(currency) {
        model.selectedCurrency = _selectorCurrencyWithCodeOf(currency.code);
    }, this.selectedCountry = function() {
        return delivery.countryWithCodeOf(model.selectedCountry.code);
    }, this.displayTheBanner = function() {
        model.bannerIsVisible = !0;
    }, this.hideTheBanner = function() {
        model.bannerIsVisible = !1;
    }, this.displayTheSelector = function() {
        model.selectorIsVisible = !0;
    }, this.hideTheSelector = function() {
        model.selectorIsVisible = !1;
    }, this.selectedDeliveryPreference = function() {
        return delivery.preferenceForCodesOf(model.selectedCountry.code, model.selectedCurrency.code);
    }, this.translateSelectorTo = function(language) {
        $translate.uses(language.code), angular.forEach(model.selectorLanguages, function(selectorLanguage) {
            selectorLanguage.isSelected = selectorLanguage.code === language.code ? !0 : !1;
        });
    }, this.setStoreFinderLinkLanguageTo = function(language) {
        model.storeFinderLinkLanguageCode = language.code;
    }, this;
} ]), function() {
    var $translateProvider, app = angular.module("duk.dpm.module", [ "duk.dpm" ]);
    app.config([ "$translateProvider", function(_$translateProvider) {
        $translateProvider = _$translateProvider;
    } ]), app.run([ "duk.dpm.settings", function(settings) {
        function translationUrlParts() {
            var urlParts = settings.remoteLanguageTranslationsUrl.split("{language}");
            return "" === urlParts[1] && (urlParts[1] = " "), urlParts;
        }
        var urlParts = translationUrlParts();
        $translateProvider.useStaticFilesLoader({
            prefix: urlParts[0],
            suffix: urlParts[1]
        });
    } ]);
}();