

/**
 * TodoItem class.
 * Used when adding todo items for a TaskList
 * Contains all html generating concerning display of Todo Items
 * Methods: add(), init()
 * 
 */
var TodoItem = {
    parent_list:'',
    oid:'', // oid e egentligen ID bara, oid e djevulens pafund
    //field_value:'',
    title:'',
    close_time:'',
    event_has_past:'',
    is_checked:false,
    oid_mem:null,
    title_mem:null,
    
    init: function(oid) {
        //eTodo.update();
        //eDesktop.widget.init_pos('eTodo');
        TodoItem.oid = oid
    },
    
    over: function(oid){
        $j('#id_'+oid).addClass('edit_group');
        $j($j('#id_'+oid).find('.item-tools-over')).show();
        
    },
    out: function(oid){
        $j('#id_'+oid).removeClass('edit_group');
        $j($j('#id_'+oid).find('.item-tools-over')).hide();
    },
    check_toggle:function(oid){
        //$j($j('#id_'+oid).find('img.green2')).css('background-position','0px -36px!important');
        
        if($j($j('#id_'+oid).find('img.check-box')).hasClass('checked')){
            /*$j($j('#id_'+oid).find('img.check-box')).addClass('green2');
            $j('#id_'+oid).css('text-decoration','none');
            $j($j('#id_'+oid).find('img.check-box')).removeClass('checked');*/
            var checked = ".";
        } else {
            /*$j('#id_'+oid).css('text-decoration','line-through');
            $j($j('#id_'+oid).find('img.check-box')).addClass('checked');
            $j($j('#id_'+oid).find('img.check-box')).removeClass('green2');*/
            var checked = "marked";
        }
        
        var req = xdbc.addQue(xdbc.cmd('family_19'));
        req.setAttribute('sys:set_oid', oid);
        req.setAttribute('sys:set_parent_id', $j('#id_'+oid).attr('parent_id') );
        req.setAttribute('sys:set_marked_as_done', checked);
        
        xdbc.exec(function(resp) {
            var return_object = resp.selectSingleNode('//item');
            TodoItem.populate_object_from_xpath(return_object);
            TodoItem.re_draw_activity();
        });
        
    },
    remove: function(oid){
        $j('#id_'+oid).remove();
        var req = xdbc.addQue(xdbc.cmd('family_20'));
        req.setAttribute('sys:set_oid', oid);
        req.setAttribute('sys:remove', oid);

        xdbc.exec(function(resp) {
            TodoItem.populate_object_from_xpath(resp);
        });
    },
    
    /**
     *
     */
    participant_exist: function(activity_id, value_to_check){
        var checked_participants = TodoList.content.selectNodes('//todo_list/item[@id="'+activity_id+'"]/participant');
        for( var j = 0; j < checked_participants.length; j++ ) {
            if(value_to_check == checked_participants[j].getAttribute('participant_id') ){
                return true;
            }
        }
        return false;
    },
    
    /**
     * Open the modal layer for an activity and set values from ledger to the form
     *
     */
    edit: function(parent_list, oid){
        modalLayer('id_modal_edit_activity', true, 260);
        
        //eForm.init( $('id_modal_edit_activity') ) ;
        TodoItem.parent_list = parent_list;
        var activity = TodoList.get_activity(TodoItem.parent_list, oid);
        

        $j('#id_activity_id_edit').val( oid );
        $j('#id_activity_parent_id_edit').val( parent_list );
        $j('#id_activity_title_edit').val( activity.getAttribute('title') );
        $j('#id_activity_close_time').val( activity.getAttribute('close_time') );
        $j('#id_activity_is_checked_edit').val( activity.getAttribute('is_checked') );
        
        $j('#id_member_activity_list > input').each(function(i){
            var field_value = $j(this).val().split('-');
            
            if( TodoItem.participant_exist(oid, field_value[1]) ){
                $j(this).attr('checked','checked');
            }
        });
        
        return false;
    },
    
    populate_object_from_xpath: function(xpath_object){
        TodoItem.oid = xpath_object.getAttribute('id');
        TodoItem.title = xpath_object.getAttribute('title');
        TodoItem.event_has_past = xpath_object.getAttribute('event_has_past');
        TodoItem.close_time = xpath_object.getAttribute('close_time');
        TodoItem.parent_list = xpath_object.getAttribute('parent_id');
        TodoItem.is_checked = xpath_object.getAttribute('is_checked');
        //TodoItem.is_checked = (xpath_object.getAttribute('is_checked') == '1') ? true:false;
    },
    
    /**
     * Save the edited activity item
     */
    edit_submit: function(){
        oid = $j('#id_activity_id_edit').val();
        parent_id = $j('#id_activity_parent_id_edit').val();
        new_title = $j('#id_activity_title_edit').val();
        is_checked = $j('#id_activity_is_checked_edit').val();
        
        $j($j('#id_'+oid).find('span')[1]).html(new_title);

        var close_time = $j('#id_activity_close_time').val();
        
        
        // Parse out the member as a semi-colon separated string
        var checked_str = "";
        $j('#id_member_activity_list').children('input[type="checkbox"]').each(function(){
            if($j(this).get(0).checked ){
                checked_str += $j(this).val()+";";
            }
        });
        checked_str = checked_str.substring(0,(checked_str.length-1));

        var req = xdbc.addQue(xdbc.cmd('family_21'));
        req.setAttribute('sys:set_oid', oid);
        req.setAttribute('sys:set_parent_id', parent_id);
        req.setAttribute('sys:set_title', new_title);
        req.setAttribute('sys:set_is_checked', is_checked); // Not modified here, therefore using TodoItem.is_checked
        req.setAttribute('sys:set_close_time', close_time);
        req.setAttribute('sys:edit_participants', checked_str);
        req.setAttribute('sys:save', "");

        
        xdbc.exec(function(resp) {
            var return_object = resp.selectSingleNode('//item');
            TodoItem.populate_object_from_xpath(return_object);
            TodoItem.re_draw_activity();

        });
        TodoItem.oid_mem = null;
        
        $j('#simplemodal-container').find('.simplemodal-close').click();
        
        // Re-Fetch the xml content
        TodoList.content = null;
        TodoList.get_content();
        
        return false;
    },
    
    re_draw_activity: function(){
        // Re-painting the whole activity, nice and fail-proof, someone got tighter jquery syntax?
        $j('#id_'+TodoItem.oid).before('<div id="tmp_placer">&nbsp;OPlacer</div>');
        $j('#id_'+TodoItem.oid).remove();
        $j('#tmp_placer').after( TodoItem.get_html() );
        $j('#tmp_placer').remove();
        /*$j('#id_'+oid)
            .before( TodoItem.get_html() )
            .remove();*/
    
    },
    
    /**
     * Handles all HTML for presenting an activity
     */
    get_html: function(){
        if(TodoItem.oid == ''){
            return '';
        }
        
        //html += '<div style="overflow: auto; height: 240px;" class="todo_row" id="eTodoRows">';
        events  = 'onmouseover="TodoItem.over('+TodoItem.oid+');" ';
        events += 'onmouseout="TodoItem.out('+TodoItem.oid+');" ';
        
        check_box_properties = (TodoItem.is_checked == '1') ? 'checked="true" class="check-box checked"':'checked="false" class="check-box green2"';
        custom_styles  = '';
        custom_styles += (TodoItem.is_checked) ? 'text-decoration:line-through;':'';
        custom_styles += (TodoItem.event_has_past) ? 'color:red;':'';
        
        close_time_html = (TodoItem.close_time) ? ' ('+TodoItem.close_time+')':'';
        
        
        html = ''
        + '<div '+events+' style="'+custom_styles+'overflow:hidden;border-bottom: 1px dotted rgb(204, 204, 204); margin: 5px 0px 5px 0px; padding: 2px 0px 2px 0px;" class="rowTitle" t_id="'+TodoItem.oid+'" id="id_'+TodoItem.oid+'" gtype="rowTitle" parent_id="'+TodoItem.parent_list+'">'
        + '<span style="float:left;"><img align="absmiddle2" onclick="TodoItem.check_toggle('+TodoItem.oid+');" '+check_box_properties+' src="/include/images/_.gif"/></span>'
        + '<span style="float:left; width:150px;">' + TodoItem.title + ''+close_time_html +'</span>'
        + '<span style="float:right;" class="item-tools-over">';
        
        html += '<a href="javascript:TodoItem.remove('+TodoItem.oid+')"><img src="/include/images/16/delete.png" border="0"/></a>'
        html += '<a href="#" onclick="TodoItem.edit('+TodoItem.parent_list+','+TodoItem.oid+');"><img src="/include/images/16/edit.png" border="0"/></a>'
        
        html += '</span></div>';
        //html += '<div style="border-bottom: 1px dotted rgb(204, 204, 204); margin: 5px; padding: 2px; height: 20px;" class="drowTitle" t_id="2629" id="id_2630" gtype="rowTitle">'+ TodoItem.title +'</div>';
        //html += '</div>';
        
        return html;
    },
    
    add: function(parent_list) {

        TodoItem.parent_list = parent_list;

        var req = xdbc.addQue(xdbc.cmd('family_14'));
        req.setAttribute('sys:add', TodoItem.title);
        req.setAttribute('sys:set_parent_id', TodoItem.parent_list);
        req.setAttribute('sys:set_oid', " ");

        xdbc.exec(function(resp) {
            var return_object = resp.selectSingleNode('//item');

            TodoItem.oid = return_object.getAttribute('id');
            parent_id = return_object.getAttribute('parent_id');

            TodoItem.is_checked = false;
            TodoItem.close_time = '';
            TodoItem.event_has_past = '';
            var number_of_items = $j('#easyTaskList_'+parent_id).children('.rowTitle').length;
            
            
            if(number_of_items > 0) {
                $j($j('#easyTaskList_'+parent_id).children('.rowTitle')[number_of_items-1]).after( TodoItem.get_html() );

            } else {
                $j('#easyTaskList_'+parent_list).html( TodoItem.get_html() );

            }
            
            // Append the new todo item activity to the xml, parent_id todo list
            var todo_list = TodoList.content.selectSingleNode('//todo_list[@id="' + parent_id + '"]');
            todo_list.appendChild(return_object);
        });

        return false;
    },
        
    html: function(text, id){
         //return '<div gtype="rowTitle" id="'+id+'" class="rowTitle">&nbsp; '+ text +'</div>';
    },
    
    toString: function(){
        string = 'TodoItem('
        + 'oid='+TodoItem.oid
        + ', title='+TodoItem.title
        + ', parent_list='+TodoItem.parent_list
        + ', close_time='+TodoItem.close_time
        + ', event_has_past='+TodoItem.event_has_past
        + ', is_checked='+TodoItem.is_checked
        + ')';
        return string
    }
    
}




