var DragDrop = {};

//
//

DragDrop.isAuthenticated = function(){
    return __logged__ == 1 ? true : false;
}

DragDrop.Finalize = function(){
    var positions = DragDrop.getAllPositions();
    DragDrop.savePostitions(positions);
}

DragDrop.getAllPositions = function(){
    var positions = {
        'boxes':{
            'CENTER': {},
            'RIGHT' : {},
            'EXTENDED':{}
        }
    };
    $('#list1').find('.b_news').each(function(i, o){
        positions.boxes.CENTER[$(o).attr('title')] = i;
    });
    $('#list2').find('.b_news').each(function(i, o){
        positions.boxes.RIGHT[$(o).attr('title')] = i;
    });
    $('#list3').find('.b_news').each(function(i, o){
        positions.boxes.EXTENDED[$(o).attr('title')] = i;
    });

    return positions;
}

DragDrop.savePostitions = function(positions){
    if('undefined' == typeof positions){
        return;
    }
    
    try{
        jQuery.post(__url__, positions, function(data, textStatus, XMLHttpRequest){}, 'json');
        
    }catch(e){
        
    }
}

DragDrop.deleteBox = function(evt, elm){
    evt.preventDefault();
    if(!confirm('Are you sure?')){
        return;
    }
    var parent = $(elm).parents('.b_news');
    var code = parent.attr('title');
    //if(DragDrop.isAuthenticated()){
    DragDrop.deleteBoxForUser(elm, code, parent);
/*}else{
        DragDrop.deleteBoxForGuest(elm, code, parent);
    }*/
}

DragDrop.deleteBoxForGuest = function(elm, code, parent){
    try{
        // from cookie
        var categories = getCookie('components').split('/');
        categories = $.grep(categories, function(value) {
            return value != code;
        });
        setCookie('components', categories.join('/'), expirymonth, '/');
        // disable checkbox
        var expr = '#components_'+code;
        $(expr).attr('checked', false);

        $(parent).remove();
    }
    catch(e){
    //console.error(e)
    }
}

DragDrop.deleteBoxForUser = function(elm, code, parent){
    try{
        var params = {
            'code': code
        };
        jQuery.post(__url_remove_box__, params, function(data, textStatus, XMLHttpRequest){}, 'json');
        // disable checkbox
        var expr = '#components_'+code;
        $(expr).attr('checked', false);

        $(parent).remove();
    }catch(e){
    //console.error(e)
    }
}

DragDrop.openSettingsBox = function(evt, elm){
    $('.b_news_setting').each(function(i, o){
        DragDrop.cancelSettings(o);
    });

    var parent = $(elm).parents('.b_news');
    var code = parent.attr('title');
    var tpl = $('#edit-template .b_news_setting').clone();
    tpl.find('form').attr('id', 'settings-form');
    tpl.find('.code').val(code);
    
    if (-1 != $.inArray(code, __categories__)) {
        var sub_tpl = $('#edit-template .change-category').clone();
        sub_tpl.find('.current_category').val(code);
    } else {
        var sub_tpl = $('#edit-template .limit-records').clone();
    }

    tpl.find('.inner-block').append(sub_tpl);
    parent.find('.b_news_item').addClass('hidden');
    parent.append(tpl);

}

DragDrop.cancelSettings = function(elm) {
    var parent = $(elm).parents('.b_news');
    parent.find('.b_news_setting').remove();
    parent.find('.b_news_item').removeClass('hidden');
}

DragDrop.prevNews = function(elm){
    try{
        var ref = $(elm).parents('#news-in-picks-block');
        var index = 0;
        var items = ref.find('.news-fragment');
        items.each(function(i, o){
            var id = o.id;
            id = id.split('-');
            if(!$(o).hasClass('hidden')){
                $(o).addClass('hidden');
                index = i;
            }
        });

        var next_index = --index < 0 ? items.length -1 : index;
        $(items[next_index]).removeClass('hidden');
        ref.find('.current-number').text(next_index+1);// next_index + 1 => for human

    }catch(e){}
}

DragDrop.nextNews = function(elm){
    try{
        var ref =$(elm).parents('#news-in-picks-block');
        var index = 0;
        var items = ref.find('.news-fragment');
        items.each(function(i, o){
            var id = o.id;
            id = id.split('-');
            if(!$(o).hasClass('hidden')){
                $(o).addClass('hidden');
                index = i;
            }
        });

        var next_index = index++ >= items.length -1 ? 0 : index;
        $(items[next_index]).removeClass('hidden');
        ref.find('.current-number').text(next_index+1);// next_index + 1 => for human

    }catch(e){}
}

DragDrop.discoverFeeds = function(){
    var params = {
        'link': $('#rss_link').val()
    }
    jQuery.post(__url_discover_feed__, params, DragDrop.embedDiscoveredFeeds, 'json');
}

DragDrop.embedDiscoveredFeeds = function(reply, textStatus, XMLHttpRequest){
    if(reply.result){
        $('#discovered-feeds').html(reply.data);
    }
}

DragDrop.fetchRsses = function(){
    var rss = [];
    $('.rss').each(function(i, o){
        rss[rss.length++] = o.id;
    });

    $(rss).each(function(i, o){
        jQuery.post(__url_fetch_feeds__, {codes: $.toJSON(o)}, DragDrop.injectFeeds, 'json');
    });
}

