$(document).ready(function() {
        
    fwix.home.welcomeResize();
    $(window).resize(function(){
        fwix.home.welcomeResize();
    });
    fwix.comments.bindKeyPressEvents();

    // REQUEST SOURCE
    $("#request_source form input")
        .click(function() {
            $(this).addClass('selected');
            if($(this).val() == 'http://...')
                $(this).val('');
            else
                $(this).select('');
        }) 
        .blur(function() {
            if($(this).val() == '') {
                $(this).removeClass('selected');
                $(this).val('http://...');
            }
            else
                $(this).select('');
        })
        .keypress(function (e) {
            if(e.which == 13) {
                fwix.feed.source_recommendation_submit();
                return false;
            }
        });

    // Poll for new content
    setInterval(function() {
        if($('#feed').attr('filter_type') != 'top_stories')
            fwix.feed.update();
        fwix.feed.adjustTime();
    },30000); // 30 seconds
});

/* HOME
/ *******************************************************************************************/
fwix.home = {
    /*** fwix.home.welcomeClose ***/
    welcomeClose: function(status){
        $("#welcome").slideUp();
        if(status == 'logged_in')
            fwix.cookieSet('welcome_home_logged_in', true, 999999, 0, '/');
        else
            fwix.cookieSet('welcome_home_logged_out', true, 999999, 0, '/');
    },


    /*** fwix.home.welcomeResize ***/
    welcomeResize: function(){
        welcome_promo = $('#welcome');
        if(welcome_promo.length == 0)
            return;
        padding = welcome_promo.css('padding-left');
        padding = padding.substr(0,-2);
        promo_width = welcome_promo.width() - (2 * padding);
        cols = welcome_promo.find('ul');
        col_width = cols.width();
        total_col_width = 0;

        cols.each(function(){
            total_col_width += col_width;
            if(total_col_width > promo_width){
                $(this).hide();
            }else{
                $(this).show();
            }
        });

    }
}