/**
 * The Todolist - container for activities
 * 
 */
var TodoList = {
    id:'',
    title:'',
    parent_id:'',
    todo_items:null,
    content:null,
    
    init: function(parent_id){
        TodoList.parent_id = parent_id;
    },

    get_content: function(){
        // Fetch the xml content
        if(TodoList.content == null){
            var req = xdbc.addQue(xdbc.cmd('family_16'));
            req.setAttribute('sys:set_parent_id', TodoList.parent_id);
            req.setAttribute('sys:fetch_all', "df");

            xdbc.exec(function(resp) {
                TodoList.content = resp;
                //TodoItem.render_added(resp);
                /*
                var todo_lists = TodoList.content.selectNodes('//todo_list');

                if( todo_lists.length>0 ) {
                    for( var i = 0; i < todo_lists.length; i++ ) {
                        var id = todo_lists[i].getAttribute('id');
                        var items = TodoList.content.selectNodes('//todo_list[@id="'+id+'"]/item');
                        var participants = TodoList.content.selectNodes('//todo_list[@id="'+id+'"]/participant');
                        
                        //var items = TodoList.content.selectNodes('//todo_list/item');
                        //var items = todo_lists.selectNodes('//item');


                        // Loop the Todo Items
                        if( items.length>0 ) {
                            var html = '';
                            for( var j = 0; j < items.length; j++ ) {
                                html += items[j].getAttribute('title') + '<br>';
                                var item_id = items[j].getAttribute('id');
                                var item_title = items[j].getAttribute('title');

                            }
                        }
                        // Loop the Participants
                        if( participants.length>0 ) {
                            var html = '';
                            for( var j = 0; j < participants.length; j++ ) {
                                html += participants[j].getAttribute('title') + '<br>';
                                var participant_id = participants[j].getAttribute('participant_id');

                            }
                        }
                    }
                }*/
                
                eDesktop.widget.init($j('#widgetContainer').attr('container_id'));
            });
        }
        
    },

    /**
     * Send as a SMS or Email to yourself
     * @param ID: <todolist_id>
     * @param type: email|SMS
     */
    send_as: function(id, type){
        /*
        if(type=='SMS') {
            txt = ' som ett SMS?';
        } else {
            txt = ' till din epostaddress?';
        }*/
        
        if( site.user.phone_mobile=="" ) {
            alert('Du har inte angett mobiltelefonnummer, ange det under kontoinställningar.');
            return false;
        }
        
        var req = xdbc.addQue(xdbc.cmd('family_18'));
        req.setAttribute('sys:set_parent_id', TodoList.parent_id);
        req.setAttribute('sys:set_id', id);
        req.setAttribute('sys:send_as', type);

        xdbc.exec(function(resp) {
            var return_object = resp.selectSingleNode('//TodoList/todo_list');
            status = return_object.getAttribute('status');
            if(status == 'ok' ){
                alert('Att-göra-listan skickad');
            } else if(status == 'nocredits') {
                alert('Du har inte tillräckligt med SMS för att skicka Att-göra-listan.');
            } else {
                alert('Att-göra-listan kunde inte skickas. Kontrollera telefonnumret.');
            }
            
        });
        return false;
    },
    
    get_items: function(){
        
    },
    
    
    persistance: {
        set_id: function(id){
            TodoList.id = id;
        },
        
        /**
         * Save to database
         * When adding and editing a Todo List
         * When submitting the form
         */
        save: function(){
            
            
            var id = $j('#id_list_id_edit').val();
            todo_list_id = $j('#id_list_id_edit').val();
            var title = $j('#id_list_title_edit').val();
            
            if(title == ''){
                alert('Var god ange ett namn på Att-Göra-Listan');
                $j('#id_list_title_edit').focus();
                return false;
            }

            // Parse out the member as a semi-colon separated string
            var checked_str = "";
            $j('#id_member_list').children('input[type="checkbox"]').each(function(){
                if($j(this).get(0).checked ){
                    checked_str += $j(this).val()+";";
                }
            });
            checked_str = checked_str.substring(0,(checked_str.length-1));
            
            var req = xdbc.addQue(xdbc.cmd('family_15'));
            req.setAttribute('sys:set_parent_id', TodoList.parent_id);
            if(id == ''){
                // ADD
                req.setAttribute('sys:set_id', 'NULL');
            } else {
                // EDIT
                req.setAttribute('sys:set_id', id);
            }
            req.setAttribute('sys:set_title', title);
            req.setAttribute('sys:set_participants_str', checked_str);
            req.setAttribute('sys:save','');

            xdbc.exec(function(resp) {

                var return_object = resp.selectSingleNode('//TodoList/todo_list');
                
                TodoList.persistance.set_id( return_object.getAttribute('id') );
                
                /*
                if(TodoList.content == null){
                    TodoList.content = resp;
                } else {
                    // Append the new xml to the content
                    TodoList.content.appendChild(return_object);
                }*/
                
                if(todo_list_id == ''){
                    // ADD
                    TodoList.content.appendChild(return_object);
                    TodoList.add_widget_dyn();
                } else {
                    // EDIT
                    // Search the node and set the attributes
                    var todo_list = TodoList.content.selectSingleNode('//todo_list[@id="'+todo_list_id+'"]');
                    todo_list.setAttribute('title',title);

                    //var participants = TodoList.content.selectNodes('//todo_list[@id="'+todo_list_id+'"]/participant');
                    
                    participants = return_object.selectNodes('//participant');
                    db_participants = todo_list.selectNodes('//participant');
                    
                    // Remove all participants first
                    if(db_participants.length > 0){
                        for(var i=0; i < db_participants.length; i++){
                            db_participants[i].parentNode.removeChild(db_participants[i]);
                        }
                    }
                   
                    // Add participants according to return object
                    if(participants.length > 0){
                        for(var i=0; i < participants.length; i++){
                            todo_list.appendChild(participants[i])
                        }
                    }

                    // Post save - gui specific
                    $j('#TaskList_'+id+'Widget').find('.widget-header > strong').html(title);
                }
                
            });
            
            // Post save - gui specific
            $j('#simplemodal-container').find('.simplemodal-close').click();
            return false;
        },
    },

    edit_widget: {
        
        /**
         * This function is called from jquery.easywidgets.js
         * Also used for adding widget
         */
        show_modal: function (obj){
            
            if(obj == null){
                // ADD
                modalLayer('id_modal_todo_list', true, 260);
                $j('#id_modal_todo_list_label').html('L&auml;gg till lista');
                $j('#id_list_id_edit').val('');
            } else {
                // EDIT
                // Extract the TodoList ID
                parent_div = $j($j($j(obj.parent()[0]).parent()[0]).parent()[0]);
                var widget_id = parent_div.attr('id');
                element_id = widget_id.replace(/\D/gi, function(sMatch) {
                    return sMatch.replace(/./g, "");
                });
                var title = parent_div.find('.widget-header > strong').text();
                
                modalLayer('id_modal_todo_list', true, 260);
                $j('#id_modal_todo_list_label').html('&Auml;ndra lista');
                
                $j('#id_list_id_edit').val( element_id );
                $j('#id_list_title_edit').val( title );
                
                $j('#id_member_list > input').each(function(i){
                    var field_value = $j(this).val().split('-');
                    
                    if( TodoList.edit_widget.search_participant(element_id, field_value[1]) ){
                        $j(this).attr('checked','checked');
                    }
                });
            }
            return true;
        },
        
        /**
         * Search for current participants for this <id>Todo List
         */
        search_participant: function(todolist_id, participant_id_to_check){
            var checked_participants = TodoList.content.selectNodes('//todo_list[@id="'+todolist_id+'"]/participant');
            for( var j = 0; j < checked_participants.length; j++ ) {
                if(participant_id_to_check == checked_participants[j].getAttribute('participant_id') ){
                    return true;
                }
            }
            return false;
        },
        /**
         * Returning the html for the member list
         */
        participants_html: function(todolist_id){
            
            html = '';
            for(i=0; i < js_member_list.length; i++){
                user_id = js_member_list[i]['user_id'];
                name = js_member_list[i]['name'];
                html += '<input type="checkbox" name="participants[]" id="participant_'+user_id+'" value="4-'+user_id+'"';
                if(TodoList.edit_widget.search_participant(todolist_id, user_id)){
                    html += 'checked="checked"';
                }
                html += '/>\n';
                html += '<label for="participant_'+user_id+'">'+name+'</label><br />\n\n';
            }
            return html;
        }
    },
    
    /**
     * Currently not in use
     */
    edit_widget_html_OLD: function(id, title){
        html = '<div><form onsubmit="return TodoList.edit_title('+id+');"><input type="text" value="'+title+'" id="id_edit_title_'+id+'" />'
        + '<img src="/include/images/16/button_ok.png" onclick="TodoList.edit_title('+id+');"/></div>'
        + '</form>'
        + '<div><a href="javascript: TodoList.add_task_list_fronpage('+id+');">L&auml;gg till p&aring; framsidan</a></div>'
        + '<h3>Beh&ouml;righet</h3>'
        + '<form onsubmit="return TodoList.persistance.save_participants(this,'+id+');">'
        + TodoList.edit_widget.participants_html(id)
        + '<input type="submit" value="Spara">'
        + '</form>'
        + '<div style="border-bottom:1px dashed #BBBBBB;margin-right:10px;">&nbsp;</div>';
        return html;
    },
    
    /**
     * Add an new todo item to the task list
     */ 
    add_item: function(id){
        
        TodoList.id = id;
        TodoItem.title = $j('#todo_caption_'+id).val();
        TodoItem.add(id);
        
        $j('#todo_caption_'+id).val('');
        return false;
    },
    
    add_widget_dyn: function(){
        //location.href='?get=todoList&action=lists#TaskList_' + TodoList.id + 'Widget';
        //location.href='?get=todoList&action=restore_widgets';
        AddWidgetDyn('TaskList', TodoList.id, 'widget-place-1', TodoList.title, 1);
    },
    
    /**
     * Search the xml data and return matching activity (todo item)
     */
    get_activity: function(list_id, id){
        //var activity = TodoList.content.selectNodes('//todo_list[@id="'+list_id+'"]/item');
        var activity = TodoList.content.selectSingleNode('//todo_list/item[@id="'+id+'"]');
        return activity;
    },
    
    /**
     * Hypra function to inspect the ledgah
     */
    debug_dump_xml: function(){
        html = '<div id="sdfsd" style="border:4px solid black; position:absolute; top:200px; width:600px; left:10px; background-color:black; color:ivory; font-weight:bold;">';
        
        var todo_lists = TodoList.content.selectNodes('//todo_list');

        if( todo_lists.length>0 ) {
            for( var i = 0; i < todo_lists.length; i++ ) {
                var id = todo_lists[i].getAttribute('id');
            
                var items = TodoList.content.selectNodes('//todo_list[@id="'+id+'"]/item');
                var participants = TodoList.content.selectNodes('//todo_list[@id="'+id+'"]/participant');
                
                
                html += 'todo_lists id = '+todo_lists[i].getAttribute('id')+' :: ';
                html += 'title = '+todo_lists[i].getAttribute('title');
                html += '<br>';
                
                // Loop the Todo Items
                if( items.length>0 ) {
                    for( var j = 0; j < items.length; j++ ) {
                        //html += items[j].getAttribute('title') + '<br>';
                        var item_id = items[j].getAttribute('id');
                        var item_title = items[j].getAttribute('title');
                        
                        item_participants = TodoList.content.selectNodes('//item[@id="'+item_id+'"]/participant');
                        if( item_participants.length>0 ) {
                            for( var p = 0; p < item_participants.length; p++ ) {
                                html += '&nbsp; &nbsp; &nbsp; &nbsp; item participant_id='+item_participants[p].getAttribute('participant_id');
                                html += '<br>';
                            }
                        }
                        
                        html += '&nbsp; &nbsp; item id = '+item_id+' :: title='+item_title;
                        html += '<br>';

                    }
                }
                // Loop the Participants
                if( participants.length>0 ) {
                    //var html = '';
                    for( var j = 0; j < participants.length; j++ ) {
                        //html += participants[j].getAttribute('title') + '<br>';
                        var participant_id = participants[j].getAttribute('participant_id');
                        html += '&nbsp;LISTA participant_id = '+ participant_id +'';
                        html += '<br>';

                    }
                }
                html += '-----------------------------<br><br>';
            }
        }
        
        
        html += '</div>';
        $j('body').append(html);
        location.href='#sdfsd';
    
    }

}



