jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
    validLabels = /^(data|css):/,
    attr = {
        method: matchParams[0].match(validLabels) ? matchParams[0].split(':')[0] : 'attr',
        property: matchParams.shift().replace(validLabels,'')
    },
    regexFlags = 'ig',
    regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

var obj;
var text_desc = false;
var assignment_referrer_anchor = false;
var announcement_widget_id = false;
var last_comment = 0;
var close_menu_element;
function getTodo(val){
    //		$('#course_list').attr('disabled', 'disabled')
    $.post('/fb/widget/todoload', {
        'id': val
    }, 
    function(data){
        $('#next_week_assistments').html('');
        if(data['future'].lenght > 0){
        for(key in data['nextweek']){
            item = data['nextweek'][key]
            div = $('<div>');
            $(div).addClass('todo');
            $(div).attr('rel', item['id'])
            span = $('<span>');				
            a1 = $('<a>');
            a1.html(item['due_date'] + ': ' + item['name']);
            $(a1).attr('href', item['link'])
            $(a1).addClass('nav');
            $(span).append(a1);
            if(item['submit_id'] == null){					
                $(span).append($('<br>'))
                a = $('<a>');
                a.addClass('submit_assignment_widget');
                a.attr('rel', item['group_id']);
                a.text('Submit');
                $(span).append(a);
            }else{
                $(span).css('text-decoration', 'line-through');
            }
            $(div).append(span)
            $('#next_week_assistments').append(div)
        }
        }else{
            $('#next_week_assistments').html('<span style="color:black">No Assignments Found!</span>');
        }
        $('#future_assistments').html('');
        if(data['future'].lenght > 0){
        for(key in data['future']){
            item = data['future'][key]
            div = $('<div>');
            $(div).addClass('todo');
            $(div).attr('rel', item['id'])				
            span = $('<span>');				
            a1 = $('<a>');
            a1.html(item['due_date'] + ': ' + item['name']);
            $(a1).attr('href', item['link']);
            $(a1).addClass('nav');
            $(span).append(a1);
            if(item['submit_id'] == null){					
                $(span).append($('<br>'))
                a = $('<a>');
                a.addClass('submit_assignment_widget');
                a.attr('rel', item['group_id']);
                a.text('Submit');
                $(span).append(a);
            }else{
                $(span).css('text-decoration', 'line-through');
            }
            $(div).append(span)
            $('#future_assistments').append(div)
        }        			
        }
        else{
            $('#future_assistments').html('<span style="color:black">No Assignments Found!</span>');
        }
        $('#course_list').removeAttr('disabled')
    }, 
    'json')
}

function openVideoStream(id1, name) {
    popup_fb3 = new popUp();
    popup_fb3.containerStyle = {
        display: 'none',
        zIndex:'4',
        top:'0px',
        left: '0px',
        position:'fixed',
        margin: '0px',
        boxShadow:'0 0 1px #fff',
        borderRadius:'8px',
        opacity: 1,
        backgroundColor:'#fff',
        overflow: 'hidden',
        border: '10px solid rgba(82, 82, 82, 0.7)'
    };
    popup_fb3.onclose = function(){
        stopCheckStream();
        endLoggingStream();    
        if ($('#signInButt').attr('name')=="signOut"){
             checkSignOut('signout');
        }
        $('#stream_to_delete').remove();
        popup_fb3.clearMe();
    };
    popup_fb3.load('/fb/livevideos/viewlivestream/sid/'+id1,{
        width: '500px',
        title: name,
        postClear: true,
        buttons:[
        {
            //value:'Return to Live Video Streams',
            value:'Close',
            clickFunction:function(){
                popup_fb3.hide();
                stopCheckStream();
                endLoggingStream();    
            }
        }
        ]
    })
    return false;
}

