﻿var Staples = {};

Staples.Utilities = {
    Loader: {
        nudge: function (url, trigger) {
            $.ajax({
                cache: false,
                type: 'POST',
                url: url,
                dataType: 'json',
                success: trigger
            });
        },
        load: function (url, target, message, messageType) {
            successFunctions = [];

            if (target) {
                successFunctions.push(function (data) {
                    $(target).html(data);
                });
            }

            if (message) {
                successFunctions.push(function (data) {
                    if (messageType && messageType === 'alert') {
                        alert(message);
                    } else {
                        Staples.Utilities.Loader.addMessage(message);
                    }
                });
            }

            $.ajax({
                cache: false,
                type: 'POST',
                url: url,
                dataType: 'html',
                success: successFunctions
            });
        },
        addMessage: function (message) {
            var messageId = 'id-' + Staples.Utilities.Loader.guid();
            var message = ['<li id="', messageId, '">', message, '</li>'].join('');

            var messageContainer = $('#message-container');
            if (messageContainer.length == 0) {
                messageContainer = $(document.createElement('ul'));
                messageContainer.attr('id', 'message-container');
                $('body').append(messageContainer);
            }

            messageContainer.append(message);
            window.setTimeout(function () {
                $('#' + messageId).remove();
                if ($('#message-container li').length == 0) {
                    $('#message-container').remove();
                }
            }, 2000);
        },
        s4: function () {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        },
        guid: function () {
            return (Staples.Utilities.Loader.s4() + Staples.Utilities.Loader.s4() + "-" + Staples.Utilities.Loader.s4() + "-" + Staples.Utilities.Loader.s4() + "-" + Staples.Utilities.Loader.s4() + "-" + Staples.Utilities.Loader.s4() + Staples.Utilities.Loader.s4() + Staples.Utilities.Loader.s4());
        }
    },
    Publisher: {
        subscribers: {
            any: []
        },
        subscribe: function (fn, type) {
            type = type || 'any';
            if (typeof this.subscribers[type] === "undefined") {
                this.subscribers[type] = [];
            }

            this.subscribers[type].push(fn);
            return this;
        },
        publish: function (type, data) {
            var i, imax, a;

            type = type || 'any';
            if (typeof this.subscribers[type] === "undefined") {
                return;
            }

            for (a = this.subscribers[type], imax = a.length, i = 0; i < imax; i += 1) {
                Staples.Utilities.Publisher.trigger(a[i], data);
            }
            return this;
        },
        trigger: function (fn, data, init) {
            if (typeof fn === "function") {
                fn(data);
            } else if (typeof fn === "string") {
                Staples.Utilities.Loader.load(fn);
            } else if (typeof fn === "object" && fn.url && !init) {
                Staples.Utilities.Loader.load(fn.url, fn.target, fn.message, fn.messageType);
            } else if (typeof fn === "object" && fn.url && init) {
                Staples.Utilities.Loader.load(fn.url, fn.target, null);
            }
        }
    }
};

