﻿var TENews = new function() {

    this.onLoad = function() {
        $('a[rel="external"]').attr('target', '_blank');

        swfobject.embedSWF("/img/clock-locman.swf", "clock", "130", "100", "9.0.0");
        TENews.Load.enableBlinkingText();
        if ($.datepicker) {
            TENews.Load.enableDatePickers();
        }
        TENews.Load.setNavCurrentLink();
        $('a[rel=lightbox]').colorbox({ maxHeight: '80%' });
    };
};       // ns TENews

// NAMESPACE TENews.Load
// Contiene metodi da eseguire al caricamento della pagina, come gestori di eventi e così via.
TENews.Load = new function() {

    this.enableNewsTicker = function(list, speed, pause, elementsToShow) {
        if (list.data('ticker')) return;
        list.css('height', (list.find('li:first').outerHeight() * elementsToShow + 8 * elementsToShow - 16) + 'px').data('ticker', 1);
        function newsTicker() {
            var first = list.find('li:first');
            first.slideUp(speed, function() {
                $(this).remove().appendTo(list).show();
            });
        }

        interval = setInterval(newsTicker, pause);
    };

    this.enableEnterForSubmit = function(input, submit) {
        input.keypress(function(e) {
            if (e.which == 13) {
                submit.trigger('click');
            }
        });
    };

    this.embedYouTubeVideo = function(videoId, width, height) {
        if (!width) width = "700";
        if (!height) height = "400";

        $(document).ready(function() {
            $('#video').replaceWith('<iframe class="youtube-player" type="text/html" width="' + width + '" height="' + height + '" src="http://www.youtube.com/embed/' + videoId + '" frameborder="0"></iframe>');
        });
    };

    this.embedYouTubeVideoElement = function(elementId, videoId, width, height) {
        if (!width) width = "700";
        if (!height) height = "400";

        $(document).ready(function() {
            $('#' + elementId).replaceWith('<iframe class="youtube-player" type="text/html" width="' + width + '" height="' + height + '" src="http://www.youtube.com/embed/' + videoId + '" frameborder="0"></iframe>');
        });
    };

    this.enableBlinkingText = function() {
        var interval = setInterval("TENews.Load.doBlink()", 800);
    };

    this.doBlink = function() {
        $('.blink').each(function() {
            $(this).css('visibility', $(this).css('visibility') != 'hidden' ? 'hidden' : 'visible');
        });
    };

    this.enableDatePickers = function() {
        var dates = $(".date input").attr('autocomplete', 'off').datepicker({
            changeMonth: true,
            changeYear: true,
            onSelect: function(selectedDate) {
                if ($(this).hasClass("startdate")) {
                    instance = $(this).data("datepicker");
                    date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
                    dates.not(this).datepicker("option", "minDate", date);
                }
            }
        });
    };

    this.setNavCurrentLink = function() {
        var location = document.location.pathname;
        if (location.lastIndexOf('/') > 1) {
            var parentLocation = '/' + location.substring(1, location.substring(1).indexOf('/') + 1) + '/';
            $('#nav li a[href="' + parentLocation + '"]').addClass('current');
        }
        $('#nav li a[href="' + location + '"]').addClass('current');
    };

    this.createLatLongMap = function(mapElementId, latitude, longitude) {
        var mapCenter = new google.maps.LatLng(latitude, longitude);
        var opts = {
            zoom: 11,
            center: mapCenter,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false
        };

        var map = new google.maps.Map(document.getElementById(mapElementId), opts);

        var marker = new google.maps.Marker({
            position: mapCenter,
            map: map
        });
    };

    this.createLatLongMapEditor = function(mapElementId, latitudeInputId, longitudeInputId) {
        var mapCenter = new google.maps.LatLng(42.792377, 10.283203);
        var opts = {
            zoom: 11,
            center: mapCenter,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false
        };

        var latitudeInput = $('#' + latitudeInputId);
        var longitudeInput = $('#' + longitudeInputId);

        var map = new google.maps.Map(document.getElementById(mapElementId), opts);

        var marker;

        if (latitudeInput.val() != '' && longitudeInput.val() != '') {
            placeMarker(new google.maps.LatLng(parseFloat(latitudeInput.val()), parseFloat(longitudeInput.val())));

            map.setCenter(marker.getPosition());
            map.setZoom(13);
        }

        google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(event.latLng);
            latitudeInput.val(event.latLng.lat());
            longitudeInput.val(event.latLng.lng());
        });

        function placeMarker(location) {
            if (marker) {
                marker.setPosition(location);
            } else {
                marker = new google.maps.Marker({
                    position: location,
                    map: map
                });
            }
        }
    };

    this.enableCKEditorEvents = function() {
        for (instance in CKEDITOR.instances) {
            CKEDITOR.instances[instance].on("instanceReady", function() {
                this.document.on("keyup", function() { CKEDITOR.instances[instance].updateElement(); });
                this.document.on("paste", function() { CKEDITOR.instances[instance].updateElement(); });
                this.document.on("cut", function() { CKEDITOR.instances[instance].updateElement(); });
            });
        }
    };
};    // ns TENews.Load