function forumWatchThread(thread_oid) {
    var cmd = parent.xdbc.addQue(parent.xdbc.cmd('message_03'));
    cmd.setAttribute('sys:watch_thread', thread_oid);
    var response = parent.xdbc.exec();
    document.location.reload();
}

function forumUnWatchThread(thread_oid) {
    var cmd = parent.xdbc.addQue(parent.xdbc.cmd('message_03'));
    cmd.setAttribute('sys:unwatch_thread', thread_oid);
    var response = parent.xdbc.exec();
    document.location.reload();
}

function sendCalendarAgenda() {
    
    if( site.user.phone_mobile=="" ) {
        alert('Du har inte angett mobiltelefonnummer, ange det under kontoinställningar.');
        return false;
    }
    
    $j.get('/?get=calendar&action=agenda&print=1&text=1', function (resp) {

        var chars = 0;
        var last_part = 0;
        for( var i = 0; i<resp.length; i++ ) {
            
            chars++;
            if( chars>140 || (resp.length-1)==i ) {
                var sms_part = resp.substring(last_part, (last_part+chars));
                var last_part = last_part+chars;
                chars = 0;
                
                sms_part = sms_part.replace(/\n/g, '[CRLF]');
                var cmd = parent.xdbc.addQue(parent.xdbc.cmd('sms_01'));
                cmd.setAttribute('sys:enable_credit_check_ledger', 'on');
                cmd.setAttribute('sys:set_number', site.user.phone_mobile);
                cmd.setAttribute('sys:set_message', sms_part);
                
                parent.xdbc.exec(function(resp){
                    // Fetching with jquery, loggin the sent SMS
                    var result = $j('result', resp); // Since we have a single node, this syntax works fine
                    var number = result.attr('number');
                    var status = result.attr('status');
                    
                    jledger_call('<SmsLog _cmdId="smslog_02" sys:set_sent_to_number="'+number+'" sys:set_status="'+status+'" sys:save="1"></SmsLog>', null);
                    
                    if(status == 'fail'){
                        alert("Kunde inte leverera SMS:et till nummer: " + number);
                    } else if(status == 'nocredits'){
                        alert("Kunde inte leverera SMS:et. Inga SMS-krediter");
                    } else {
                        alert("SMS:et skickades till nummer: " + number);
                    }
                });
            }
        }
    });
    return false;
}