Staples.UI = {
    init: function () {
        Staples.UI.Slider.init();
        Staples.UI.Quicksearch.init();
        Staples.UI.Location.init();
    },
    Gallery: {
        mouseover: function (large, src, name, thumbs) {
            $(large).attr('src', src).attr('alt', name);
            if (thumbs) {
                $(thumbs).removeClass('selected');
            }
        }
    },
    Location: {
        latitude: null,
        longitude: null,
        init: function () {
            if (!Staples.UI.Location.latitude || !Staples.UI.Location.longitude) {
                if (navigator.geolocation && navigator.geolocation.getCurrentPosition) {
                    navigator.geolocation.getCurrentPosition(Staples.UI.Location.success, Staples.UI.Location.failed)
                }
            }
            $('.show-location-changer').on('click', Staples.UI.Location.changer);
            $('#location-changer input[type="text"]').on('keydown', function (e) {
                if (e.keyCode == 27) {
                    Staples.UI.Location.hide();
                }
            });
        },
        changer: function (e) {
            var doc = $(document);
            var docOldWidth = $(window).width();

            if (e) {
                var target = $(e.currentTarget);
                var targetTop = target.offset().top;
                var targetLeft = target.offset().left + target.outerWidth() / 2;

                var changer = $('#location-changer');
                changer.css('top', targetTop).css('left', targetLeft).toggle();

                var docNewWidth = doc.width();
                if (docNewWidth > docOldWidth) {
                    changer.css('left', targetLeft - (docNewWidth - docOldWidth) - 16);
                }

                if (targetTop + changer.outerHeight() > doc.scrollTop() + $(window).height()) {
                    changer.css('top', doc.scrollTop() + $(window).height() - changer.outerHeight() - 32);
                }

                $('#location-changer-bg').width(docOldWidth).height(doc.height()).toggle().click(Staples.UI.Location.hide);
                $('#location-changer:visible').find('input[type="text"]').focus().select();
            }
            return false;
        },
        hide: function () {
            $('#location-changer-bg').hide();
            $('#location-changer').hide();
        },
        success: function (position) {
            $.ajax({
                cache: false,
                type: 'POST',
                url: '/de-DE/Notification/Location',
                data: ['latitude=', position.coords.latitude, '&', 'longitude=', position.coords.longitude].join(''),
                dataTypeString: 'xml',
                success: function (data) {
                    $('#your-location-city').text(data.city);
                    $('#your-location').fadeOut().fadeIn().fadeOut().fadeIn();
                    if (data.reload) {
                        Staples.Utilities.Loader.addMessage(data.message);
                        location.reload();
                    }
                }
            });
        },
        failed: function () { }
    },
    Slider: {
        sliders: null,
        timerId: null,
        autoscroll: function () {
            for (i = 0, im = Staples.UI.Slider.sliders.length; i < im; i++) {
                var checked = $(Staples.UI.Slider.sliders[i]).find('input:checked');

                var toCheck = $(Staples.UI.Slider.sliders[i]).find('input:checked ~ input');
                if (toCheck.length == 0) {
                    toCheck = $(Staples.UI.Slider.sliders[i]).find('input[type="radio"]:first-child');
                }

                if (toCheck.length > 0) {
                    $(toCheck[0]).attr('checked', true);
                    $('div.slider-content:visible, div.slider-content-background:visible', Staples.UI.Slider.sliders[i]).fadeOut('fast', function () {
                        $('input:checked + label.slider-thumb + div.slider-content', Staples.UI.Slider.sliders[i]).next().fadeIn('fast', function () {
                            $(this).prev().fadeIn('fast');
                        });
                    });
                }
            }
        },
        init: function () {
            Staples.UI.Slider.sliders = $('div.animated-slider');
            Staples.UI.Slider.timerId = window.setInterval(Staples.UI.Slider.autoscroll, 5000);

            $('input:checked', 'div.slider').next().next().show().next().show();
            $('label', 'div.slider').on('click', function () {
                var clicked = $(this);

                window.clearInterval(Staples.UI.Slider.timerId);
                //Staples.Utilities.Publisher.publish('slider_clicked', { target: clicked });

                var clicked_parent = clicked.parents('div.slider');
                $('div.slider-content:visible, div.slider-content-background:visible', clicked_parent).fadeOut('fast', function () {
                    $('input:checked + label.slider-thumb + div.slider-content', clicked_parent).next().fadeIn('fast', function () {
                        $(this).prev().fadeIn('fast');
                    });
                });
            });
        }
    },
    Quicksearch: {
        init: function () {
            var search = $('#search');

            var dropdown = search.find('select');
            dropdown.css('opacity', 0);
            dropdown.css('filter', 'alpha(opacity=0)');
            dropdown.prev().text(dropdown.find(':selected').text());
            dropdown.click(function () {
                var self = $(this);
                self.prev().text(self.find(':selected').text());
            });
        }
    }
}

Staples.Init = function () {
	Staples.UI.init();

	$('form').submit(function () {
	    var form = $(this);
	    if (form.hasClass('keep-position')) {
	        var top = $(document).scrollTop();
	        if (top > 0) {
	            form.attr('action', [form.attr('action'), '#', top].join(''));
	        }
	    }

	    var allFields = $('input[type="text"],textarea', form);
	    for (i = 0, im = allFields.length; i < im; i++) {
	        var field = $(allFields[i]);
	        field.val(field.val().replace(/<(\S)/g, '< $1'));
	    }
	});

	$('input.focus').focus();

	$('a.keep-position').on('click', function (e) {
		var link = $(this);
		var top = $(document).scrollTop();

		if (top > 0) {
			link.attr('href', [link.attr('href').replace(/#(\d+)/g, ''), '#', top].join(''));
		}
	});
	$('a.blank').on('click', function (e) {
		var newWindow = window.open(this.getAttribute('href'), '_blank');
		newWindow.focus();
		return false;
	});

	var hash = self.document.location.hash;
	if (hash) {
		var match = hash.match('#(\\d+)');
		try {
			$(document).scrollTop(parseInt(match[1]));
		} catch (e) { }
	}
};

$(Staples.Init);
