﻿$(document).ready(function() {
    $('#change_mode_link').click(function(e) {

        if ($('#change_mode_link').attr("href") == "/Narrow") {
            $.cookie("mode", "Narrow");
            window.location = "http://most.ua/Narrow";
        }
        else {
            $.cookie("mode", "Wide");
            window.location = "http://most.ua/Wide";
        }
    });

    $('div.close_alert').click(function(e) {
        setTimeout(function() {
            var target = $('div#alert');
            target.animate({ 'marginRight': '-270px' }, 500);
        }, 10)
        e.preventDefault();
    });
});


mostWidgets = function() {
    this.init = function() {
        $('.widget').each(function() {
            var w = new mostWidget();
            w.init($(this).attr('id'));
        });
    };

    this.recalculateZIndex = function() {
        $('.widget').each(function(index) {
            $(this).css('z-index', 10000 - 100 * index);
            $(this).css('left', 0);
            $(this).css('top', 0);
        });
    };
    this.saveWidgetsPosition = function(cookieName) {
        var c1 = '';
        var c2 = '';
        var c3 = '';
        $('#column_1 .widget').each(function(index) {
            try {
                var name = $(this).attr('class').match(/widget_name_(\w*)/)[1];
                var id = $(this).attr('id').match(/^widget_(\d*)$/)[1];
                var w = "{'id':" + id + ", 'name':'" + name + "', 'index':" + index + "}";
                c1 += w + ",";
            } catch (err) { };
        });
        $('#column_2 .widget').each(function(index) {
            try {
                var name = $(this).attr('class').match(/widget_name_(\w*)/)[1];
                var id = $(this).attr('id').match(/^widget_(\d*)$/)[1];
                var w = "{'id':" + id + ", 'name':'" + name + "', 'index':" + index + "}";
                c2 += w + ",";
            } catch (err) { };
        });
        $('#column_3 .widget').each(function(index) {
            try {
                var name = $(this).attr('class').match(/widget_name_(\w*)/)[1];
                var id = $(this).attr('id').match(/^widget_(\d*)$/)[1];
                var w = "{'id':" + id + ", 'name':'" + name + "', 'index':" + index + "}";
                c3 += w + ",";
            } catch (err) { };
        });
        var cookieString = "{'column1':[" + c1.replace(/,$/, '') + "], 'column2':[" + c2.replace(/,$/, '') + "], column3:[" + c3.replace(/,$/, '') + "]}";
        if (isUserAuth) {
            $.get('/json/SaveWidgetsPosition?widgetsJSon=' + encodeURIComponent(cookieString));
        } else {
            $.cookie(cookieName, cookieString);
            ShowAlertMesage('Вы переместили блоки!');
        };
    };
};

ShowAlertMesage = function(message) {
    setTimeout(function() {
        var target = $('div#alert');
        (target.find('.alert_c strong')).html(message);
        target.animate({ 'marginRight': '0px' }, 500);
    }, 10)
};

mostWidget = function() {
    this.id = null;
    this.element = null;
    this.regions = {
        title: null,
        controls: null,
        header_custom_left: null,
        header_custom_right: null,
        content: null,
        settings: null,
        footer_custom_left: null,
        footer_custom_right: null
    };
    this.controls = {
        refresh: null,
        collapse: null,
        close: null,
        settings: null
    };
    this.events = {
        selectTabEvent: 'selectTab'
    };
    this.tabbed = false;
    this.tabs = null;

    this.init = function(id) {
        var el = $('#' + id);
        this.id = id;
        if (el.length == 0) return false;
        this.element = el[0];
        this.regions.title = el.find('.w_title')[0] || null;
        this.regions.controls = el.find('.w_controls')[0] || null;
        this.regions.header_custom_left = el.find('.w_header_custom.left')[0] || null;
        this.regions.header_custom_right = el.find('.w_header_custom.right')[0] || null;
        this.regions.content = el.find('.w_content')[0] || null;
        this.regions.settings = el.find('.w_settings')[0] || null;
        this.regions.footer_custom_left = el.find('.w_footer_custom.left')[0] || null;
        this.regions.footer_custom_right = el.find('.w_footer_custom.right')[0] || null;

        $('#' + id + ' .w_header *').mousedown(function(e) {
            e.stopPropagation();
        });

        this.tabbed = (el.find('.w_tabs').length != 0);
        if (this.tabbed) {
            this.tabs = new Array();
            var tabs = el.find('.w_tabs .w_tab');
            var tabsC = el.find('.w_tab_content');
            for (var i = 0; i < tabs.length; i++) {
                this.tabs.push({
                    tab: tabs.eq(i),
                    tabContent: tabsC.eq(i),
                    visible: false
                });
                tabs.eq(i).bind('click', { _this: this, index: i }, function(e) {
                    e.data._this.selectTab(e.data.index);
                });
            };
            //инициализация новостных табов при загрузке
            //this.selectTab(0);
        };
    };

    this.selectTab = function(index) {
        if (this.tabbed && index >= 0 && index < this.tabs.length) {
            for (var i = 0; i < this.tabs.length; i++) {
                this.tabs[i].visible = false;
                this.tabs[i].tab.removeClass('w_tab_active');
                this.tabs[i].tabContent.removeClass('w_tab_content_active');
            };
            this.tabs[index].visible = true;
            var more = this.tabs[index].tab.closest('.widget').find('.w_footer .w_more a');
            more.attr('href', this.tabs[index].tab.attr('_moreLink'));
            more.html(this.tabs[index].tab.attr('_moreText'));
            this.tabs[index].tab.addClass('w_tab_active');
            this.tabs[index].tabContent.addClass('w_tab_content_active');
        };
    };
};

var widgets;
$(function() {
	$('.png').each(function(){
		$(this).parent().pngFix();
	});
	
	widgets = new mostWidgets();
	widgets.init();
	widgets.recalculateZIndex();
	$('.widgets_container').sortable({
		connectWith: '.widgets_container',
		placeholder: 'widget_placeholder',
		handle: '.w_header',
		items: '.w_draggable',
		update: function(e, ui) {
			if (ui.sender == null) { //prevent double event firing on moving between columns
				widgets.saveWidgetsPosition('widgets_position');
			};
			widgets.recalculateZIndex();
		},
		start: function(e, ui) {
			ui.helper.css('z-index', '20000');
		}
	});
});