/**
 * Use this SMS js-class to send text message with AJAX
 *
 */
var Sms = {
    dialog: function(nr, event) {
        /* wtf is the intended use of this */
        $('sms_window').style.display='';
        $('sms_nr').value = nr;
        $('sms_message').value = '';
        $('sms_send_button').disabled = false;
    },
    reset: function(){
        $j('#sms_send_button').attr('disabled','');
    },
    send: function() {
       
        /* Calling the jquery way instead, ledger preload independent aswell as xdbc.. */
        jledger_call('<Sms _cmdId="sms_01" sys:set_number="'+ $j('#sms_nr').val() +'" sys:set_message="'+ $j('#sms_message').val() +'" sys:enable_credit_check_ledger="on" sys:send=""></Sms>', function(resp){
            // Fetching with jquery, loggin the sent SMS
            var result = $j('result', resp); // Since we have a single node, this syntax works fine
            var number = result.attr('number');
            var status = result.attr('status');
            jledger_call('<SmsLog _cmdId="smslog_02" sys:set_sent_to_number="'+number+'" sys:set_status="'+status+'" sys:save="1"></SmsLog>', null);
            
            if(status == 'fail'){
                alert("Kunde inte leverera SMS:et till nummer: " + number);
            } else if(status == 'nocredits'){
                alert("Kunde inte leverera SMS:et. Inga SMS-krediter");
            } else {
                alert("SMS:et skickades till nummer: " + number);
            }
        });
        
        $j('#simplemodal-container').find('.simplemodal-close').click();
        Sms.reset();
        return false;  
        
        /*
        var cmd = parent.xdbc.addQue(parent.xdbc.cmd('sms_01'));
        cmd.setAttribute('sys:set_number', $('sms_nr').value);
        cmd.setAttribute('sys:set_message', $('sms_message').value);
        var response = parent.xdbc.exec();
        
        */

/*        resultcode = resp.selectSingleNode('//Sms/result');
        console.debug(resultcode);
                                          */
        /*
        if (resultcode[0].getAttribute('status') == 'ok')
        {
      */
            //site.close_edit_popup();
            
            
        /*
        }
        else
        {
            alert('SMS:et kunde ej skickas'); // XXX: translate!!!
        }
      */
      
    }
}