$(function(){
    $(document).ready(function(){
        if (typeof(popup_fb)=='undefined') popup_fb = new popUp();
        if (typeof(popup_attach)=='undefined') popup_attach = new popUp();
    })
    function addWidget(){
        id1=$(this).attr('rel');
        $(this).attr('disabled', 'disabled');
        $.post('/fb/widget/loadwidget',{
            'id':id1
        }, function(data){
            if(data['colspan'] == 1){
                $('.column:first').append(data['html']);
            }else{
                $('.column_right:first').append(data['html']);
            }
            wrapper = $('.hidenwidget[rel='+id1+']').parent();
            $('.hidenwidget[rel='+id1+']').remove();
            count=$('.hidenwidget').length;
            $('#addwidget').html('Add widget('+count.toString()+')')
            if(count == 0){
                $('#addwidget').hide();
            }
            if(count==0){
                $(wrapper).html('No hidden widgets');
            }
            doSort();
            viewWidgetsSort();
        }, 'json')
    }


    $( ".ui-icon-minusthick, .ui-icon-plusthick" ).live('click',function() {                
        $( this ).toggleClass( "ui-icon-minusthick" ).toggleClass( "ui-icon-plusthick" );
        $( this ).parents( ".portlet:first" ).find( ".portlet-content" ).toggle('slow',viewWidgetsSort);
                        
    })  
		
    $('.addwidgetbutton').live('click',addWidget);	
	
	
    $('input[type="text"]').live('keydown', function(e){
        if(13==e.keyCode){
            return false;
        }
    })
	
    $('#event_date').live('mouseover',
        function(){
            $(this).datetimepicker({
                dateFormat: 'yy-mm-dd',
                stepMinute: 10
            })
        }
        );

    $('#share_text').live('focus', function(){
        if($(this).text() == "What's on your mind?"){
            $(this).text('');
        }
    }).blur(function(){
        if($(this).text() == ''){
            $(this).text("What's on your mind?");
        }
    })
    
    $('.icon_album').live('click', function(){
        //        $('#icon_row').hide();
        $('#photo_row').show();
        $('#video_row').hide();
        $('#events_row').hide();
        $('#links_row').hide();
        $('#share_btn1').hide();         
        return false;
    })
    
    $('.icon_video').live('click', function(){
        //        $('#icon_row').hide();
        $('#photo_row').hide();
        $('#video_row').show();
        $('#events_row').hide();
        $('#links_row').hide();    
        $('#share_btn1').hide();                
        return false;
    })
    
    $('.icon_events').live('click', function(){
        //        $('#icon_row').hide();
        $('#photo_row').hide();
        $('#video_row').hide();
        $('#events_row').show();
        $('#links_row').hide();        
        $('#share_btn1').hide();                
        return false;
    })
    
    $('.icon_link').live('click', function(){
        //        $('#icon_row').hide();
        $('#photo_row').hide();
        $('#video_row').hide();
        $('#events_row').hide();		
        $('#links_row').show();     
        $('#share_btn1').hide();                
        return false;
    })
    
    $('.RemoveLink').live('click', function(){        
        $('#photo_row').hide();
        $('#events_row').hide();
        $('#links_row').hide();
        $('#video_row').hide();
        $('#share_btn1').show();                
    })
    
    function showErrorDialog(){
        popup_fb.load('<div style="color:#333333; font-size:11px">Please enter some text or attach an image!</div>',{
            title: 'Error',
            buttons:[{
                value:'Okay',
                clickFunction:function(){
                    popup_fb.hide();
                    $('#button_share_status').removeClass('progress_bar_f_share');
                }
            }]
        })
    }
    
    $('#whatsnew_form').live('mouseover',function(){
        
        $(this).ajaxForm(
        {
            success: function(data){
                stop_progress_bar('button_share_status');
                $('#whatsnew_form input[type!=submit][name!="id"], select, textarea').val('');
                $('#upload_file').replaceWith('<input type="file" name="upload_file" style="overflow:hidden;" id="upload_file" class="upload_file"/>');
                $('#video_file').replaceWith('<input type="file" name="video_file" id="video_file" class="video_file" style="overflow:hidden;" />');
                $('#whatsnew_list').find('div:first').before(data);
            },
            beforeSubmit: function(arr, $form, options){               
                share_text = $('#share_text').val();
                link = $('#share_link').val();
                file = $('#upload_file').val();
                file2 = $('#video_file').val();
                event_text = $('#event_title').val();
                //if ($('#share_text').val() == '' || $('#share_text').val() == "What's on your mind?") {
                if((share_text == "What's on your mind?" || share_text == '') && file == '' && file2 == '' && link == 'http://' && event_text == ''){
                    popup_fb.load('<div style="color:#333333; font-size:11px">Please enter some text!</div>',{
                        title: 'Error',
                        buttons:[{
                            value:'Okay',
                            clickFunction:function(){
                                popup_fb.hide();
                                return false;
                            }
                        }]
                    })
                    return false;
                }
                start_progress_bar('button_share_status','progress_bar_f_share');
                              
                if((share_text == "What's on your mind?" || share_text == '') && file == '' && file2 == '' && link == 'http://' && event_text == ''){
                    showErrorDialog();
                    return false;
                }
                $('.RemoveLink').click();
                $('#link_share_image').show();
                $('#link_share_btn').hide(); 
                $('#event_share_image').show();
                $('#event_share_btn').hide();
                $('#video_share_image').show();
                $('#video_share_btn').hide();
                $('#share_image').show();
                $('#share_btn_end').hide();
            }        
        });
    }

    );
        
    $('#studyhall_comments_form').live('click',function(){
        $(this).ajaxForm(
        {
            success: function(data){                
                $('#studyhall_comments_form input[type!=submit][name!="id"], select, textarea').val('');
                $('#upload_file').replaceWith('<input type="file" class="upload_file" id="upload_file" style="overflow:hidden;" name="upload_file">');
                $('.RemoveLink').click();
            },
            beforeSubmit: function(arr, $form, options){                
                var share = $('#share_text').val();
                
                var link = $('#share_link').val();
                var file = $('#upload_file').val();
                var file2 = $('#video_file').val();
                var event = $('#event_title').val();                
                if((share == "What's on your mind?" || share == '') && file == '' && file2 == '' && link == 'http://' && event == ''){
                    showErrorDialog();
                    return false;
                }
            }        
        }    
        )
    }

    );
    
    $('.whatsnew_event').live('mouseover', function(){
        $(this).find('.close_icon').show();
    })
    $('.whatsnew_event').live('mouseout', function(){
        $(this).find('.close_icon').hide();
    })
    
    $('.close_icon').live('click', function(){                
        var menu = $(this).parent().find('.close_menu');
        close_menu_element = menu;
        var display = menu.css('display');
        $('.close_menu').hide();
        var position = $(this).position();   
        menu.css('left', position.left - 185);
        if(display == 'none'){
            menu.show();
        }
        $('.close-wrapper').height($('html').height() + 'px');
        $('.close-wrapper').show();
    })
    $('.close-wrapper').live('click', function(){
       $('.close-wrapper').hide();
       close_menu_element.hide();
       close_menu_element = null;
    });
    
    $('.close_menu_item').live('click', function(){
        $(this).parents('.close_menu').hide();
        url = $(this).attr('rel');
        obj = $(this).parents('.whatsnew_event');
        obj.html("<div class='progress_bar_no'></div>");
        uid = obj.attr('rel');        
        $.get(url, {}, function(data){
            $('#whatsnew_list').html(data);
        }, 'html');
    });
    
    $('#hidden_streams').live('click', function(){
		
        gid = $('#whatsnew').attr('rel');
        popup_fb.load('/fb/whatsnew/gethide?id='+gid,{
            title: 'Hidden Streams',
            width: '400px',
            buttons:[{
                value: 'Close',
                clickFunction: function() {
                    popup_fb.hide();
                }
            }]
        })
    })
    
	
    $('.restore_events').live('click',function(){            
        id1 = $(this).attr('rel');
        gid = $('#whatsnew').attr('rel');
        $.post('/fb/whatsnew/showevents', {
            'uid':id1, 
            'id':gid
        }, function(data){
            $('#whatsnew_list').html(data);                
        }, 'html');
        if($('.restore_events').length == 1 && $('.restore_events_by_type').length == 0){
            $(this).parents('table').replaceWith('<b>No hidden streams at this time.</b>');
        }
        $(this).parents('tr').remove();		
    })
    
    $('.restore_events_by_type').live('click',function(){            
        id1 = $(this).attr('rel');
        gid = $('#whatsnew').attr('rel');
        $.post('/fb/whatsnew/showeventsbytype', {
            'uid':id1, 
            'id':gid
        }, function(data){
            $('#whatsnew_list').html(data);                
        }, 'html');
        if($('.restore_events').length == 0 && $('.restore_events_by_type').length == 1){
            $(this).parents('table').replaceWith('<b>No hidden streams at this time.</b>');
        }
        $(this).parents('tr').remove();		
    })
	
    $('#upload_file').live('change' ,function(){        
        if (!checkIE()) {
            var files = document.getElementById("upload_file").files;
            var message = '';
            if(!checkIE()){
            for (var i = 0; i < files.length; i ++) 
            {
                file = files[i];
                var type = file.fileType != null ? file.fileType : file.type;
                var size = file.fileSize != null ? file.fileSize : file.size;
                if (max_file_size < size) {
                    message = 'Maximum allowed file size 10M. ';
                }

                if (jQuery.inArray(type, arrPhotoTypes) == -1) {
                    message += 'Illegal photo format. Allowed ' + strPhoto;
                }
                if (message != '') {
                    $('#upload_file').val('');
                    popUpPhoto = new popUp();
                    popUpPhoto.load('<div>' + message + '</div>', {
                        title: 'Error',
                        buttons:[{
                            value:'Okay',
                            clickFunction:function(){
                                popUpPhoto.hide();
                            }
                        }]
                    })

                }

            }
            }
        }
        if($(this).val() != ''){
        $('#share_image').hide();
        $('#share_btn_end').show();
        }
    })
    
    $('#video_file').live('change' ,function(){
        if (!checkIE()) {
            var files = document.getElementById("video_file").files;
            var message = '';
            for (var i = 0; i < files.length; i ++) 
            {
                file = files[i];
                var type = file.fileType != null ? file.fileType : file.type;
                var size = file.fileSize != null ? file.fileSize : file.size;
                if (max_file_size < size) {
                    message = 'Maximum allowed file size 10M. ';
                }
                if (jQuery.inArray(type, arrVideoTypes) == -1) {
                    message += 'Illegal video format. Allowed ' + strVideo;
                }
                if (message != '') {
                    $('#video_file').val('');
                    popUpVideo = new popUp();
                    popUpVideo.load('<div>' + message + '</div>', {
                        title: 'Error',
                        buttons:[{
                            value:'Okay',
                            clickFunction:function(){
                                popUpVideo.hide();
                            }
                        }]
                    })

                }

            }
        }
        $('#video_share_image').hide();
        $('#video_share_btn').show();
    })
        
    $('#share_link').live('keyup', function(){
        var link_val = $('#share_link').val();
        if( link_val.match(/^(https?:\/\/)?([\w\.]+)\.([a-z]{2,6}\.?)(\/[\w\.]*)*\/?$/) == null ) {
            $('#link_share_image').show();
            $('#link_share_btn').hide(); 
        } else {
            $('#link_share_image').hide();
            $('#link_share_btn').show();        
        }
    })
    
    $('#event_title').live('keypress', function(){
        $('#event_share_image').hide();
        $('#event_share_btn').show();
    })
    
    $('.small_image').live('click', function(){
        popup_fb.load('<img src="'+$(this).attr('src')+'" />', {
            title: 'Image',
            width: 'auto',
            height: 'auto',
            buttons:[{
                value:'Okay',
                clickFunction:function(){
                    popup_fb.hide()
                }
            }]
        })
    })
    
    $('.show_comment').live('click',function(){
        $(this).parent().find('.comment_form').toggle();
        return false;
    })        
    
    $('.text_comment').live('focus', function(){
        if($(this).text() == "Write a comment..."){
            $(this).text('');
        }
    }).blur(function(){
        if($(this).text() == ''){
            $(this).text("Write a comment...");
        }
    })
    $('.text_comment').live('keypress', function(e){
        var key_code = (e.keyCode ? e.keyCode : e.which);
        if(key_code == 13){
            form = $(this).parents('.comment_form');
            edit_flag = $(this).attr('edit');
            var rand = 111111 + Math.floor(Math.random()*999999);
            event_id = $(this).attr('rel');
            //form.before("<div id='comm_" + rand + "'><center><div class='progress_bar_no'></div></center></div></div>");
            text = $(this).val();            
            $(this).val('');
            gid = $('input[name=id]').val();
            $.post('/fb/whatsnew/addcomment', {
                'text':text, 
                'id': gid, 
                'event_id':event_id
            }, function(data){                
                //$('#comm_' + rand).html(data);				
                form.before(data)
                if(edit_flag){
                    $.post('/fb/whatsnew/deletecomment', {
                        'id':last_comment
                    })
                    $('.whatsnew_event .text_comment').removeAttr('edit');
                }
                last_comment = form.parents('.whatsnew_event .comment:last').attr('rel');
            }, 'html')
            return false;
        }
    })
    $('.close_comment_icon').live('click', function(){
        obj = $(this).parents('.comment');        
        id1 = obj.attr('rel');
        if(id1 != last_comment){
            obj.html("<div class='progress_bar_no'></div>");
            $.post('/fb/whatsnew/deletecomment', {
                'id':id1
            }, function(data){
                if(data != '0'){
                    obj.remove();
                }
            },'text')
        }else{
            obj.hide();
            text_val = $(obj).find('.comment_val:first').html();            
            $(obj).parents('.comm_z').find('.text_comment').val(text_val);
            $(obj).parents('.comm_z').find('.text_comment').attr('edit', 1);
        }
    })
    
    $('#new_annoncement').live('click', function(){
        if ($('#new_annoncement').hasClass('multiply')) {
            var has_class = '/multiply/1';
        } else {
            var has_class = '';
        }
		
		
        popup_fb.load('/fb/announcements/addform' + has_class, {
            title: 'Add Announcement',
            width: '425px',
            buttons:[
            {
                value:'Create Announcement',
                clickFunction:function(){
                    $('#announcements_form').ajaxSubmit({
                        type: "POST",
                        dataType: "text",
                        success: function (data) {
                            try{
                                obj = $.parseJSON(data)
                                $('#errors').html('');
                                if(obj['date']){
                                    $('#errors').html($('#errors').html() + 'Date can not be empty<br />');
                                }
                                if(obj['desc']){
                                    $('#errors').html($('#errors').html() + 'Description can not be empty<br />');
                                }
                            } catch(e){
                                $('#start_announcements_zone').after(data);
                                if ($('.announcement').size() > 0) {
                                    $('#start_announcements_zone').hide();
                                } else {
                                    $('#start_announcements_zone').show();
                                }
                                countAnnoncemnts();
                                popup_fb.hide();
                                $.ajax({
                                    type: 'POST',
                                    url: '/fb/announcements/update-widget-announcement',
                                    data: {
                                        part_data:true
                                    },
                                    success: function(responceText){
                                        $("#widget_announcement").html(responceText);
                                    }
                                });
                                    
                            }								
                        },
                        error: function () 
                        {
                            alert('error')
                        } 
                    });
					                        
                } 
            },
            {
                value: 'Cancel',
                clickFunction: function() {
                    popup_fb.hide();
                }
            }
            ]
        })
    })

    $('.attached-forum-comment').live('click', function(){
       var file_id = $(this).attr('rel');
       var popup_attach_comment = new popUp();
       popup_attach_comment.load('/fb/forum/attach/id/'+file_id,{
            title: 'Comment Attachments',
            buttons:[{
                value: 'Close',
                clickFunction: function() {
                    popup_attach_comment.hide();
                }
            }]
       });
    });
    
    $('.view_forum_attachments').live('click', function(){
        var question_id = $(this).attr('rel');
        popup_fb.load('/fb/forum/attachments/id/'+question_id,{
            width: 500,
            title: 'Forum Attachments',
            buttons:[{
                value: 'Close',
                clickFunction: function() {
                    popup_fb.showButtons(1);
                    popup_fb.showButtons(2);
                    popup_fb.hide();
                    if (announcement_widget_id) {
                        if (announcement_widget_id == 'archive'  ) {
                            $('.view_announcement_archive').click();
                        }
                        $('.view_announcement[rel="' + announcement_widget_id + '"]').click();
                        announcement_widget_id = false;
                    }
                }
            },
            {
                value:'Return to attachments',
                clickFunction:function(){
                    $('#image').hide();
                    $('#attach').show();
                    popup_fb.hideButtons(2);
                    popup_fb.showButtons(1);
                }
            }],
            callback: function(){
                popup_fb.hideButtons(2);
            }
        });
    });
    
    $('.view_attachments').live('click', function(){
        id1 = $(this).parents('.announcement').attr('rel');
        if (typeof(id1) == "undefined") {
            id1 = $(this).attr('rel');
        }
        popup_fb.load('/fb/announcements/attachments/id/'+id1,{
            width: 500,
            title: 'Announcement Attachments',
            postClear: true,
            buttons:[{
                value: 'Close',
                clickFunction: function() {
                    popup_fb.showButtons(1);
                    popup_fb.showButtons(2);
                    popup_fb.hide();
                    if (announcement_widget_id) {
                        if (announcement_widget_id == 'archive'  ) {
                            $('.view_announcement_archive').click();
                        }
                        $('.view_announcement[rel="' + announcement_widget_id + '"]').click();
                        announcement_widget_id = false;
                    }
                }
            },
            {
                value:'Return to attachments',
                clickFunction:function(){
                    $('#image').hide();
                    $('#attach').show();
                    popup_fb.hideButtons(2);
                    popup_fb.showButtons(1);
                }
            }],
            callback: function(){
                popup_fb.hideButtons(2);
            }
        })		
        return false;
    })
	
   	
    $('.view_announcement_archive').live('click', function(){
		
        popup_fb.load('/fb/announcements/archive', {
            title: 'Announcements Archive',
            buttons:[{
                value: 'Close',
                clickFunction: function() {
                    popup_fb.hide();
                }
            }]
        })
    //        $('#dialog').load('/fb/announcements/archive', function(){
    //            $('#dialog').dialog({
    //                position:['center','center'],
    //                width: 500,
    //                modal: true,
    //                title: 'Announcements Archive',
    //                buttons:{
    //                    'Close':function(){
    //                        $( this ).dialog( "destroy");
    //                    }
    //                }
    //            });
    //        });
    });
    $('.view_announcement').live('click', function() {		
        var announcement_id = $(this).attr('rel');
        popup_fb.load('/fb/announcements/single/id/' + announcement_id,{
            width: '500px',
            title: 'Announcement Detail',
            pastClear: true,
            buttons:[
            {
                value:'I have read this',
                clickFunction:function(){
                    $.post('/fb/announcements/read', {
                        'id':announcement_id
                    }, function(data){
                        $('.announcement_row[rel=' + announcement_id + ']').parent().remove();
                    },'text');
                    popup_fb.hide();
                }
            },
            {
                value:'Close',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })
    });
        
	
    $('.clear_announcement').live('click', function(){
        id1 = $(this).parents('.announcement').attr('rel');
		
        popup_fb.load('<div style="color:#333333; font-size:11px">This action cannot be undone. This will remove this Announcement from the system and from visibility by all group members. Do you wish to continue?</div>',{
            title: 'Clear Announcement',
            width: 500,
            buttons:[
            {
                value:'Clear Announcement',
                clickFunction:function(){
                    $('.announcement[rel=' + id1 + ']').html("<div class='progress_bar_no'></div>");
                    $.post('/fb/announcements/delete/', {
                        'id':id1
                    }, function(data){
                        if(data != 0){
                            $('.announcement[rel=' + id1 + ']').remove();
                            if ($('.announcement').size() > 0) {
                                $('#start_announcements_zone').hide();
                            } else {
                                $('#start_announcements_zone').show();
                            }
                            countAnnoncemnts();
                        }
                    },'text')
                    popup_fb.hide();
                    $.ajax({
                        type: 'POST',
                        url: '/fb/announcements/update-widget-announcement',
                        data: {
                            part_data:true
                        },
                        success: function(responceText){
                            $("#widget_announcement").html(responceText);
                        }
                    });
                }
            },
            {
                value: 'Cancel',
                clickFunction: function() {
                    popup_fb.hide();
                }
            }
            ]
        })
        return false;	
    })	
    
    $('.edit_announcement').live('click', function(){
        var id1 = $(this).parents('.announcement').attr('rel');
        var group_id = $('#group_name_' + id1).attr('rel');
        if (group_id) {
            var strParam = '/gid/' + group_id;
        } else {
            var strParam = '';
        }
		
		
        popup_fb.load('/fb/announcements/editform/id/'+id1 + strParam,{
            title: 'Modify Announcement',
            width: "425px",
            buttons:[
            {
                value: 'Save Announcement',
                clickFunction:function(){
                    $('#announcements_form').ajaxSubmit({
                        type: "POST",
                        dataType: "text",
                        success: function (data) {								
                            try{
                                obj = $.parseJSON(data)
                                $('#errors').html('');
                                if(obj['date']){
                                    $('#errors').html($('#errors').html() + 'Date can not be empty<br />');
                                }
                                if(obj['desc']){
                                    $('#errors').html($('#errors').html() + 'Description can not be empty<br />');
                                }
                            } catch(e){													
                                $('.announcement[rel=' + id1 + ']').replaceWith(data);
                                popup_fb.hide();
                                $.ajax({
                                    type: 'POST',
                                    url: '/fb/announcements/update-widget-announcement',
                                    data: {
                                        part_data:true
                                    },
                                    success: function(responceText){
                                        $("#widget_announcement").html(responceText);
                                    }
                                });
                            }								
                        },
                        error: function () 
                        {
                            alert('error')
                        } 
                    });
                } 
            },
            {
                value: 'Cancel',
                clickFunction: function() {
                    popup_fb.hide();
                }
            }
            ]
        })
        return false;
    })

	
    $('.read_announcement').live('click', function(){
        id1 = $(this).parents('.announcement').attr('rel');
        tagA = $(this);
        $.post('/fb/announcements/read', {
            'id': id1
        }, function(data){
            $(tagA).replaceWith('Read it');
        }, 'json')
        return false;
    })
	
	$('.readThis').live('change', function(){
        id1 = $(this).parents('.announcement').attr('rel');
        tagA = $(this).parents('.announcement');
        $.post('/fb/announcements/read', {
            'id': id1
        }, function(data){
            $(tagA).remove();
        }, 'json')
        return false;
    })
	
    $('.reply_announcement').live('click', function(){
        id1 = $(this).parents('.announcement').attr('rel');
        popup_fb.load('/fb/announcements/replyform', {
            width: 575,
            title: 'Reply to an Announcement',
            params: {
                'announcemene_id': id1
            },
            buttons:[{
                value:'Send Reply',
                clickFunction:function(){
                    if ($('#text').val() == '') {
                        popUpEmpty = new popUp();
                        popUpEmpty.load('<div>Enter text in reply</div>',{
                            width: 575,
                            title: 'Error',
                            buttons:[{
                                
                                value:'Cancel',
                                clickFunction:function(){
                                    popUpEmpty.hide();
                                }
                                    
                            }]
                        });
                    } else {
                        $('#reply_form').ajaxSubmit({
                            type: "POST",
                            dataType: "text",
                            success:function(data){
                                try{
                                    obj = $.parseJSON(data)
                                    $('#errors').html('');
                                    if(obj['date']){
                                        $('#errors').html($('#errors').html() + 'Date can not be empty<br />');
                                    }
                                    if(obj['desc']){
                                        $('#errors').html($('#errors').html() + 'Description can not be empty<br />');
                                    }
                                } catch(e){
									if($('.announcement[rel=' + id1 + ']').hasClass('announcements')){
										$('.announcement[rel=' + id1 + ']').remove();
									}else{
										$('.announcement[rel=' + id1 + ']').replaceWith(data);
									}
                                    popup_fb.hide();
                                }
                            }
                        });
                    }
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb.hide();
                    if (announcement_widget_id) {
                        $('.view_announcement[rel="' + announcement_widget_id + '"]').click();
                        announcement_widget_id = false;
                    }
                }
            }
            ],
            callback:function(){
                $('#aid').val(id1);
            }
        })
        return false;
    })

		
    $('.view_own_replies').live('click', function(){
        id1 = $(this).parents('.announcement').attr('rel');
        popup_fb.load('/fb/announcements/viewownreply/id/' + id1, {
            width: 500,
            title: 'Announcement Replies',
            buttons:[{
                value:'Return to Announcements',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }]
        })
        return false;
    })
	
    $('.view_replies').live('click', function(){
        id1 = $(this).parents('.announcement').attr('rel');
        popup_fb.load('/fb/announcements/viewreply/id/' + id1, {
            width: 500,
            title: 'Announcement Replies',
            buttons:[{
                value:'Return to Announcements',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }]
        })        
        return false;
    })
	
    $('.view_rsvp').live('click', function(){
        id1 = $(this).parents('.announcement').attr('rel');
		
        popup_fb.load('/fb/announcements/rsvp/id/' + id1, {
            width: 500,
            title: 'RSVP Report',
            buttons:[
            {
                value: 'Return to Announcements',
                clickFunction: function() {
                    popup_fb.hide();
                }
            }
            ]
        })
		       
        return false;
    })
	
    function countAnnoncemnts(){
        var annCount = $('.announcement').size()
        val = 'Displaying ' + annCount + ' Announcement';
        if(annCount != 1){
            val += 's'
        }
        $('#count_annoncements').text(val)
    }
	
    function countAssignments(){
        annCount = $('.assignment').size()
        val = 'Displaying ' + annCount + ' Assignment';
        if(annCount != 1){
            val += 's'
        }
        $('#count_assignments').text(val)
    }	
	
    $('#clear_past_annoncements').live('click', function(){
        gid = $('#anonsments').attr('rel');
        href = $(this).attr('href');
        popup_fb.load('<div style="font-size: 11px; color: #333333">This action cannot be undone. This will remove all Announcements prior to today\'s date from the system and from visibility by all group members. Do you wish to continue?</div>',{
            title: 'Clear All Past Announcements',
            width: '500px',
            buttons:[{
                value:'Clear All Past Announcements',
                clickFunction:function(){
                    $.post('/fb/announcements/clearpast', {
                        'gid':gid
                    }, function(){
                        popup_fb.hide();
                        countAnnoncemnts();
                        location.href = '#announcements/index/'+Math.random();
                    })
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })
		
        return false;
    })
	
    //----------------
    $('#new_assignment').live('click', function(){
        popup_fb.load('/fb/assignments/addform',{
            title: 'Add New Assignment',
            width: '450px',
            buttons:[{
                value:'Create Assignment',
                clickFunction:function(){
                    $('#assignments_form').ajaxSubmit({
                        type: "POST",
                        dataType: "text",
                        success: function (data) {
                            try{
                                obj = $.parseJSON(data)
                                $('#errors').html('');
                                if(obj['name']){
                                    $('#errors').html($('#errors').html() + 'Name can not be empty<br />');
                                }
                                if(obj['start_date']){
                                    $('#errors').html($('#errors').html() + 'Start date can not be empty<br />');
                                }
                                if(obj['due_date']){
                                    $('#errors').html($('#errors').html() + 'Due date can not be empty<br />');
                                }
                            } catch(e){									
                                $('#start_assignments_zone').after(data);
                                countAssignments()
                                popup_fb.hide();
                            }								
                        },
                        error: function () 
                        {
                            alert('error')
                        } 
                    });
					                        
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })
        return false;        
    })
	
    $('#modify_course_syllabus').live('click', function (){
        var group_id = $('#coursesyllabus').attr('rel');
        popup_fb.load('/fb/coursesyllabus/addform/id/' + group_id,{
            callback: function(){
                if (text_desc != false) {
                    $('#desc').val(text_desc);
                }
            },
            title: $('#modify_course_syllabus').text(),
            postClear: true,
            buttons:[
            {
                value:'Update',
                clickFunction:function() {
                    var group_id = $('#group_id').val();
                    var description = $('#desc').val();
                    $.post('/fb/coursesyllabus/updatedata', {
                        'group_id': group_id, 
                        'desc': description
                    }, function(resultData) {
                        if (resultData == '') {
                            $('#coursesyllabus .description').html('<pre style="font-family: \"lucida grande\",tahoma,verdana,arial,sans-serif;">There is no Course Syllabus added as of yet; click on Add Course Syllabus to add one.</pre>');
                            $('#modify_course_syllabus').text('Add Course Syllabus');
                        } else {
                            $('#coursesyllabus .description pre').text(resultData);
                            $('#modify_course_syllabus').text('Modify Course Syllabus');
                        }
                    });
                    popup_fb.hide();
                }
            },
            {
                value:'Return to Course Syllabus',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })
    });

    $('.edit_assignment').live('click', function(){
        id1 = $(this).parents('.assignment').attr('rel');
        popup_fb.load('/fb/assignments/editform/id/'+id1,{
            width: '450px',
            title: 'Modify Assignment',
            buttons:[
            {
                value:'Save Assignment',
                clickFunction:function(){
                    var message = '';
                    if ($('#name').val() == '') {
                        message = 'Name can not be empty. ';
                    }
                    if ($('#start_date').val() == '') {
                        message += 'Start date can not be empty. ';
                    }
                    if ($('#due_date').val() == '') {
                        message += 'Due date can not be empty. ';
                    }
                    if (message == '') {
                        $('#assignments_form').ajaxSubmit({
                            type: "POST",
                            dataType: "text",
                            success: function (data) {
                                try{
                                    obj = $.parseJSON(data)
                                    $('#errors').html('');
                                    if(obj['date']){
                                        $('#errors').html($('#errors').html() + 'Date can not be empty<br />');
                                    }
                                    if(obj['desc']){
                                        $('#errors').html($('#errors').html() + 'Description can not be empty<br />');
                                    }
                                } catch(e){													
                                    $('.assignment[rel=' + id1 + ']').replaceWith(data);
                                    popup_fb.hide();
                                }								
                            },
                            error: function () 
                            {
                                alert('error')
                            } 
                        });
                    } else {
                        popUpEmpty = new popUp();
                        popUpEmpty.load('<div>' + message + '</div>', {
                            title: 'Error',
                            buttons:[{
                                value:'Okay',
                                clickFunction:function(){
                                    popUpEmpty.hide();
                                }
                            }]
                        });
                    }
                }
            },
            {
                value: 'Cancel',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })
        return false;
    })

    $('.view_assignment_attachments').live('click', function(){
        id1 = $(this).parents('.assignment').attr('rel');
        popup_fb.load('/fb/assignments/attachments/id/'+id1, {
            width: '500px',
            title: 'Assignment Attachments',
            buttons:[
            {
                value:'Return to attachments',
                clickFunction:function(){
                    $('#image').hide();
                    $('#attach').show();
                    popup_fb.hideButtons(1);
                    popup_fb.showButtons(2);
                }
            },
            {
                value: 'Cancel',
                clickFunction: function(){
                    popup_fb.hide();
                }
            },
            {
                value: 'Close',
                clickFunction: function(){
                    $('#image').hide();
                    $('#attach').show();
                    popup_fb.hideButtons(3);
                    popup_fb.showButtons(2);
                }
            }
            ]
        });
        popup_fb.hideButtons(1);
        popup_fb.hideButtons(3);
        return false;
    })
	
    $('.clear_assignment').live('click', function(){
        id1 = $(this).parents('.assignment').attr('rel');
        popup_fb.load('<div style="font-size:11px; color:#333333">You have selected to clear assignment entry. This will remove it from the system and cannot be undone. Are you sure you wish to proceed and clear this entry?</div>', {
            width: '500px',
            title: 'Clear Assignment',
            buttons:[
            {
                value: 'Clear Assignment',
                clickFunction:function(){
                    $('.assignment[rel=' + id1 + ']').html("<div class='progress_bar_no'></div>");
                    $.post('/fb/assignments/delete/', {
                        'id':id1
                    }, function(data){
                        if(data != 0){
                            $('.assignment[rel=' + id1 + ']').remove();
                            countAssignments();
                        }
                    },'text');
                    $('.assignment[rel=' + id1 + ']').remove();
                    popup_fb.hide();
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })			
        return false;	
    })    	

    $('.view_assignment').live('click', function(){
        id1 = $(this).parents('.assignment').attr('rel');
        title = $(this).html();
        popup_fb.load('/fb/assignments/viewassignment/id/'+id1,{
            width: '500px',
            title: title,
            buttons:[{
                value:'Return to Assignments',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }]
        })
        return false;
    })

    $('.submit_assignment').live('click', function(){
        id1 = $(this).parents('.assignment').attr('rel');
        popup_fb.load('/fb/assignments/submitform/', {
            callback:function(){
                $('input[name="aid"]').val(id1);
            },
            width: '500px',			
            title: 'Submit Assignment',
            buttons:[
            {
                value:'Submit Assignment',
                clickFunction:function(){
                    if($('#file_first').val()!=''){
                        $('#assignments_submit_form').ajaxSubmit({
                            type: "POST",
                            dataType: "text",
                            success: function (data) {								
                                try{
                                    obj = $.parseJSON(data)
                                    $('#errors').html('');
                                    if(obj['conf']){
                                        $('#errors').html($('#errors').html() + 'Please, click the checkmark.<br />');
                                    }
                                } catch(e){													
                                    $('.assignment[rel=' + id1 + ']').replaceWith(data);
                                    popup_fb.hide();
                                }								
                            }
                        });
                    }else{
                        $('#errors').html('No content is selected for uploading.');
                    }
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })
        return false;
    })		
	
    $('.submit_assignment_widget').live('click', function(){
        id1 = $(this).parents('.todo').attr('rel');		
        group = $(this).attr('rel')
        popup_fb.load('/fb/assignments/submitform/id/'+group,{
            width: '500px',
            title: 'Submit Assignment',
            buttons:[
            {
                value:'Submit Assignment',
                clickFunction:function(){
                    if($('#file_first').val()!=''){
                        $('#assignments_submit_form').ajaxSubmit({
                            type: "POST",
                            dataType: "text",
                            success: function (data) {									
                                try{
                                    obj = $.parseJSON(data)
                                    $('#errors').html('');
                                    if(obj['conf']){
                                        $('#errors').html($('#errors').html() + 'Date can not be empty<br />');
                                    }
                                } catch(e){													
                                    getTodo($('#course_list').val());
                                    popup_fb.hide();
                                }								
                            }
                        });
                    }else{
                        $('#errors').html('No content is selected for uploading.');
                    }
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })
        return false;
    })
	
	
    $('.view_submission').live('click', function(){
        id1 = $(this).parents('.submission').attr('rel');
        popup_fb.load('/fb/assignments/viewsubmission/id/'+id1, {
            width: '500px',
            title: 'Submissions',
            buttons:[
            {
                value:'Return to Assignments',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })
        return false;
    })

    //-----  added Dmytro Yaroshenko 09.08.2011
    $('.view_livevideo').live('click', function(){
        id1 = $(this).parents('.livevideos').attr('rel');
        title = $(this).html();
        popup_fb2 = new popUp();
        popup_fb2.containerStyle = {
            display: 'none',
            zIndex:'4',
            top:'0px',
            left: '0px',
            position:'fixed',
            margin: '0px',
            boxShadow:'0 0 1px #fff',
            borderRadius:'8px',
            opacity: 1,
            backgroundColor:'#fff',
            overflow: 'hidden',
            border: '10px solid rgba(82, 82, 82, 0.7)'
        };
        popup_fb2.onclose = function(){
            popup_fb2.clearMe();
        };
        popup_fb2.load('/fb/livevideos/viewlivevideo/sid/'+id1,{
            width: '500px',
            title: title,
            postClear: true,
            buttons:[
            {
                value:'Return to Live Video Streams',
                clickFunction:function(){
                    popup_fb2.hide();
                }
            }
            ]
        })
        return false;
    })

    //-----  added Dmytro Yaroshenko 10.08.2011
    $('.view_livestream').live('click', function(){
        id1 = $(this).parents('.livevideos').attr('rel');
        if (id1 == undefined || id1 == '') {
            id1 = $(this).attr('id');
        }
        title = $(this).attr('rel');
        openVideoStream(id1, title);
        return false;
    });

    $('#myViewTabVideoStream').live('click', function() {
        $(this).css('color', 'white');
        $(this).css('background', '#3b5998');
        $('#userViewTabVideoStream').css('color', 'black');
        $('#userViewTabVideoStream').css('background', 'white');
        $('#myVideoViewVideoStream').css('display', '');
        $('#userVideoViewVideoStream').css('display', 'none');
    })

    $('#userViewTabVideoStream').live('click', function() {
        $(this).css('color', 'white');
        $(this).css('background', '#3b5998');
        $('#myViewTabVideoStream').css('color', 'black');
        $('#myViewTabVideoStream').css('background', 'white');
        $('#myVideoViewVideoStream').css('display', 'none');
        $('#userVideoViewVideoStream').css('display', '');
    })

    //-----  added Dmytro Yaroshenko 11.08.2011
    $('.view_livevideo_attachments').live('click', function(){
        id1 = $(this).parents('.livevideos').attr('rel');
        if (id1 == undefined || id1 == '') {
            id1 = $(this).attr('id');
        }
        title = $(this).html();
        popup_fb2 = new popUp();
        popup_fb2.containerStyle = {
            display: 'none',
            zIndex:'4',
            top:'0px',
            left: '0px',
            position:'fixed',
            margin: '0px',
            boxShadow:'0 0 1px #fff',
            borderRadius:'8px',
            opacity: 1,
            backgroundColor:'#fff',
            overflow: 'hidden',
            border: '10px solid rgba(82, 82, 82, 0.7)'
        };
        popup_fb2.onclose = function(){
            popup_fb2.clearMe();
        };
        popup_fb2.load('/fb/livevideos/viewattachments/sid/'+id1,{
            width: '500px',
            title: title,
            buttons:[
            {
                value:'Return to Live Video Streams',
                clickFunction:function(){
                    popup_fb2.hide();
                }
            }
            ]
        })
        return false;
    })

    //---- added by Dmytro Yaroshenko 15.08.2011

    function ajaxSubmitMyForm() {
                          GLOBAL_OBJECT.id = $('#livevideos_form #group_id').val();
                          $('#livevideos_form').ajaxSubmit({
                                type: "POST",
                                dataType: "html",
                                beforeSubmit: function() {
                                     popup_fb2.lock();
                                     popup_fb2.hideButtons(1);
                                },
                                success: function (data) {
                                    try{
                                        obj = $.parseJSON(data)
                                        if (obj['message'] != undefined) {
                                            $('.livevideos_add_edit_form').html(obj['message']);
                                            delete GLOBAL_OBJECT.camera_type;
                                            delete GLOBAL_OBJECT.camera_id;
                                            popup_fb2.unlock();
                                            setTimeout(function(){
                                                $('.livevideos_add_edit_form').parent().parent().remove();
                                                popup_fb2.hide();
                                                $('#groupcontent').load('/fb/livevideos/index/id/'+GLOBAL_OBJECT.id);
                                                delete GLOBAL_OBJECT.id;
                                            }, 2000);
                                        } else {
                                            popup_fb2.showButtons(1);
                                            popup_fb2.unlock();
                                            $('.livevideos_add_edit_form').parent().html(data);
                                        }
                                    } catch(e){
                                        $('.livevideos_add_edit_form').parent().html(data);
                                        popup_fb2.showButtons(1);
                                        popup_fb2.unlock();
                                    }
                                },
                                error: function ()
                                {
                                    alert('error')
                                }
                            });
    }

    function sendRequestForFacilityOfCamera(action, req_id) {
                        var popup_request_params;
                        if (action == 'edit') {
                            popup_request_params = {id: req_id, come_from:'event', from: 'view'};
                        } else {
                            var facility_id = cams[$('#camera_id').val()];
                            popup_request_params = {facility: facility_id, come_from: 'event'};
                        }
                        popup_fb2.lock();
                        popupConfirmRequest = new popUp();
                        popupConfirmRequest.containerStyle = {
                            display: 'none',
                            zIndex:'6',
                            top:'0px',
                            left: '0px',
                            position:'fixed',
                            margin: '0px',
                            boxShadow:'0 0 1px #fff',
                            borderRadius:'8px',
                            opacity: 1,
                            backgroundColor:'#fff',
                            overflow: 'hidden',
                            border: '10px solid rgba(82, 82, 82, 0.7)'
                        };
                        popupConfirmRequest.load(
                            '<div class="fb_facilities_view"><div class="fb_facilities_view_message">You have selected Camera with Facility that requires a reservation. To continue by filling out a reservation request, click Continue below. </div></div>\n\
                            <input type="hidden" id="hidden_id" name="hidden_id" value="' + cams[$('#camera_id').val()] + '"/>',
                            {
                                title: 'Application for Facilities Use',
                                preLoadAnimation: false,
                                postClear: true,
                                width: '300px',
                                buttons: [
                                {
                                    value: 'Continue',
                                    clickFunction: function() {
                                        popupConfirmRequest.lock();
                                        popupRequest = new popUp();
                                        var facility_id = $('#hidden_id').val();
                                        popupRequest.containerStyle = {
                                            display: 'none',
                                            zIndex:'9',
                                            top:'0px',
                                            left: '0px',
                                            position:'fixed',
                                            margin: '0px',
                                            boxShadow:'0 0 1px #fff',
                                            borderRadius:'8px',
                                            opacity: 1,
                                            backgroundColor:'#fff',
                                            overflow: 'hidden',
                                            border: '10px solid rgba(82, 82, 82, 0.7)'
                                        };
                                        popupRequest.load('/admins/requests/'+action,
                                        {
                                            width: '650px',
                                            params: popup_request_params,
                                            title: 'Make Request',
                                            postClear: true,
                                            buttons: [
                                            {
                                                value:'Continue',
                                                clickFunction:function(){
                                                    $('#' + getRequestTarget() + ' form').ajaxSubmit({
                                                        type: "POST",
                                                        dataType: "html",
                                                        beforeSubmit: function () {
                                                            popupRequest.hideButtons(1);
                                                        },
                                                        success: function (data) {
                                                            try{
                                                                obj = $.parseJSON(data)
                                                                if (obj['id'] != undefined) {
                                                                    $('#request_id').val(obj['id']);
                                                                    popup_fb2.lock()
                                                                    ajaxSubmitMyForm();
                                                                } else {
                                                                    $('.livevideos_add_edit_form #message').html('<span style="color: black">Error happened on processing request.</span>');
                                                                }
                                                                popupRequest.hide();
                                                                popupConfirmRequest.hide();
                                                                popup_fb2.unlock();
                                                            } catch(e){
                                                                $('.livevideos_add_edit_form #message').html('<span style="color: black">Error happened on processing request.' + e.text + '</span>');
                                                            }
                                                        },
                                                        error: function ()
                                                        {
                                                            alert('error')
                                                        }
                                                    });
                                                    result = true;
                                                }
                                            },
                                            {
                                                value:'Cancel',
                                                clickFunction:function() {
                                                    $('.livevideos_add_edit_form #message').html('<span style="color: black">You have chosen the camera for a fixed facility, which requires the approval of the request.</span>');
                                                    popupRequest.hide();
                                                    popupConfirmRequest.hide();
                                                }
                                            }
                                            ],
                                            onclose: function(){
                                                popupConfirmRequest.unlock();
                                                popup_fb2.unlock();
                                            },
                                            callback: function(){
                                                var val = facility_id;
                                                $('#facility_id').val(val);
                                                var name = $('#facility_id').attr('name');
                                                var start_date = $('#start_date').val().split(' ');
                                                $('#req_date_single').val(start_date[0]);
                                                $('#facility_id').attr('disabled', 'true');
                                                var input = '<input type="hidden" name="' + name + '" value="' + val + '" />';
                                                $('#facility_id').after(input);
                                            }
                                        });
                                    }
                                },
                                {
                                    value: 'Cancel',
                                    clickFunction: function() {
                                        popupConfirmRequest.hide();
                                    }
                                }
                                ],
                                onclose: function() {
                                    popup_fb2.unlock();
                                }
                            }
                        )

    }

    $('.new_livevideos').live('click', function() {
        popup_fb2 = new popUp();
        popup_fb2.containerStyle = {
            display: 'none',
            zIndex:'4',
            top:'0px',
            left: '0px',
            position:'fixed',
            margin: '0px',
            boxShadow:'0 0 1px #fff',
            borderRadius:'8px',
            opacity: 1,
            backgroundColor:'#fff',
            overflow: 'hidden',
            border: '10px solid rgba(82, 82, 82, 0.7)'
        };
        popup_fb2.onclose = function(){
            popup_fb2.clearMe();
        };
        popup_fb2.load('/fb/livevideos/addform',{
            width: '450px',
            title: 'Add New Live Video Stream',
            postClear: true,
            buttons:[
            {
                value:'Create Video Stream',
                clickFunction:function() {
                    if (GLOBAL_OBJECT.camera_type != undefined && $("#livevideos_form #camera_type").val() == 'external') {
                        $("#livevideos_form #camera_id").rules('add',{
                            required: true,
                            min: 1,
                            messages: {
                               required: "Please, select camera",
                               min: "* Please, select camera"
                            }
                        });
                    } else {
                        if (GLOBAL_OBJECT.camera_type != undefined) {
                            $("#livevideos_form #camera_id").rules('remove');
                        }
                    }
                    if($("#livevideos_form").valid() 
                        && GLOBAL_OBJECT.camera_type != undefined
                        && $("#livevideos_form #camera_type").val() == 'external'
                        && $("#livevideos_form #camera_id").val() in cams
                        && ($("#livevideos_form #camera_id").val() != GLOBAL_OBJECT.camera_id)) {
                        
                        sendRequestForFacilityOfCamera('add');
                    } else {
                        if ($("#livevideos_form").valid()) {
                            if ($("#livevideos_form #camera_id").val() in cams && $("#livevideos_form #camera_type").val() != 'userown') {

                            } else {
                                $('#livevideos_form #request_id').val('0');
                            }
                            ajaxSubmitMyForm();
                        }
                    }
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb2.hide();
                    delete GLOBAL_OBJECT.camera_type;
                    delete GLOBAL_OBJECT.camera_id;
                }
            }
            ]
        });
        return false;
    })

    //----- added by Dmytro Yaroshenko  16.08.2011  ---

    $('.edit_livevideos').live('click', function(){
        id1 = $(this).parents('.livevideos').attr('rel');
        id2 = $(this).parents('#livevideos').attr('rel')
        if (id1 == undefined || id1 == '') {
            id1 = $(this).attr('id');
        }
        if (id2 == undefined || id2 == '') {
            id2 = $(this).attr('gid');
        }
        popup_fb2 = new popUp();
        popup_fb2.containerStyle = {
            display: 'none',
            zIndex:'4',
            top:'0px',
            left: '0px',
            position:'fixed',
            margin: '0px',
            boxShadow:'0 0 1px #fff',
            borderRadius:'8px',
            opacity: 1,
            backgroundColor:'#fff',
            overflow: 'hidden',
            border: '10px solid rgba(82, 82, 82, 0.7)'
        };
        popup_fb2.load('/fb/livevideos/editform/id/'+id2+'/sid/'+id1,{
            width: '450px',
            title: 'Modify Video Stream',
            postClear: true,
            buttons:[
            {
                value:'Save Video Stream',
                clickFunction:function(){
                    if (GLOBAL_OBJECT.camera_type != undefined && $("#livevideos_form #camera_type").val() == 'external') {
                        $("#livevideos_form #camera_id").rules('add',{
                            required: true,
                            min: 1,
                            messages: {
                               required: "Please, select camera",
                               min: "* Please, select camera"
                            }
                        });
                    } else {
                        if (GLOBAL_OBJECT.camera_type != undefined) {
                            $("#livevideos_form #camera_id").rules('remove');
                        }
                    }
                    var dt_start = $('#start_date').val().split(' ');
                    var date_start = dt_start[0];
                    var date = new Date (date_start);
                    var date_str = date.getTime();
                    if($("#livevideos_form").valid() && GLOBAL_OBJECT.camera_type != undefined && $("#livevideos_form #camera_type").val() == 'external' && $("#livevideos_form #camera_id").val() in cams && ($("#livevideos_form #camera_id").val() != GLOBAL_OBJECT.camera_id || date_str != $('#date_prev_str').val())) {
                        if ($('#request_id').val() > 0) {
                            sendRequestForFacilityOfCamera('edit', $('#request_id').val());
                        } else {
                            sendRequestForFacilityOfCamera('add');
                        }
                    } else {
                        if ($("#livevideos_form").valid()) {
                            if ($("#livevideos_form #camera_id").val() in cams && $("#livevideos_form #camera_type").val() != 'userown') {

                            } else {
                                $('#livevideos_form #request_id').val('0');
                            }
                            ajaxSubmitMyForm();
                        }
                    }
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb2.hide();
                    popup_fb2.clearMe();
                    delete GLOBAL_OBJECT.camera_type;
                    delete GLOBAL_OBJECT.camera_id;
                }
            }
            ]
        })
        return false;
    })
    
    $('.clear_livevideos').live('click', function(){
        id1 = $(this).parents('.livevideos').attr('rel');
        if (id1 == undefined || id1 == '') {
            id1 = $(this).attr('id');
        }
        popup_fb2 = new popUp();
        popup_fb2.containerStyle = {
            display: 'none',
            zIndex:'4',
            top:'0px',
            left: '0px',
            position:'fixed',
            margin: '0px',
            boxShadow:'0 0 1px #fff',
            borderRadius:'8px',
            opacity: 1,
            backgroundColor:'#fff',
            overflow: 'hidden',
            border: '10px solid rgba(82, 82, 82, 0.7)'
        };

        popup_fb2.onclose = function(){
            my_ajax_reload();
            popup_fb2.clearMe();
        }
        popup_fb2.load('You have selected to clear Video Stream entry. <br />This will remove it from the system and cannot be undone. <br />Are you sure you wish to proceed and clear this entry?', {
            title: 'Clear Stream',
            width: 500,
            buttons:[
            {
                value:'Clear Video Stream',
                clickFunction:function(){
                    $('.livevideos[rel=' + id1 + ']').html("<div class='progress_bar_no'></div>");
                    $.post('/fb/livevideos/delete/', {
                        'sid':id1
                    }, function(data){
                        if(data != 0){
                            $('.livevideos[rel=' + id1 + ']').remove();
                            countLivevideos();
                        }
                    },'text');
                    $.get('/fb/livevideos/hasaddpermission', {
                        'sid':id1
                    }, function(data){
                        if (countLivevideos() == 0) {
                            var html = '<div id="empty_message">There are no Live Video Streams listed as of yet';
                            if (data == 'has') {
                                html += '; click on Add New Video Stream to add one.';
                            }
                            html += '</div>';
                            if ($('#livevideos_zone #start_livevideos_zone') != undefined) {
                                $('#livevideos_zone #start_livevideos_zone').after(html);
                            } 
                        }
                    }, 'text');
                    popup_fb2.hide();
                    try{
                        if (popupView != undefined) {
                            popupView.hide();
                        }
                    } catch (e) {}
                    if($('.actions input')[0] != undefined && $('.actions input')[0].value > 0) {
                        $('.event_id_' + $('.actions input')[0].value).remove();
                    }
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb2.hide();                    
                }
            }
            ]
        })
        return false;
    })

    $('#clear_past_livevideos').live('click', function(){
        gid = $('#livevideos').attr('rel');
        href = $(this).attr('href');
        popup = new popUp();
        popup.load('You have selected to clear all of your past Live Video Streams entries. This will remove them from the system and cannot be undone. Are you sure you wish to proceed and clear these entries?', {
            title:'Clear All Past Video Streams',
            width: '500px',
            buttons:[
                {
                    value: 'Clear All Past Video Streams',
                    clickFunction: function(){
                        $.post('/fb/livevideos/clearpast', {
                            'gid':gid
                        }, function(){
                            popup.hide();
                            my_ajax_reload();
                        });
                    }
                },
                {
                    value: 'Cancel',
                    clickFunction: function(){
                        popup.hide();
                    }
                }
            ]
        })        
        return false;
    })

    function countLivevideos(){
        annCount = $('.livevideos').size()
        val = 'Displaying ' + annCount + ' Live Video Stream';
        if(annCount != 1){
            val += 's'
        }
        $('#count_livevideo').text(val)
        return annCount;
    }

$('#attachments_list').live('click', function(){
    if ($('#attachments_table').css('display') == 'none') {
        $('#attachments_list #arrow_22').css('display','');
        $('#attachments_list #arrow_21').css('display','none');
        $('#attachments_table').css('display', '');
    } else {
        $('#attachments_list #arrow_22').css('display','none');
        $('#attachments_list #arrow_21').css('display','');
        $('#attachments_table').css('display', 'none');
    }
});

$('.view_image_stream').live('click', function(){
    $('#attachments_list #arrow_21').css('display','');
    $('#attachments_list #arrow_22').css('display','none');
    $('#attachments_table').hide();
    $('#image').show();
    $('#image img:first').attr('src', '/download?type=file&q=' + $(this).attr('rel'));
    $('#image a:first').attr('href', '/download?type=file&q=' + $(this).attr('rel'));
    $('#dialog').dialog('option', 'buttons', [{
        text: 'Close',
        click: function(){
            $('#image').hide();
            $('#attachments_list #arrow_22').css('display','');
            $('#attachments_list #arrow_21').css('display','none');
            $('#attachments_table').show();
            /*$('#dialog').dialog('option', 'buttons', [{
                text:'Return to attachments',
                click:function(){
                    $( this ).dialog( "destroy");
                }}]
            )*/
        }
    }])
    return false;
})
$('.hide_image_stream').live('click', function(){
        $('#attachments_list #arrow_22').css('display','');
        $('#attachments_list #arrow_21').css('display','none');
		$('#attachments_table').show();
		$('#image').hide();
		$('#image img:first').attr('src', '')
		$('#image a:first').attr('href', '')
})

function my_ajax_reload() {
     var my_href = window.location.href.split('#');
     var temp_href = my_href[1];
     var splited_temp_href = temp_href.split('/');
     var needed_href = '';
         for (var i = 0; i < splited_temp_href.length; i++) {
             if (i < splited_temp_href.length - 1) {
                 if (i != 0) {
                     needed_href += '/' + splited_temp_href[i];
                 } else {
                     needed_href += splited_temp_href[i];
                 }
             } else {
                 if(splited_temp_href[i] != '' && i > 1) {
                     needed_href += '/' + splited_temp_href[i];
                 } else {
                     needed_href += splited_temp_href[i];
                 }
             }
         }
     window.location.href='#'+needed_href + '/';
}
    //----- end of Dmytro Yaroshenko adds ---

    $('#clear_past_assignments').live('click', function(){
        gid = $('#assignments').attr('rel');
        href = $(this).attr('href');
        popup_fb.load('You have selected to clear all of your past assignment entries. This will remove them from the system and cannot be undone. Are you sure you wish to proceed and clear these entries?', {
            width: '500px',
            title: 'Clear All Past Assignments',
            buttons:[
            {
                value:'Clear All Past Assignments',
                clickFunction:function(){
                    $.post('/fb/assignments/clearpast', {
                        'gid':gid
                    }, function(){
                        popup_fb.hide();
                        location.href = '#assignments/index/'+Math.random();
                    })
                }
            },
            {
                value:'Cancel',
                clickFunction:function(){
                    popup_fb.hide();
                }
            }
            ]
        })
        return false;
    })
	
	
    //////////////////////////////////////////////////////////////////
    //							STUDY GROUPS						//
    //////////////////////////////////////////////////////////////////

    function countStudygroups(){
        annCount = $('#mygroup_list .studygroup_info').size()		
        $('#count_groups').text(annCount)
        annCount = $('#nomygroup_list .studygroup_info').size()		
        $('#count_groups1').text(annCount)
    }

    $('#new_studygroup').live('click', function(){
        gid = $(this).parents('#studygroups').attr('rel');
        popup = new popUp();
        popup.load('/fb/studygroup/addform',{
            title: 'Add Study Group',
            postClear: true,
            width: '500px',
            buttons:[
                {
                    value:'Create Study Group',
                    clickFunction:function(){
                        $('#addstudygroup_form').ajaxSubmit({
                            type: "POST",
                            dataType: "json",
                            success:function(data){
                                if(data['status'] == 'error'){
                                    popup.load(data['form'])
                                }else{								
                                    $('#mygroup_list').prepend(data['html'])
                                    popup.hide();
                                    $('.popup_pop_container').remove();
                                    countStudygroups();
                                }
                            }
                        });
                    }
                },
                {
                    value: 'Cancel',
                    clickFunction:function(){
                        popup.hide();
                    }
                }
            ]
        })
    })

    $('.studygroup_edit').live('click', function(){
        obj = $(this).parents('.studygroup_info');
        id1 = $(obj).attr('rel');
        
        popup = new popUp();
        popup.load('/fb/studygroup/editform/id/'+id1,{
            title: 'Modify Study Group',
            width: '500px',
            buttons:[
                {
                    value:'Save Study Group',
                    clickFunction:function(){
                        $('#addstudygroup_form').ajaxSubmit({
                            type: "POST",
                            dataType: "json",
                            success:function(data){
                                if(data['status'] == 'error'){
                                    popup.load(data['form'])
                                }else{								
                                    $(obj).replaceWith(data['html'])
                                    popup.hide();
                                }
                            }
                        });
                    }
                },
                {
                    value: 'Cancel',
                    clickFunction:function(){
                        popup.hide();
                    }
                }
            ]
        })
        
    })

    $('.studygroup_delete').live('click', function(){
        obj = $(this).parents('.studygroup_info');
        id1 = $(obj).attr('rel');
        popup = new popUp();
        popup.load('Are you sure you want to clear this group from the system?',{
            width: '500px',
            title: 'Clear Study Group',
            buttons:[
                {
                    value:'Yes',
                    clickFunction:function(){
                        $.post('/fb/studygroup/clear/', {
                            'id':id1
                        }, function(){
                            $(obj).slideUp('fast', function(){
                                $(obj).remove();
                                countStudygroups()
                            })					
                        })
                        popup.hide();
                    }
                },
                {
                    value:'Cancel',
                    clickFunction:function(){
                        popup.hide();
                    }
                }
            ]
        })
    })

    $('.studygroup_view_members').live('click', function(){	
        id1 = $(this).parents('.studygroup_info').attr('rel');
        popup = new popUp();
        popup.load('/fb/studygroup/members/id/' + id1, {
            title: 'Group members',
            width: '500px',
            buttons:[
                {
                    value:'Cancel',
                    clickFunction:function(){
                        popup.hide();
                    }
                }
            ]
        })
    })

    $('.studygroup_join').live('click', function(){
        var obj = $(this).parents('.studygroup_info');
        id1 = $(obj).attr('rel');
        studygroup_name = $('.studygroup_info[rel="'+id1+'"] .studygroup_name').text();
        popupJoin = new popUp();
        popupJoin.load('Do you really want to join "' + studygroup_name + '" Study Group?',{
            title: 'Join Study Group!',
            width: '500px',
            buttons:[
                {
                    value:'Yes',
                    clickFunction:function(){
                        $.post('/fb/studygroup/join/', {
                            'id':id1
                        }, function(data){
                            if(data['status'] == 'join'){
                                $(obj).remove();
                                $('#mygroup_list').prepend(data['html'])
                            }
                            if(data['status'] == 'semi'){
                                $(obj).replaceWith(data['html'])							
                            }
                            countStudygroups();
                            popupJoin.hide();
                            $('.popup_pop_container').remove();
                        },'json')					
                    }
                },
                {
                    value:'Cancel',
                    clickFunction:function(){
                        popupJoin.hide();
                        $('.popup_pop_container').remove();
                    }
                }
            ]
        })
    })

    $('.approve_ok').live('click', function(){
        obj = $(this).parents('.approve');
        id1 = $(obj).attr('rel');
        $.post('/fb/studygroup/approve/', {
            'id':id1
        }, function(){
            $(obj).remove();
            $('#count_approvals').text($('.approve').size())
        })
    })

    $('.approve_ignore').live('click', function(){
        obj = $(this).parents('.approve');
        id1 = $(obj).attr('rel');
        $.post('/fb/studygroup/ignore/', {
            'id':id1
        }, function(){
            $(obj).remove();
            $('#count_approvals').text($('.approve').size())
        })
    })

    $('.studygroup_leave').live('click', function(){
        obj = $(this).parents('.studygroup_info');
        id1 = $(obj).attr('rel');
        $.post('/fb/studygroup/leave/', {
            'id':id1
        }, function(data){
            $(obj).remove();
            $('#nomygroup_list').append(data);
            countStudygroups()
        })
    })

    $('.studygroup_invite').live('click', function(){
        obj = $(this).parents('.studygroup_info');
        id1 = $(obj).attr('rel');
        gid = $('#studygroups').attr('rel');
        popup = new popUp();
        popup.load('/fb/studygroup/inviteform/id/' + gid+'/sid/'+id1,{
            title: 'Join Study Group',
            width: '500px',
            buttons:[
                {
                    value:'Yes',
                    clickFunction:function(){
                        var arr = new Array;
                        $('.classmate_selected').each(function(){
                            arr.push($(this).attr('rel'));
                        })
                        $.post('/fb/studygroup/invite', {
                            'users':arr,
                            'message': $('#message').text(),
                            'sid': id1
                        }, function(data){
                            $(obj).replaceWith(data);
                            popup.hide();
                            $('.popup_pop_container').remove();
                        })					
                    }
                },
                {
                    value:'Cancel',
                    clickFunction:function(){
                        popup.hide();
                        $('.popup_pop_container').remove();
                    }
                }
            ]
        });
        
    })

    $('.invite_accept').live('click', function(){
        var obj = $(this).parents('.studygroup_info');
        var id1 = $(obj).attr('rel1');
        $.post('/fb/studygroup/inviteaccept', {
            'id': id1
        }, function(){
			
            //$(obj).remove();
            })
    })

    $('.invite_ignore').live('click', function(){
        var obj = $(this).parents('.studygroup_info');
        var id1 = $(obj).attr('rel1');
        $.post('/fb/studygroup/inviteignore', {
            'id': id1
        }, function(){
            $(obj).remove();
        })
    })

    $('.studygroup_sendmessage').live('click', function(){
        obj = $(this).parents('.studygroup_info');
        id1 = $(obj).attr('rel');
        popup_join = new popUp();
        popup_join.load('/fb/studygroup/messageform/id/' + id1,{
            title: 'Join Study Group',
            width: '500px',
            buttons:[
                {
                    value:'Yes',
                    clickFunction:function(){
                        $('#sendmessage_form').ajaxSubmit({
                            type: "POST",
                            dataType: "json",
                            success:function(data){
                                if(data['status'] == 'error'){
                                   popup_join.load(data['form']);
                                } else {																
                                    popup_join.hide()
                                }
                                $('.popup_pop_container').remove();
                            }
                        });
                    }
                },
                {
                    value:'Cancel',
                    clickFunction:function(){
                        popup_join.hide();
                        $('.popup_pop_container').remove();
                    }
                }
            ]
        });
    })

    $('.mark_as_read').live('click', function(){
        obj = $(this);
        id1 = $(obj).parents('.studygroup_message').attr('rel');
        $.post('/fb/studygroup/messageread', {
            'id':id1
        }, function(){
            $(obj).replaceWith('Readed');
        })
    })

    $('.message_clear').live('click', function(){
        obj = $(this).parents('.studygroup_message');
        id1 = $(obj).attr('rel');
        $.post('/fb/studygroup/messageclear', {
            'id':id1
        }, function(){
            $(obj).remove();
            $('#count_messages').text($('.studygroup_message').length);
        })
    })

    $('#mind_comment').live('keypress', function(e){
        code = (e.keyCode ? e.keyCode : e.which);
        form = $(this).parents('.comment_form');
        if(code == 13){
            text = $(this).val();
            mind_id = $(this).attr('rel');
            $(this).val('');
            gid = $('input[name=id]').val();
            alert(mind_id+':'+text+':'+gid)
            $.post('/fb/studygroup/addcomment', {
                'text':text, 
                'id': gid, 
                'mind_id':mind_id
            }, function(data){                
                form.before(data);                
            }, 'html')
        }
    })
    
//    function showFileUploader(){
//        for (i=1;i<5;i++){
//            
//            if($('#img_close-'+i).size()==0){
//                $(".sg_share_file #share-"+i).wrap('<div id="wrap-'+i+'"></div>')
//                $(".sg_share_file #share-"+i).after('<a href="javascript:void(0);" id="img_close-'+i+'" class="deleteicon"> x</a>');
//            }
//            $("#wrap-"+i).hide();
//        }
//        
//        $("#file_upload").dialog({
//            modal:true, 
//            show:'slide', 
//            title:'Upload your file'
//        });
//        $("#file_upload").dialog('open');
//        
//    }
    
//    $(".attach_more").live('click',function(){
//        for(j=1;j<5;j++){
//            if(!$("#wrap-"+j).is(':visible')){
//                $("#wrap-"+j).show();
//                console.log(j); 
//                if(j==4) $(".attach_more").hide();
//                break;
//            }
//        }
//    })
    
    $(window).load(function(){
        for (i=1;i<5;i++){
            //alert(i);
            $("#img_close-1").live("click", function(){
                $(".attach_more").show();
                $("#wrap-1").hide();
            })
            $("#img_close-2").live("click", function(){
                $(".attach_more").show();
                $("#wrap-2").hide();
            })
            $("#img_close-3").live("click", function(){
                $(".attach_more").show();
                $("#wrap-3").hide();
            })
            $("#img_close-4").live("click", function(){
                $(".attach_more").show();
                $("#wrap-4").hide();
            })
        }
    })

    function shareFile(){
        $('.sg_share_file').unbind('submit');
        $('.sg_share_file').ajaxForm({
            type: "POST",
            dataType: "text",
            success:function(response){
                response = response.replace(/<table>/g,'');
                response = response.replace(/<tbody>/g,'');
                response = response.replace(/<\/tbody>/g,'');
                response = response.replace(/<\/table>/g,'');
                $('#study_files_table').append(response);
                $("#file_upload").dialog('close');
            },
            error: function(error){
                
            }
        })
    }
 
 
    function validate_date(month, day, year){
        result=null;
        date = {
            'day':day, 
            'year':year,
            'month':month
        };
        $.ajax({
            url:  '/fb/json/valdate',
            dataType:'json',
            data: date,
            success: function(response){
                this.result = response;
            }
             
        })
        return result;
    }
     
     
    /**
      * date validation  event
      */
     
    $('#date_element').live('blur',function(){
        $.post('/fb/studygroup/ajax',
        {
            'op':'validate',
            'element':'date',
            'day':$('#date-day').val(),
            'month':$('#date-month').val(),
            'year':$('#date-year').val()
        },
        function(response){
            if(response){
                errors ='<ul>';
                for(error in response.date){
                    errors += '<li>'+response.date[error]+'</li>';
                }
                errors += '</ul>';
                $('#date_element_error').html(errors);
            }
                    
            if(response==''||response==null){
                //alert('null');
                $('#date_element_error').empty();
            }
        },
        'json'
        );
         
    })
    $('#share_btn').live('click',function(){
        var is_event = 0;
        if ($('#event_title') != '' && $('#event_location') != '' && $('#event_date') != '') {
            is_event = 1;
        }
        if ($('#what_mind_text').val() == '' && is_event == 0) {
            popUpEmpty = new popUp();
            popUpEmpty.load('<div>Please, enter some text.</div>', {
                title: 'Error',
                buttons:[{
                    value:'Okay',
                    clickFunction:function(){
                        popUpEmpty.hide();
                    }
                }]
            })
        } else {
            $('#whatmind_form').ajaxSubmit({
                url:'/fb/studygroup/addmind',
                type: 'POST',
                success: function(response){
                    $('.whats_mind_list').prepend(response);
                    $('#what_mind_text').val('');
                    $('#photo').val('');
                    $('#video').val('');
                    $('#event_title').val('');
                    $('#event_location').val('');
                    $('#event_date').val('');
                    $('#share_link').val('http://');
                    $('.RemoveLink').click();
                    $('#photo').replaceWith('<input id="photo" type="file" name="photo">');
                    $('#video').replaceWith('<input id="video" type="file" name="video">');
                },
                error: function (){
                    alert('error');
                }

            });
        }
        return false;
    });
  

    function delete_mind(id){
        $.post('/fb/studygroup/deletemind',{
            'id':id
        });
        $('.what_mind_event:[rel='+id+']').remove();
    }

    $('#note_btn').live('click',function(){
        if ($('#note_text').val() == '') {
            popUpError = new popUp();
            popUpError.load('<div>Please, enter some text.</div>', {
                title: 'Error',
                buttons:[{
                    value:'Okay',
                    clickFunction:function(){
                        popUpError.hide();
                    }
                }]
            });
        } else {
            $('#note_form').ajaxSubmit({
                url:'/fb/studygroup/addnote',
                type: 'POST',
                success: function(response){
                    $('.notes_list').prepend(response);
                    $('#note_text').val('');
                    $('#note_photo').val('');
                    $('#note_photo_row').hide();
                    var count_notes = $('.count_notes span').text();
                    count_notes++;
                    $('.count_notes span').text(count_notes);
                    $('#note_photo').replaceWith('<input id="note_photo" type="file" name="note_photo">');
                },
                error: function (){
                    alert('error');
                }

            });
        }
        return false;
    });

    $("#modify_note").live('click', function(){
        var id = $(this).parents('.note_event').attr('rel');
        popup = new popUp();
        popup.load('/fb/studygroup/modifynote?id='+id,{
            title: 'Modify note',
            buttons:[
                {
                    value:'Modify',
                    clickFunction:function(){
                        $('#modify_form_note').ajaxSubmit({
                            url:'/fb/studygroup/updatenote',
                            success: function(response){
                                $('div[rel='+id+']').replaceWith(response);
                                popup.hide();
                            }
                        })
                        return false;
                    }
                },
                {
                    value:'Cancel',
                    clickFunction:function(){
                        popup.hide();
                    }
                }
            ]
        })
    })
    $('.message_clear').live('click', function(){
        obj = $(this).parents('.studygroup_message');
        id1 = $(obj).attr('rel');
        $.post('/fb/studygroup/messageclear', {
            'id':id1
        }, function(){
            $(obj).remove();
            $('#count_messages').text($('.studygroup_message').length);
        })
    })


    $("#delete_note").live('click', function(){
        var id = $(this).parents('.note_event').attr('rel');
        popup = new popUp();
        popup.load('Are you sure you want to delete this note?',{
            title: 'Delete note',
            buttons:[
                {
                    value:'Delete',
                    clickFunction:function(){
                        $.post('/fb/studygroup/deletenote', {
                            'note_id': id
                        });
                        popup.hide();
                        $('div[rel='+id+']').remove();
                        var count_notes = $('.count_notes span').text();
                        count_notes--;
                        $('.count_notes span').text(count_notes);
                    }
                },
                {
                    value:'Cancel',
                    clickFunction:function(){
                        popup.hide();
                    }
                }
            ]
        });
        
    })
    $(".show_note_attach").live('click', function(){
//        var note_id = $(this).parents('.note_event').attr('rel');
//        showNoteAttach(note_id);
        var note_id = $(this).parents('.note_event').attr('rel');
        if (typeof(popup_fb) == 'undefined' || !popup_fb.popContainer.parentNode) popup_fb = new popUp();
        popup_fb.load('/fb/studygroup/noteattach/id/'+note_id, {
            width: '500px',
            title: 'Note Attachments',
            callback: function(){
                popup_fb.hideButtons(1);
                popup_fb.hideButtons(3);
            },
            buttons:[
            {
                value:'Return to attachments',
                clickFunction:function(){
                    $('#image').hide();
                    $('#attach').show();
                    popup_fb.hideButtons(1);
                    popup_fb.showButtons(2);
                }
            },
            {
                value: 'Cancel',
                clickFunction: function(){
                    popup_fb.hide();
                }
            },
            {
                value: 'Close',
                clickFunction: function(){
                    $('#image').hide();
                    $('#attach').show();
                    popup_fb.hideButtons(3);
                    popup_fb.showButtons(2);
                }
            }
            ]
        });
        return false;
    })

    function showNoteAttach(id){
        $.post('/fb/studygroup/noteattach', {
            'id':id
        }, function(response){
            response = $.parseJSON(response);
            content ='<tr><td width="60%" style="text-align: left; padding-right: 3px; ">'+response.file_name+
            '</td><td width="13%" style="text-align: left; padding-right: 3px; ">'+
            '<a onclick="showImage()">View</a></td>'+
            '<td width="27%" style="text-align: left; padding-right: 3px; ">'+
            '<a href="/fb/files/download/id/'+response.hash+'" target="_self">'+
            'Download</a></td></tr><tr><td colspan="3" style="border-bottom:1px solid gray"></td></tr>';
//            $('.note_popup').html($('#viewer').html());
//            $('.note_popup').children('table').append(content);
            popup = new popUp();
            popup.load(content,{
                title: 'Attachments',
                width: '400px',
               // height: '250px',
                buttons: [
                    {
                        value:'Close',
                        clickFunction:function(){
                            popup.hide();
                        }
                    }
                ]
            });
        });
    }
})
function uploadFileValidation(strSelector, intMaxFileSize, arrAllowedTypesExtensions, strAllowedExtensions) {
    var last_this;
    var total_file_size = 0;
    var message = '';
    var failed_type = 0;
    $(strSelector).each(function(){
        last_this = this;
        if (typeof(this.files) != 'undefined') {
            var files = this.files;
            for(var i = 0; i < files.length; i++) {
                file = files[i];
                var type = file.fileType != null ? file.fileType : file.type;
                var size = file.fileSize != null ? file.fileSize : file.size;
                if (arrAllowedTypesExtensions.length > 0) {
                    if (jQuery.inArray(type, arrAllowedTypesExtensions) == -1) {
                        failed_type = 1;
                        $(last_this).val('');
                    }
                }
                if (intMaxFileSize > 0) {
                    total_file_size += size;
                }
            }
        }
    });
    if (intMaxFileSize > 0) {
        if (total_file_size > intMaxFileSize) {
            message += 'Maximum allowed file size 10M. ';
        }
    } 
    if (failed_type == 1) {
        message += 'Illegal photo format. Allowed ' + strAllowedExtensions;
    }
    if (message != '') {
        $(last_this).val('');
        popUpFileValidate = new popUp();
        popUpFileValidate.load('<div>' + message + '</div>', {
            title: 'Error',
            buttons:[{
                value:'Okay',
                clickFunction:function(){
                    popUpFileValidate.hide();
                }
            }]
        })
    }
}

$(function(){
    $('#pager_whatsnew').live('click', function(){
        $.post('/fb/whatsnew/getevents',{'start':whatsnew_start},function(data){
            $('#pager_whatsnew').replaceWith(data);
            whatsnew_start += 10;
        });
    });
})

var last;
function processFormPass() {
    if (last == undefined) {
        var last = $('.respass_form:last');
    }
    last.ajaxSubmit({
        type: "POST",
        dataType: "text",
        success: function (data) {
            try{
                var obj = $.parseJSON(data);
                if (obj['message'] != undefined) {
                     $('.respass_div').html(obj['message']);
                     $('.respass_div').parent().parent().next().find('button:first').css('display', 'none');
                     setTimeout(function(){
                         popup_res.hide();
                     }, 4000);
                }else {
                     $('.popup_content_div').has('.respass_div').html(data);
                }
            } catch(e){
                $('.popup_content_div').has('.respass_div').html(data);
            }
        },
        error: function (e)
            {
                alert('error ' + e.text);
            }
     });
}

$('#restore_pass_link').live('click',function(){
    popup_res = new popUp();
    var title = 'Restore password';
    popup_res.containerStyle = {
            display: 'none',
            zIndex:'4',
            top:'0px',
            left: '0px',
            position:'fixed',
            margin: '0px',
            boxShadow:'0 0 1px #fff',
            borderRadius:'8px',
            opacity: 1,
            backgroundColor:'#fff',
            overflow: 'hidden',
            border: '10px solid rgba(82, 82, 82, 0.7)'
        };
    popup_res.onclose = function(){
        delete window.popup_res;
        $('.popup_pop_container').has('input[name="login"]').find('.popup_close:first').click();
    };
    $(popup_res).load('/restore_password',function(res){
       popup_res.load('<div>' + res + '<div>',{
            width: '350px',
            title: title,
            buttons:[
            {
                value:'Send',
                clickFunction:function(){
                    processFormPass();
                }
            },
            {
                value:'Back',
                clickFunction:function(){
                    popup_res.hide();
                }
            }
            ]
        })
        return false;
    });
});