/* FEED
/ *******************************************************************************************/
fwix.feed = {
    /*** fwix.feed.update ***/
    update: function() { 
        var ref = $('#feed'),
            page = parseFloat(ref.attr('page')),
            item_newest = ref.find('.item:first'),
            filter_type = ref.attr('filter_type'),
            filter_id = ref.attr('filter_id');
        if(page != 1) 
            return;

        time_newest = item_newest.find('.time_ago').attr('timestamp');

        if(filter_type == 'day') {
            date = new Date();
            year = date.getFullYear();
            month = parseFloat(date.getMonth())+1;
            d = date.getDate();

            today = year+'-'+(month < 10 ? '0'+month : month)+'-'+(d < 10 ? '0':'')+d;
            if(filter_id != today) {
                return;
            }
        }

        filter_qs = "";
        if(filter_type != null) {
            filter_qs += "&filter_type="+encodeURIComponent(filter_type);
            filter_qs += "&filter="+encodeURIComponent(filter_id);
        }
     	$.ajax({
       		type: "GET",
       		url: fwix.site_url+'/ajax/feed_updates.php',
            async: false,
            data: "geo_id="+fwix.geo_id+
                  filter_qs+
                  "&most_recent_ts="+encodeURIComponent(time_newest),
    		dataType: "json",
       		success: function(data) {
                
                if(!data.error && data.feed.length > 0) {
                    num_new = data.feed.length;
                    if (num_new > 1) {
                        update = 'updates!';
                        pronoun = 'them';
                    } else {
                        num_new = 'one';
                        update = 'update!';
                    }
                    link = '<a href="'+location.href+'" >Refresh</a> for '+num_new+' new '+update; 
                    $('.status').html(link);
                    if($('.status').css('display') == 'none')
                        $('.status').slideDown(500);
                }
       		}
     	});
    },

    /*** fwix.feed.paginate ***/
    paginate: function() { 
        var ref = $('#feed'),
            page_size = parseFloat(ref.attr('page_size')),
            page = parseFloat(ref.attr('page')) + 1,
            filter_type = ref.attr('filter_type'),
            filter_id = ref.attr('filter_id');
            
    	fwix.loadingShow();
     	$.ajax({
       		type: "GET",
       		url: fwix.site_url+'/internalapi/',
            data: "geo_id="+fwix.geo_id+
                  (filter_type != null ? "&filter_type="+encodeURIComponent(filter_type)+"&filter="+encodeURIComponent(filter_id) : '')+
                  "&page="+encodeURIComponent(page)+
                  "&page_size="+encodeURIComponent(page_size),
    		dataType: "json",
       		success: function(data) {

                if(data.feed.length > 0) {
                
                    ref.attr('page',page); //update the page number
                    ref.find('.item:last').removeClass('last'); //remove last class from last item
                
                    for (var i = 0 ; i < data.feed.length ; i++) {
                        var feed_item = data.feed[i];
                        fwix.feed.storyBuild(ref.find('.items')[0], feed_item, 'append');
                       
                        fwix.comments.surveyBuild(ref.find(".item[story_id='"+feed_item.storyid+"'] .comments ul")[0],feed_item);
                        for (var j = 0 ; j < feed_item.comments.length ; j++) {
                            var comm = feed_item.comments[j];
                            fwix.comments.build(ref.find(".item[story_id='"+feed_item.storyid+"'] .comments ul"),comm,'append');
                        }
                    }
                    ref.find('.item:last').addClass('last'); //add last class to last item
                }
                else {
                    ref.find('.paginate').addClass('empty');
                    ref.find('.paginate').html('There are no more stories for this topic.');
                }
    	        fwix.loadingHide();
       		}
     	});
    },

    /*** fwix.feed.storyBuild ***/
    storyBuild: function(ref, item, direction) { 
        article_href = fwix.geo_url+'/article/'+item.storyid+'/'+item.url_title;

        feed_item = document.createElement('div');
        feed_item.className = 'item';
        feed_item.setAttribute('story_id', item.storyid);

        story = document.createElement('div');
        story.className = 'story';
        feed_item.appendChild(story);

        //GRAPHIC
        if(item.image && (item.summary.length > 100 || item.noun == 'youtube')){
            graphic = document.createElement('span');
            graphic.className = 'graphic';
            story.appendChild(graphic);
            image_link = document.createElement('a');
            graphic.appendChild(image_link);
            image_link.href = article_href;
            image = document.createElement('img');
            image_link.appendChild(image);
            image.src = item.image;
            image.width = '100';
            image.alt = item.title; 
        }

        // TITLE
        title = document.createElement('h4');
        story.appendChild(title);
        title_link = document.createElement('a');
        title.appendChild(title_link);
        title_link.href = article_href;
        title_link.innerHTML = item.title;

        //SUMMARY
        summary = document.createElement('p');
        story.appendChild(summary);
        source_link = document.createElement('a');
        summary.appendChild(source_link);
        source_link.href = fwix.geo_url+'/source/'+encodeURIComponent(item.pretty);
        source_link.className = 'source';
        source_link.innerHTML = item.pretty;
        if(item.summary && item.summary.length > 50){
            if(item.image && item.summary.length > 250)
                summary_text = fwix.strTruncate(item.summary, 250-item.pretty.length, '...');
            else
                summary_text = fwix.strTruncate(item.summary, 190-item.pretty.length, '...');
            summary.appendChild(document.createTextNode(' - '+summary_text));
        }

        small = document.createElement('small');
        story.appendChild(small);

        //TIME AGO
        ts = new Date(item.print_time*1000);
        time_ago = document.createElement('a');
        small.appendChild(time_ago);
        time_ago.href = fwix.geo_url+'/day/'+ts.getFullYear()+'-'+(ts.getMonth()+1)+'-'+ts.getDate();
        time_ago.className = 'time_ago';
        time_ago.setAttribute('timestamp', item.print_time);
        time_ago.appendChild(document.createTextNode(item.interaction_type + ' '));
        time_wrap = document.createElement('span');
        time_ago.appendChild(time_wrap);
        time_wrap.className = 'time';
        time_wrap.innerHTML = fwix.timeAgo((item.print_time ? item.print_time : item.timestamp));
        small.appendChild(document.createTextNode(' - '));

        //COMMENT TOGGLE
        comment_toggle = document.createElement('a');
        small.appendChild(comment_toggle);
        comment_toggle.href = 'javascript:fwix.feed.commentsToggle(\''+item.storyid+'\');';
        comment_toggle.className = 'comment';
        comment_toggle.innerHTML = 'Comment';
        small.appendChild(document.createTextNode(' - '));

        //SURVEY TOGGLE
        survey_toggle = document.createElement('a');
        small.appendChild(survey_toggle);
        survey_toggle.href = 'javascript:fwix.feed.surveyToggle(\''+item.storyid+'\');';
        survey_toggle.className = 'poll';
        survey_toggle.innerHTML = 'Vote';
        small.appendChild(document.createTextNode(' - '));
        
        //SHARE BUTTON
        share_button = document.createElement('a');
        small.appendChild(share_button);
        share_button.href = 'javascript:fwix.story.share(\''+item.storyid+'\');';
        share_button.className = 'share';
        share_button.innerHTML = 'Share';
        
        //VIDEO BUTTON
        if(item.noun == 'youtube'){
            small.appendChild(document.createTextNode(' - '));
            video_button = document.createElement('a');
            small.appendChild(video_button);
            video_button.href = 'javascript:fwix.feed.insertVideo(\''+item.storyid+'\');';
            video_button.className = 'share';
            video_button.innerHTML = 'Play Video';
        }

        //MAP BUTTON
        if(fwix.logged_in){
            small.appendChild(document.createTextNode(' - '));
            map_button = document.createElement('a');
            small.appendChild(map_button);
            map_button.href = 'javascript:fwix.story.mapPopover(\''+item.storyid+'\')';
            map_button.className = 'share';
            map_button.innerHTML = 'Map';
        }

        if(fwix.admin){
            small.appendChild(document.createTextNode(' - '));
            admin_button = document.createElement('a');
            small.appendChild(admin_button);
            admin_button.style.color = 'red';
            admin_button.href = '#';
            admin_button.onclick = function(){fwix.admin.dropdown(item.storyid); return false};
            admin_button.innerHTML = 'X';

            drop_down = document.createElement('ul');
            small.appendChild(drop_down);
            drop_down.className = 'admin_dropdown';
            drop_down.id = 'admin_'+item.storyid;

            options = [{'name':'Remove Picture', 'type':'unpicture'},
                       {'name':'Unpublish', 'type':'unpublish'},
                       {'name':'Deactivate (remove from site)', 'type':'deactivate'}]

            for(i in options){
                li = document.createElement('li');
                drop_down.appendChild(li);
                drop_down_item = document.createElement('a');
                li.appendChild(drop_down_item);
                drop_down_item.href = 'javascript:fwix.admin.commandSubmit(\''+options[i].type+'\',\''+item.storyid+'\')';
                drop_down_item.innerHTML = options[i].name;
            }
        }

        clear = document.createElement('div');
        clear.className = 'clear';
        story.appendChild(clear);

        //COMMENTS
        comments = document.createElement('div');
        feed_item.appendChild(comments);
        comments.className = 'comments';
        comments.setAttribute('storyid', item.storyid);
        if(item.comments.length > 0 || item.show_survey)
            comments.className += ' visible';
        comments_list = document.createElement('ul');
        comments.appendChild(comments_list);

        //COMMENTS FORM
        comments_form = document.createElement('form');
        comments.appendChild(comments_form);
        comments_form.className = 'comment_form';
        
        textarea = document.createElement('textarea');
        comments_form.appendChild(textarea);
        textarea.innerHTML = 'Write a comment...';

        if(!fwix.logged_in){
            name_label = document.createElement('label');
            comments_form.appendChild(name_label);
            name_label.className = 'name';
            name_label.appendChild(document.createTextNode('Name: '));
            name_input = document.createElement('input');
            name_label.appendChild(name_input);
            name_input.type = "text";
            name_input.name = "name";
    
            email_label = document.createElement('label');
            comments_form.appendChild(email_label);
            email_label.className = 'email';
            email_label.appendChild(document.createTextNode('Email: '));
            email_input = document.createElement('input');
            email_label.appendChild(email_input);
            email_input.type = "text";
            email_input.name = "email";
        }

        clear = document.createElement('div');
        clear.className = 'clear';
        comments_form.appendChild(clear);

        account_data = document.createElement('p');
        account_data.className = 'account';
        comments_form.appendChild(account_data);

        if(fwix.logged_in){
            account_data.innerHTML = 'Signed in as '+fwix.user_name;
        }else{
            sign_in = document.createElement('a');
            account_data.appendChild(sign_in);
            sign_in.href = 'javascript:fwix.account.login();';
            sign_in.innerHTML = 'Sign in';
        }

        submit = document.createElement('p');
        comments_form.appendChild(submit);
        submit.className = 'submit';
        submit_button = document.createElement('a');
        submit.appendChild(submit_button);
        submit_button.href = "javascript:fwix.comments.submit('"+item.storyid+"');";
        submit_button.className = "button";
        submit_text = document.createElement('span');
        submit_button.appendChild(submit_text);
        submit_text.innerHTML = 'Post Comment';
        


        if(direction == 'append') 
            ref.appendChild(feed_item);
        else 
            ref.appendChild(feed_item, ref.firstChild);
        fwix.feed.storyBindEvents($(ref), item); 
    },

    /*** fwix.feed.storyBindEvents ***/
    storyBindEvents: function(ref, data){
        // Bind textarea event
        feed_item = ref.find(".item[story_id='"+data.storyid+"']");
        feed_item.find("textarea")
            .bind('focus', {data: data}, function(e){
                fwix.comments.focus(data.storyid);
            })
            .bind('blur', {data: data}, function(e){
                fwix.comments.blur(data.storyid);
            });
            
        // Bind name input event
        feed_item.find("input[name='name']")
            .bind('focus', {data: data}, function(e){
                fwix.comments.focusInput(data.storyid,'name');
            })
            .bind('blur', {data: data}, function(e){
                fwix.comments.blurInput(data.storyid, 'name');
            })
            .bind('keypress', {}, function(e){
                if(e.keyCode == 13){
                    fwix.comments.submit(data.storyid); 
                    return false;
                }        
            });

        // Bind email input event
        feed_item.find("input[name='email']")
            .bind('focus', {data: data}, function(e){
                fwix.comments.focusInput(data.storyid,'email');
            })
            .bind('blur', {data: data}, function(e){
                fwix.comments.blurInput(data.storyid,'email');
            })
            .bind('keypress', {}, function(e){
                if(e.keyCode == 13){
                    fwix.comments.submit(data.storyid); 
                    return false;
                }        
            });
    },

    /*** fwix.feed.adjustTime ***/
    adjustTime: function() { 
        var last_ta = '',
            lookback = 25,
            ts_limit = Number(new Date())/1000 - 60 * 60;
            published_recently_count = 0;

        $(".item").each(function() {
            ta_elem = $(this).find('.time_ago');
            ts = ta_elem.attr('timestamp');

            ta = fwix.timeAgo(ts);
            ta_elem.find('.time').html(ta);
        });
    },

    /*** fwix.feed.commentsToggle ***/
    commentsToggle: function(story_id) { 
        var story = $("#feed .item[story_id='"+story_id+"']");
        
        if(!story.find('.comments').hasClass('focused')) {
            fwix.comments.focus(story_id);
            story.find('.comments form textarea').focus();
        }
    },

    /*** fwix.feed.surveyToggle ***/
    surveyToggle: function(story_id){
        var comments = $(".comments[storyid='"+story_id+"']");

        if(comments.find('.poll').hasClass('visible')){
            comments.find('.poll').removeClass('visible');
            if(comments.find('li:not(.poll)').length == 0)
                comments.removeClass('visible');
        }else{
            comments.find('.poll').addClass('visible');
            comments.addClass('visible');
        }

    },
    
    /*** fwix.feed.source_recommendation_submit ***/
    source_recommendation_submit: function(){
        fwix.loadingShow();

        var url = $("#request_source input"),
            response = $("#request_source form");
        $.ajax({
            type: "GET",
            url: fwix.site_url+'/ajax/request_source_submit.php',
            data: "source="+encodeURIComponent(url.val())+
                  "&geo_id="+fwix.geo_id,
            dataType: "json",
            success: function(data){
                if(data.success != 1){
                    $("#request_source form").effect('shake', {distance:4, times: 2}, 75, function() {});
                    fwix.formResponse(response, 'error', data.error);
                }else{
                    fwix.formResponse(response, 'success', 'Thanks for the recommendation');
                }
                fwix.loadingHide(); 
            }
        });
    },

    /*** fwix.feed.insertVideo ***/
    insertVideo: function(story_id){
        story = $('.item[story_id="'+story_id+'"] .story');
        existing_vid = $('#vid_'+story_id);
        if (existing_vid.length > 0) {
            existing_vid.remove()
            story.find('.play').html('Play Video');
        } else {
            story.find('.play').html('Hide Video');
            story.find('.comments').hide();
            embed_code = '<div class="video" id="vid_'+story_id+'"><div class="carrot"></div><iframe frameborder=0 scrolling="no" src="'+fwix.site_url+'/video.php?hide_header=true&link_id='+fwix.geo_id+'_'+story_id+'&autoplay=1"';
            embed_code += ' style="height: 250px; width: 380px; overflow: hidden; padding: 0px;"></iframe></div>';
            story.after(embed_code);
        }
    }
};