$j(document).ready(function(){
    
    $j('#id_temp_send_email').click(function(){
        
        href = $j(this).attr('href');
        
        msg = confirm("Vill du skicka agendan till din epostaddress?");
        if(!msg){
            return false;
        }
        
        $j.getJSON(href, function(resp){
            //console.debug('Done: ' + resp['success']);
            if(resp['success'] == 'True'){
                alert('Agendan skickades till din epostaddress.');
            }
        });
        return false;
    });
    
    /**
     * Add some behaviour for site.tpl.html c:a line 285
     * We want to make the links (that load the iframe) bold when clicked
     * Using global mem to remember last clicked link, for toggle behaviour..
     */
    var global_var_mem = $j($j('.agenda_links')[0]);
    $j('.agenda_links').click(function(){
        $j(this).css('outline','none');
        if( $j(this).css('text-decoration') != 'underline' ){
            $j(this).css('text-decoration','underline');
            global_var_mem.css('text-decoration','none');
            global_var_mem = $j(this);
        }
    });
    
    var global_var_mem2 = $j($j('.cls_calendar_selector')[0]);
    $j('.cls_calendar_selector').click(function(){
        $j(this).css('outline','none');
        if( $j(this).css('text-decoration') != 'underline' ){
            $j(this).css('text-decoration','underline');
            global_var_mem2.css('text-decoration','none');
            global_var_mem2 = $j(this);
        }
        return eCalendar.list_view( $j(this).attr('href') );
    });
    
    
});

/**
 * This is the jquery way of interacting with our ledger.
 * Supply your call_back that may look something like: my_test_callback(resp) or
 * write it inline.
 * TODO: Lift this out to a very global place
 *
 * @param post_xml <String> ie [ '<SmsCredit _cmdId="smscredit_01" sys:save="'+quantity+'"/>' ]
 * @param callback <Function>
 * @param debugging <Boolean> [ optional ]
 *
 */
jledger_call = function(post_xml, call_back, debugging){
    var ledger_location = 'index.php?get=xmlapi';
    var post_xml_full = '<data xmlns:sys="http://www.easyinteraction.se/sys" xmlns:docs="http://www.easyinteraction.se/docs">'
    + post_xml
    + '</data>';
    if(debugging){
        console.debug('POSTED:'); console.debug( post_xml_full );
    }
    $j.post(ledger_location, post_xml_full, call_back, "xml");
    // or
    /*$j.ajax({
		type: "POST",
		data: post_xml_full,
		url: ledger_location,
		dataType: "xml",
		success: call_back
	});*/
}