DragDrop.injectFeeds = function(reply) {
    $(reply).each(function(i, rss){
        var key = '#'+rss.code;
        
        $(key).find('.b_news_item').html(rss.content);
    });
}

$(document).ready(function(){

    YUI().use('dd-constrain', 'dd-proxy', 'dd-drop', function(Y) {
        //Listen for all drag:drag events
        Y.DD.DDM.on('drag:drag', function(e) {
            //Get the last y point
            var y = e.target.lastXY[1];
            //is it greater than the lastY var?
            if (y < lastY) {
                //We are going up
                goingUp = true;
            } else {
                //We are going down.
                goingUp = false;
            }
            //Cache for next check
            lastY = y;
        });
        //Listen for all drag:start events
        Y.DD.DDM.on('drag:start', function(e) {
            //Get our drag object
            var drag = e.target;
            //Set some styles here
            drag.get('node').setStyle('opacity', '.25');
            drag.get('dragNode').set('innerHTML', drag.get('node').get('innerHTML'));
            drag.get('dragNode').setStyles({
                opacity: '.5',
                borderColor: drag.get('node').getStyle('borderColor'),
                backgroundColor: drag.get('node').getStyle('backgroundColor')
            });
        });
        //Listen for a drag:end events
        Y.DD.DDM.on('drag:end', function(e) {
            var drag = e.target;
            $("#list1").css("height","auto");
            $("#list2").css("height","auto");
            var list1 = $("#list1").height();
            var list2 = $("#list2").height();
            var first_news = $(".b_last_news").height();
            var height = (list1>=list2)?list1:list2;
            //alert(list1+"-"+list2+"="+height);
            $("#list1").css("height",height);
            $("#list2").css("height",height+first_news-50);
            $("#list3").css("height",height);
            //Put our styles back
            drag.get('node').setStyles({
                visibility: '',
                opacity: '1'
            });
        });

        //
        //  DROP EVENTS
        //

        //Listen for all drop:over events
        Y.DD.DDM.on('drop:over', function(e) {
            var drag = e.drag.get('node'),
            drop = e.drop.get('node');

            if(drop.get('parentNode').hasClass('b_page_right_content')){
                return;
            }

            //Are we dropping on a li node?
            if (drop.hasClass('b_news')){//get('tagName').toLowerCase() === 'div') {
                //Are we not going up?
                if (!goingUp) {
                    drop = drop.get('nextSibling');
                }
                //Add the node to this list
                e.drop.get('node').get('parentNode').insertBefore(drag, drop);
                //Resize this nodes shim, so we can drop on it later.
                e.drop.sizeShim();
            //DragDrop.Finalize();
            }
        });
        //Listen for all drag:drophit events
        Y.DD.DDM.on('drag:drophit', function(e) {
            var drop = e.drop.get('node'),
            drag = e.drag.get('node');

            var parent = drop.get('parentNode');

            //drop.appendChild(drag);
            if (!drop.contains(drag)) {
                // parent.insertBefore(drag, drop);
                drop.appendChild(drag);
            //DragDrop.Finalize();
            //drop.insertBefore(drag);
            }
        });

        Y.DD.DDM.on('drag:end', function(e) {
            DragDrop.Finalize();
        });

        //Static Vars
        var goingUp = false, lastY = 0;

        //Get the list of li's in the lists and make them draggable
        var lis = Y.Node.all('div.b_news');
        lis.each(function(v, k) {
            var dd = new Y.DD.Drag({
                node: v,
                target: {
                    padding: '0 0 0 20'
                }
            }).plug(Y.Plugin.DDProxy, {
                moveOnEnd: false
            })/*.plug(Y.Plugin.DDConstrained, {
            constrain2node: '#play'
        });*/
        });

        //Create simple targets for the 2 lists.
        var uls = Y.Node.all('.drop_block');
        uls.each(function(v, k) {
            var tar = new Y.DD.Drop({
                node: v
            });
        });

    });

    var height = Math.max($('#list1').height(), $('#list2').height());
    $("#list3").css("height",height);


    $('.b_toolse').bind('click', function(evt){
        var elm = evt.target;
        if($(elm).hasClass('delete_ico')){
            DragDrop.deleteBox(evt, elm);
        }

        if($(elm).hasClass('settings_ico')){
            DragDrop.openSettingsBox(evt, elm);
        }
    });

    $(document).bind('click', function(e){
        try{
            var elm = $(e.target);
            
            if(elm.hasClass('next-news') || elm.hasClass('next_ico') || elm.hasClass('slide_control_r')) {
                DragDrop.nextNews(elm);
            }

            if(elm.hasClass('prev-news') || elm.hasClass('back_ico') || elm.hasClass('slide_control_l')) {
                DragDrop.prevNews(elm);
            }

            if(elm.hasClass('discover-rss-feeds')){
                DragDrop.discoverFeeds();
            }
        }catch(e){}
    });

    $(document).bind('submit', function(e){
        $('#ajax-indicator').removeClass('hidden');
    });
    
    // prevent submission for "Enter" key
    $(document).bind('keypress', function(evt){
        switch(evt.keyCode){
            case 13:
                if($(evt.target).attr('id') == 'rss_link'){
                    evt.preventDefault();
                    DragDrop.discoverFeeds();
                }
                break;
        }
    });

    DragDrop.fetchRsses();

});
