function getURLVar(key) {
	var value = [];

	var query = String(document.location).split('?');

	if (query[1]) {
		var part = query[1].split('&');

		for (i = 0; i < part.length; i++) {
			var data = part[i].split('=');

			if (data[0] && data[1]) {
				value[data[0]] = data[1];
			}
		}

		if (value[key]) {
			return value[key];
		} else {
			return '';
		}
	}
}

function getUrlPath()
{
    return window.location.pathname.split('/');
}

$(document).ready(function() {
	// Highlight any found errors
	$('.text-danger').each(function() {
		var element = $(this).parent().parent();

		if (element.hasClass('form-group')) {
			element.addClass('has-error');
		}
	});

	// Currency
	$('#form-currency .currency-select').on('click', function(e) {
		e.preventDefault();

		$('#form-currency input[name=\'code\']').val($(this).attr('name'));

		$('#form-currency').submit();
	});

	// Language
	$('#form-language .language-select').on('click', function(e) {
		e.preventDefault();

		$('#form-language input[name=\'code\']').val($(this).attr('name'));

		$('#form-language').submit();
	});

	/* Search */
	$('#search input[name=\'search\']').closest('#search').find('button').on('click', function(e) {
		var url = $('base').attr('href') + 'index.php?route=product/search';

		var value = $('header #search input[name=\'search\']').val();

		if (value) {
			url += '&search=' + encodeURIComponent(value);
		}

		window.location = url;
	});

	$('#search input[name=\'search\']').on('keydown', function(e) {
		if (e.keyCode == 13) {
			$('header #search input[name=\'search\']').closest('#search').find('button').trigger('click');
		}
	});

	// Menu
	$('#menu .dropdown-menu').each(function() {
		var menu = $('#menu').offset();
		var dropdown = $(this).parent().offset();

		var i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth());

		if (i > 0) {
			$(this).css('margin-left', '-' + (i + 10) + 'px');
		}
	});

	// Product List
	$('#list-view').click(function() {
		$(this).blur();
        $('#content .product-grid .product-card').addClass('flex-row flex-wrap');
		$('#content .product-grid').attr('class', 'product-layout product-list');
		$('#grid-view').removeClass('active');
		$('#list-view').addClass('active');

		localStorage.setItem('display', 'list');
	});

	// Product Grid
	$('#grid-view').click(function() {
        $(this).blur();
		// What a shame bootstrap does not take into account dynamically loaded columns
		var cols = $('#column-right, #column-left').length;
        $('#content .product-list .product-card').removeClass('flex-row flex-wrap');
		if (cols == 2) {
			$('#content .product-list').attr('class', 'product-layout product-grid card-deck');
		} else if (cols == 1) {
			$('#content .product-list').attr('class', 'product-layout product-grid card-deck');
		} else {
			$('#content .product-list').attr('class', 'product-layout product-grid card-deck');
		}

		$('#list-view').removeClass('active');
		$('#grid-view').addClass('active');

		localStorage.setItem('display', 'grid');
	});

	if (localStorage.getItem('display') == 'list') {
		$('#list-view').trigger('click');
		$('#list-view').addClass('active');
	} else {
		$('#grid-view').trigger('click');
		$('#grid-view').addClass('active');
	}

	// Checkout
	$(document).on('keydown', '#collapse-checkout-option input[name=\'email\'], #collapse-checkout-option input[name=\'password\']', function(e) {
		if (e.keyCode == 13) {
			$('#collapse-checkout-option #button-login').trigger('click');
		}
	});

	// tooltips on hover
	$('[data-toggle=\'tooltip\']').tooltip({container: 'body'});

	// Makes tooltips work on ajax generated content
	$(document).ajaxStop(function() {
		$('[data-toggle=\'tooltip\']').tooltip({container: 'body'});
	});
});