TENews.Actions = new function() {

    this.closePoster = function(posterId) {
        var currentDate = new Date();
        expirationDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate() + 1, 0, 0, 0);
        $.cookie("poster-" + posterId, "1", { expires: expirationDate });

        $('.poster-large').removeClass('poster-large').addClass('poster-small');
    };
};

TENews.BuySell = new function() {

    var maxPhotos;
    var $remainingPhotosCount, $addPhotoPanel, $paymentMethodsSelect, $ratesSelect;

    this.initVars = function(_maxPhotos) {
        maxPhotos = parseInt(_maxPhotos);
    };

    this.initServerElements = function(_remainingPhotosCountId, _addPhotoPanelId, _paymentMethodsSelectId, _ratesSelectId) {
        $remainingPhotosCount = $('#' + _remainingPhotosCountId);
        $addPhotoPanel = $('#' + _addPhotoPanelId);
        $paymentMethodsSelect = $('#' + _paymentMethodsSelectId);
        $ratesSelect = $('#' + _ratesSelectId);
    };

    this.deleteImage = function($item, index) {
        if (!confirm('Eliminare la foto selezionata?')) return;

        $.ajax({
            type: "POST",
            url: "/BuySell/SubmitAdvertising.aspx/DeletePhoto",
            data: "{ \'position\': " + index + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $item.fadeOut('slow', function() {
                    $item.remove();
                });

                $remainingPhotosCount.html(msg.d);
                if (parseInt(msg.d) < maxPhotos) {
                    $addPhotoPanel.show();
                } else if (parseInt(msg.d) == maxPhotos) {
                    $("#buysell-gallery").hide();
                }
            }
        });
    };

    this.initPhotoGallery = function() {
        $("#buysell-gallery").sortable({
            placeholder: 'ui-state-highlight',
            update: function(e, ui) {
                order = [];
                $(this).children('li').each(function(idx, elm) {
                    order.push(elm.id.split('_')[1])
                });
                $.ajax({
                    type: "POST",
                    url: "/BuySell/SubmitAdvertising.aspx/ReorderPhotos",
                    data: "{ \'order\': " + JSON.stringify(order, null) + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) { }
                });
            }
        });

        $("#buysell-gallery > li").click(function(event) {
            var $item = $(this), $target = $(event.target);
            var index = $(this).attr('id').split('_')[1];
            var img = $(this).children('img:first');

            if ($target.is("a.ui-icon-trash")) {
                TENews.BuySell.deleteImage($item, index);
            }

            return false;
        });
    };

    this.initPaymentMethods = function() {
        $paymentMethodsSelect.change(function() {
            var id = parseInt($(this).val());
            if (id == 0) {
                $('#payment-method-notes').hide();
                return;
            }

            $.ajax({
                type: "POST",
                url: "/BuySell/SubmitAdvertising.aspx/GetPaymentMethodNotes",
                data: "{ \'paymentMethodId\': " + id + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $('#payment-method-notes').html(msg.d).show();
                }
            });
        });
    };

    this.initRates = function() {
        $ratesSelect.change(function() {
            var id = parseInt($(this).val());
            if (id == 0) {
                $('#rate-price').hide();
                return;
            }

            $.ajax({
                type: "POST",
                url: "/BuySell/SubmitAdvertising.aspx/GetRatePrice",
                data: "{ \'rateId\': " + id + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $('#rate-price').html("L'inserzione ha un costo di <strong>" + msg.d + " euro</strong>").show();
                }
            });
        });
    };

    this.insertViewCounter = function(id) {
        $.ajax({
            type: "POST",
            url: "/BuySell/ViewAdvertising.aspx/InsertViewCounter",
            data: '{ \'advertisingId\': ' + id + ' }',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });
    };
};
