petzl.controllers.DealerLocator = function() {
    UTILS.compileDustTemplates();

    var getInitialPos = function() {
        console.log('getInitialPos()');
        if (navigator.geolocation) {
            console.log("navigator.geolocation: ", navigator.geolocation);

            navigator.geolocation.getCurrentPosition(function(position) {

                // position = {
                //     coords: {
                //         latitude: 45.27202,
                //         longitude: 5.88303
                //     }
                // };

                //MY 22.6.2015 reverse geoccoding -get lang,lat ->return country
                var geocoder = new google.maps.Geocoder();
                var myCountry = null;
                var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                geocoder.geocode({
                    'latLng': latlng
                }, function(results, status) {
                    console.log('results ' + JSON.stringify(results));
                    if (status == google.maps.GeocoderStatus.OK) {
                        myCountry = getCountryFromResult(results);
                        getDealers(position.coords.latitude, position.coords.longitude, myCountry); //NEED TO FIND THE COUNTRY!
                    } else {
                        console.log('No results found');
                    }
                });


                var geocoder = new google.maps.Geocoder();

                var initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

                if (geocoder) {
                    geocoder.geocode({
                        'latLng': initialLocation
                    }, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {

                            $('#myAddress').html(results[0].formatted_address);
                        } else {
                            $('#myAddress').html('Geocoding failed: ' + status);

                        }
                    }); //geocoder.geocode()
                }
            });
        } else {
            console.log('error in navigator.geolocation');
        }
    }

    //My 22.6.2015; take unicode and made them to symboles like & and ext.
    //Req 3889 add more fields
    function unicodeFixer(result) {
        for (i = 0; i < result.length; i++) {
            result[i].Name = decodeHtml(result[i].Name);
            result[i].City__c = decodeHtml(result[i].City__c);
            result[i].Street__c = decodeHtml(result[i].Street__c);
			if(result[i].Phone__c == undefined)
			{
				result[i].Phone__c = null;
			}
			else
			{
				result[i].Phone__c = decodeHtml(result[i].Phone__c);
			}
            
			
			
			if(result[i].Website__c == undefined)
			{
				result[i].Website__c = null;
			}
			else
			{
				result[i].Website__c = decodeHtml(result[i].Website__c);
			}
            
            if (result[0].Country__r !== undefined)
                result[i].Country__r.Name = decodeHtml(result[i].Country__r.Name);
        }
        return result;
    }
    //My 22.6.2015 : the mighty function by http://stackoverflow.com/questions/7394748/whats-the-right-way-to-decode-a-string-that-has-special-html-entities-in-it
    function decodeHtml(str) {
        var txt = document.createElement("textarea");
        txt.innerHTML = str;
        return txt.value;
    }

    var getDealers = function(posLat, posLang, country) {

        // Remote Action
        WebMobile_DealerLocator.getDealersByCoordinatesCenterMobile(UTILS.universId, posLat, posLang, country, function(result, event) {

            if (result.length > 0) {
                calculateDistance(posLat, posLang, result);
                result = unicodeFixer(result);
                UTILS.dustRender('tmpl_onlineDealer', result, $('.shopContainer'));
                $('#resultNumber').text(+result.length + ' ' + $('#resualtWebLabel').text());
            } else {
                //MY 21.06.2015 

                $('#resultNumber').text('0 ' + $('#resualtWebLabel').html());
                $('#resualttext').show();
                var resDest = JSON.parse($("input[id='IntDestributer']").val());
                calculateDistance(posLat, posLang, resDest);
                resDest.distance = Math.ceil(getDistanceFromLatLonInKm(posLat, posLang, resDest[0].Geocode__Latitude__s, resDest[0].Geocode__Longitude__s));
                UTILS.dustRender('tmpl_onlineDestINT', resDest, $('.shopContainer')); // with the INT PETZL
            }
        });
    }


    var calculateDistance = function(posLat, posLang, dealerList) {
        for (var i = 0; i < dealerList.length; i++) {
            var distance = getDistanceFromLatLonInKm(posLat, posLang, dealerList[i].Geocode__Latitude__s, dealerList[i].Geocode__Longitude__s);
            dealerList[i].distance = Math.ceil(distance);
        }
    }





    function getCountryFromResult(results) {
        var address_components = results[0].address_components;
        for (var x = 0; x < address_components.length; x++) {
            if (address_components[x].types.indexOf("country") > -1) {
                return address_components[x].short_name;
            }
        }
        return null;
    }

    var pageEvent = function() {
        $('#locateAddress').click(function() {
            $(".shopResult").remove();
            var addressInpt = $("input[id='addressInput']").val();
            new google.maps.Geocoder().geocode({
                'address': addressInpt
            }, function(results, status) { //MY :21.06.2015'language': 'en' -The resualts will back only in english and dont in the broswer lang
                // MY 18.06.2015 WHEN THERE IS NO RESUTLTTT
                $('#resualttext').css('display', 'none');
                $('#resualtDes').css('display', 'none');

                if (status == google.maps.GeocoderStatus.OK) {
                    var country = getCountryFromResult(results);
                    getDealers(results[0].geometry.location.lat(), results[0].geometry.location.lng(), country);
                }
                // MY 18.06.2015 WHEN THERE IS NO RESUTLTTT
                else {
                    $('#resultNumber').text('0 ' + $('#resualtWebLabel').html());
                    $('#resualttext').show();
                    var resDest = JSON.parse($("input[id='IntDestributer']").val());
                    UTILS.dustRender('tmpl_onlineDestINT', resDest, $('.shopContainer')); // with the INT PETZL

                }
            });
        });

        $('#addressInput').keypress(function(event) {
            if (event.which === 13)
                $('#locateAddress').click();
        });

    }

    var distanceEvent = function() {
        $('.shopContainer').on('click', '.distance', function() {

            var addr = $(this).parent().find('.address').attr('data-id');
            var mylocation = $('#myAddress').html();
            var url = 'https://maps.google.com/maps?z=25&t=s&daddr=' + addr + '&saddr=' + mylocation;
            window.open(url, '_blank');

        });
    }

    var nearLocEvent = function() {
        $('#closeDealersButton').click(function() {
            $(".shopResult").remove();
            getInitialPos();
        });
    }

    var getDistanceFromLatLonInKm = function(lat1, lon1, lat2, lon2) {
        var R = 6371; // Radius of the earth in km
        var dLat = deg2rad(lat2 - lat1); // deg2rad below
        var dLon = deg2rad(lon2 - lon1);
        var a =
            Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = R * c; // Distance in km
        return d;
    }

    var deg2rad = function(deg) {
        return deg * (Math.PI / 180)
    }


    //my 23.06
    // var getCountryFromAdd =function(result){
    // 	var splitAddress = result.formatted_address.split(', ');
    // 	var Countrycode = result.address_components[result.address_components.length-1].short_name;
    // 	return splitAddress[splitAddress.length-1];
    // }

    //my 23.06
    // var getCountryCodeFromAdd =function(result){
    // 	var Countrycode = result.address_components[result.address_components.length-1].short_name;
    // 	return String(Countrycode);
    // }

    pageEvent();
    nearLocEvent();
    getInitialPos();
    distanceEvent();
}