// Cart add remove functions
var cart = {
    notificationDelay: 300,
    hiddenPopoverDelay: 600,
    //prevent multiple request (clickers ^^)
    currentRequest: null,
    handleCartUpdate: function(items){
        // Need to set timeout otherwise it wont update the total
        setTimeout(function () {
            $('#cart-total').html(parseInt(items) > 0 ? items : '');
        }, 100);
    },
	'add': function(product_id, quantity) {
        if(cart.currentRequest){
            cart.currentRequest.abort();
        }
        cart.currentRequest = $.ajax({
			url: 'index.php?route=checkout/cart/add',
			type: 'post',
			data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
			dataType: 'json',
			success: function(json) {

				if (json['redirect']) {
					window.location = json['redirect'];
				}

				if (json['success']) {
                    useNotification(json['success'], cart.notificationDelay);
					cart.handleCartUpdate(json['total']);

                    if(parseInt(json['total']) < 10 ){
                        $('#cart > ul').load('index.php?route=common/cart/info ul li', function(){
                            $('[data-toggle="popover-cart"]').popover('_fixTitle').popover('update');
                        });
                    }

				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	},
	'update': function(key, quantity) {
        if(cart.currentRequest){
            cart.currentRequest.abort();
        }
        cart.currentRequest = $.ajax({
			url: 'index.php?route=checkout/cart/edit',
			type: 'post',
			data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
			dataType: 'json',
			success: function(json) {
                cart.handleCartUpdate(json['total']);

                if (json['success']) {
                    if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
                        useNotification(json['success'], cart.notificationDelay);
                        $('#cart-summary-container table, #cart-summary-container2 table').load('index.php?route=checkout/cart/info table tr', function(){
                            $('[data-toggle="popover-cart"]').popover('_fixTitle').popover('update');
                        });

                        //$('#prod_'+key).load('index.php?route=checkout/cart/items', { key: key }, function(data){
                        //    //console.log(JSON.parse(data));
                        //    $('#prod_'+key).replaceWith(data);
                        //    setInputQuantity('input_qty'+key, true);
                        //});
                    }
                    $('#cart > ul').load('index.php?route=common/cart/info ul li', function(){
                        $('[data-toggle="popover-cart"]').popover('_fixTitle').popover('update');
                    });
                }
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	},
	'remove': function(key) {
        if(cart.currentRequest){
            cart.currentRequest.abort();
        }
        cart.currentRequest = $.ajax({
			url: 'index.php?route=checkout/cart/remove',
			type: 'post',
			data: 'key=' + key,
			dataType: 'json',
			success: function(json) {
                cart.handleCartUpdate(json['total']);

				if (getUrlPath()[2] == 'cos' || getURLVar('route') == 'checkout/checkout') {
					window.location = '/comanda/cos';
				} else {
					$('#cart > ul').load('index.php?route=common/cart/info ul li', function(){
                        $('[data-toggle="popover-cart"]').popover('_fixTitle').popover('update');
                        if(parseInt(json['total']) === 0){
                            setTimeout(function () {
                                $('[data-toggle="popover-cart"]').popover('hide');
                            }, cart.hiddenPopoverDelay);
                        }
                    });
                }
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	}
}

var voucher = {
	'add': function() {

	},
	'remove': function(key) {
		$.ajax({
			url: 'index.php?route=checkout/cart/remove',
			type: 'post',
			data: 'key=' + key,
			dataType: 'json',
			beforeSend: function() {
				$('#cart > button').button('loading');
			},
			complete: function() {
				$('#cart > button').button('reset');
			},
			success: function(json) {
				// Need to set timeout otherwise it wont update the total
				setTimeout(function () {
					$('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
				}, 100);

				if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
					window.location = 'index.php?route=checkout/cart';
				} else {
					$('#cart > ul').load('index.php?route=common/cart/info ul li', function() {
                        $('[data-toggle="popover-cart"]').popover('update');
                    });
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	}
}

var wishlist = {
    notificationDelay: 300,
    hiddenPopoverDelay: 600,
    handleTriggerChange: function(trigger, product_id, type){
        if(type){
            $(trigger).attr('onclick', 'wishlist.remove("'+product_id+'", this)')
                .attr('data-original-title', 'Adaugat la favorite')
                .tooltip('_fixTitle').tooltip('show').blur()
                .children()
                .attr('fill', '#FD711E');
        }else{
            $(trigger).attr('onclick', 'wishlist.add("'+product_id+'", this)')
                .attr('data-original-title', 'Adauga la favorite')
                .tooltip('_fixTitle').tooltip('show').blur()
                .children()
                .attr('fill', 'none');
        }
    },
	'add': function(product_id, trigger) {
        trigger = (trigger || null);
		$.ajax({
			url: 'index.php?route=account/wishlist/add',
			type: 'post',
			data: 'product_id=' + product_id,
			dataType: 'json',
			success: function(json) {

				if (json['redirect']) {
					location = json['redirect'];
				}

				if (json['success']) {
                    useNotification(json['success'], wishlist.notificationDelay);

                    if(trigger){
                        wishlist.handleTriggerChange(trigger, product_id, 1);
                    }
                    //Mark all products in page
                    wishlist.handleTriggerChange($(document).find('[data-wishlist-id="'+product_id+'"]'), product_id, 1);

                    $('#wishlist-total').attr('title', json['total']).html(parseInt(json['total']) > 0 ? json['total'] : '');

                    $('#wishlist > ul').load('index.php?route=common/wishlist/info ul li', function(){
                        $('[data-toggle="popover-wishlist"]').popover('_fixTitle').popover('update');
                    });
				}

			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	},
	'remove': function(product_id, trigger) {
        $.ajax({
            url: 'index.php?route=account/wishlist/remove',
            type: 'post',
            data: 'product_id=' + product_id,
            dataType: 'json',
            beforeSend: function() {

            },
            complete: function() {

            },
            success: function(json) {
                if (json['redirect']) {
                    location = json['redirect'];
                }

                if (json['success']) {
                    useNotification(json['success'], wishlist.notificationDelay);

                    if(trigger){
                        wishlist.handleTriggerChange(trigger, product_id);
                    }
                    //Mark all products in page
                    wishlist.handleTriggerChange($(document).find('[data-wishlist-id="'+product_id+'"]'), product_id);

                    $('#wishlist-total').attr('title', json['total']).html(parseInt(json['total']) > 0 ? json['total'] : '');
                    $('#wishlist > ul').load('index.php?route=common/wishlist/info ul li', function(){
                        $('[data-toggle="popover-wishlist"]').popover('_fixTitle').popover('update');
                        if(parseInt(json['total']) === 0){
                            setTimeout(function () {
                                $('[data-toggle="popover-wishlist"]').popover('hide');
                            }, wishlist.hiddenPopoverDelay);
                        }
                    });
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
	}
};

var compare = {
    notificationDelay: 300,
    handleTriggerChange: function(trigger, product_id, type){
        if(type){
            $(trigger).attr('onclick', 'compare.remove("'+product_id+'", this)')
                .attr('data-original-title', 'Adaugat la comparare')
                .tooltip('_fixTitle').tooltip('show').blur()
                .children()
                .attr('fill', '#FD711E');
        }else{
            $(trigger).attr('onclick', 'compare.add("'+product_id+'", this)')
                .attr('data-original-title', 'Adauga la comparare')
                .tooltip('_fixTitle').tooltip('show').blur()
                .children()
                .attr('fill', 'none');
        }
    },
	'add': function(product_id, trigger) {
		$.ajax({
			url: 'index.php?route=product/compare/add',
			type: 'post',
			data: 'product_id=' + product_id,
			dataType: 'json',
			success: function(json) {
                if(trigger) {
                    $(trigger).blur();
                }
				if (json['success']) {
                    useNotification(json['success'], compare.notificationDelay);
                    compare.handleTriggerChange(trigger, product_id, 1);
                    //Mark all products in page
                    compare.handleTriggerChange($(document).find('[data-compare-id="'+product_id+'"]'), product_id, 1);
					$('#compare-total').html(json['total']);
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	},
	'remove': function(product_id, trigger) {
        $.ajax({
            url: 'index.php?route=product/compare/remove',
            type: 'post',
            data: 'product_id=' + product_id,
            dataType: 'json',
            success: function(json) {
                if(trigger) {
                    $(trigger).blur();
                }
                if (json['success']) {
                    useNotification(json['success'], compare.notificationDelay);
                    compare.handleTriggerChange(trigger, product_id);
                    //Mark all products in page
                    compare.handleTriggerChange($(document).find('[data-compare-id="'+product_id+'"]'), product_id);
                    $('#compare-total').html(json['total']);
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
	}
};

var checkoutPayment = {


    checkout : function (){
            var getCheckoutType = this._getCheckoutType();

            if (getCheckoutType) {
                if (this._validateAgreements()) {
                    switch (getCheckoutType) {
                        case 'cod':
                            this._setCod();
                            break;
                        case 'euplatesc':
                            this._setEuplatesc();
                            break;
                        case 'cheque':
                            break;
                        case 'bank_transfer':
                            this._setTransfer();
                            break;
                        default:
                            this._setCod();
                    }
                }
            }
            else
            {
                this._renderAgreementError();
            }

    },
    _renderAgreementError : function()
    {

    },
    _validateAgreements : function(){
        var elem = jQuery('#gdpr-wrapper input');
        var blnSuccess = true;
        jQuery.each(elem, function(index, item){
            if(jQuery(item).data('required'))
            {
                jQuery(item).removeClass('is-invalid is-valid');
                if(!jQuery(item).is(':checked'))
                {
                    jQuery(item).addClass('is-invalid');
                    blnSuccess = false;
                }
                else
                {
                    jQuery(item).addClass('is-valid');
                }
            }
        });

        if(blnSuccess)
        {
            var arrVars = [];
            var gdpr = jQuery('#gdpr-wrapper input');
            gdpr.each(function () {
                arrVars.push(jQuery(this).attr('name'));
            });
            jQuery.ajax({
                url: 'index.php?route=common/ajax',
                method: 'post',
                data: { action:'subscribe', arrVars: arrVars },
                dataType: 'json',
                beforeSend: function() {
                    jQuery('#button-confirm').button('loading');
                },
                complete: function() {
                    jQuery('#button-confirm').button('reset');
                },
                success: function(json) {
                    if (json['error'])
                    {
                        //alert(json['error']);
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    //alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                }
            });
        }

        return blnSuccess;

    },
    _setEuplatesc : function()
    {

        jQuery('#euplatesc-form').submit();

    },
    _setCod : function(){
        jQuery.ajax({
            url: 'index.php?route=extension/payment/cod/confirm',
            method:'post',
            dataType: 'json',
            beforeSend: function() {
                jQuery('#button-confirm').button('loading');
            },
            complete: function() {
                jQuery('#button-confirm').button('reset');
            },
            success: function(json) {
                if (json['redirect']) {
                    window.location = json['redirect'];
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr);
            }
        });
    },
    _setTransfer: function(){
        $.ajax({
            url: 'index.php?route=extension/payment/bank_transfer/confirm',
            method:'post',
            dataType: 'json',
            beforeSend: function() {
                $('#button-confirm').button('loading');
            },
            complete: function() {
                $('#button-confirm').button('reset');
            },
            success: function(json) {
                if (json['redirect']) {
                    window.location = json['redirect'];
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr);
            }
        });
    },
    _getCheckoutType : function(){

        return jQuery('#checkout_type').val();

    }
};

var stockAlert = {
    notificationDelay: 300,
    currentRequest: null,
    add: function(){
        if(stockAlert.currentRequest){
            stockAlert.currentRequest.abort();
        }
        stockAlert.currentRequest = $.ajax({
            url: 'index.php?route=common/ajax&action=stock_request',
            type: 'post',
            data: $("#form-stock-alert").serialize(),
            dataType: 'json',
            success: function(json) {
                $('.alert-dismissible, .text-danger').remove();

                if (json['error']) {
                    $('#form-stock-alert').removeClass('needs-validation').addClass('was-validated');
                    $('#input-email').closest('.form-group').find('.invalid-feedback').text(json['error']['email']);
                }

                if(json['warning']){
                    $('#form-stock-alert')
                        .removeClass('was-validated')
                        .addClass('needs-validation')
                        .before('<div class="alert alert-warning alert-dismissible"><i class="fa fa-check-circle"></i> ' + json['warning'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');
                    $('input[name=\'email\']').val('');
                    $('input[name=\'agree\']:checked').prop('checked', false);
                    $('input[name=\'newsletter\']:checked').prop('checked', false);
                }

                if (json['success']) {
                    $('#form-stock-alert').removeClass('was-validated').addClass('needs-validation');
                    $('#stockAlertModal').modal('hide');
                    useNotification(json['success'], stockAlert.notificationDelay);

                    $('input[name=\'email\']').val('');
                    $('input[name=\'agree\']:checked').prop('checked', false);
                    $('input[name=\'newsletter\']:checked').prop('checked', false);
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }
};

var newsletter = {
    subscribe: function(){

        jQuery.ajax({
            url: '/common/ajax',
            type: 'post',
            dataType: 'html',
            data: {action : 'newsletter_popup'},
            success: function(html) {

                $('body').append(html);

                $('#modal-agree').modal('show');
            },
            error: function(xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }
}
    /* Agree to Terms */
$(document).delegate('.agree', 'click', function(e) {
	e.preventDefault();
    window.open($(this).attr('href'), '_blank').focus();
    return;
	$('#modal-agree').remove();

	var element = this;

	$.ajax({
		url: $(element).attr('href'),
		type: 'get',
		dataType: 'html',
		success: function(data) {
			html  = '<div id="modal-agree" class="modal">';
			html += '  <div class="modal-dialog modal-lg">';
			html += '    <div class="modal-content">';
			html += '      <div class="modal-header">';
            html += '        <h4 class="modal-title">' + $(element).text() + '</h4>';
			html += '        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
			html += '      </div>';
			html += '      <div class="modal-body">' + data + '</div>';
			html += '    </div>';
			html += '  </div>';
			html += '</div>';

			$('body').append(html);

			$('#modal-agree').modal('show');
		},
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
	});
});

// Autocomplete */
(function($) {
	$.fn.autocomplete = function(option) {
		return this.each(function() {
			this.timer = null;
			this.items = new Array();

			$.extend(this, option);

			$(this).attr('autocomplete', 'off');

			// Focus
			$(this).on('focus', function() {
				this.request();
			});

			// Blur
			$(this).on('blur', function() {
				setTimeout(function(object) {
					object.hide();
				}, 200, this);
			});

			// Keydown
			$(this).on('keydown', function(event) {
				switch(event.keyCode) {
					case 27: // escape
						this.hide();
						break;
					default:
						this.request();
						break;
				}
			});

			// Click
			this.click = function(event) {
				event.preventDefault();

				value = $(event.target).parent().attr('data-value');

				if (value && this.items[value]) {
					this.select(this.items[value]);
				}
			}

			// Show
			this.show = function() {
				var pos = $(this).position();

				$(this).siblings('ul.dropdown-menu').css({
					top: pos.top + $(this).outerHeight(),
					left: pos.left
				});

				$(this).siblings('ul.dropdown-menu').show();
			}

			// Hide
			this.hide = function() {
				$(this).siblings('ul.dropdown-menu').hide();
			}

			// Request
			this.request = function() {
				clearTimeout(this.timer);

				this.timer = setTimeout(function(object) {
					object.source($(object).val(), $.proxy(object.response, object));
				}, 200, this);
			}

			// Response
			this.response = function(json) {
				html = '';

				if (json.length) {
					for (i = 0; i < json.length; i++) {
						this.items[json[i]['value']] = json[i];
					}

					for (i = 0; i < json.length; i++) {
						if (!json[i]['category']) {
							html += '<li data-value="' + json[i]['value'] + '"><a href="#">' + json[i]['label'] + '</a></li>';
						}
					}

					// Get all the ones with a categories
					var category = new Array();

					for (i = 0; i < json.length; i++) {
						if (json[i]['category']) {
							if (!category[json[i]['category']]) {
								category[json[i]['category']] = new Array();
								category[json[i]['category']]['name'] = json[i]['category'];
								category[json[i]['category']]['item'] = new Array();
							}

							category[json[i]['category']]['item'].push(json[i]);
						}
					}

					for (i in category) {
						html += '<li class="dropdown-header">' + category[i]['name'] + '</li>';

						for (j = 0; j < category[i]['item'].length; j++) {
							html += '<li data-value="' + category[i]['item'][j]['value'] + '"><a href="#">&nbsp;&nbsp;&nbsp;' + category[i]['item'][j]['label'] + '</a></li>';
						}
					}
				}

				if (html) {
					this.show();
				} else {
					this.hide();
				}

				$(this).siblings('ul.dropdown-menu').html(html);
			}

			$(this).after('<ul class="dropdown-menu"></ul>');
			$(this).siblings('ul.dropdown-menu').delegate('a', 'click', $.proxy(this.click, this));

		});
	}
})(window.jQuery);

var app_frontend = {
    ready: function () {

    },
    load: function () {

    },
    resize: function () {

    },
    loadCities: function(objSource, objTarget)
    {
        jQuery.ajax({
            type: 'POST',
            url: objTarget.data('url'),
            data: {action : objTarget.data('action'), zone_id: objSource.val() },
            dataType: 'json',
            success: function(response) {
                if(response)
                {
                    objTarget.empty();
                    objTarget.append('<option value="0">--- Selecteaza o localitate ---</option>');
                    $.each(response.cities, function(key,item){
                        objTarget.append('<option value="'+item.id+'">'+item.name+'</option>');
                    });
                    try {
                        jQuery('.searchbar').select2({
                            theme: 'bootstrap4',
                        });
                    } catch (error){
                        //console.log(error);
                    }
                }
            }
        });
    }
};
function setStorePickup()
{
    jQuery('#custom-control-label-pickup input').on('click', function(){
        jQuery('#shopModal').modal('toggle');
    })
    var locationSelector = function() {
        document.getElementById('location_id').value=this.dataset.storeid;
        jQuery('#custom-control-label-pickup strong').text(this.dataset.storename);
        jQuery('#shopModal').modal('hide');
    };
    var elements = document.getElementsByClassName('store-selector');
    if(elements)
    {
        for (var i = 0; i < elements.length; i++) {
            elements[i].addEventListener('click', locationSelector, false);
        }
    }
}
