// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
// Top Menu
function checkBrowser(){

	window.location="http://www.taskedit.com/main/incompatible_browser_type";
}


function updateCounter(d, i, k) {
    elName = 'counter' + i + k;
    $(elName).innerHTML = d;
}

function displayHelp(){
    opt = {
        method: 'post'
    };
    new Ajax.Request('/home/display_help', opt);	
	
}

function confirmClearArchives() {
    Modalbox.show("<p>All archived tasks will be removed.</p>" + "<span class='form_button' onclick=clearLogs()>Yes</span>" + "<span class='form_button' onclick=Modalbox.hide()>Cancel</span>", {
        title: "<p>Clear Archives.</p>",
        width: 300
    });
}



function clearLogs() {
    Modalbox.hide();
    $('display').select('.task[completed=1]').invoke('hide');
    opt = {
        method: 'post'
    };
    new Ajax.Request('/home/clear_archives', opt);
}
// TASK
function loggedInfoDisplay(owned, notOwned) {
    $('MB_content').update("<p class='modal_box_feedBack'>" + owned + " task were put in reports.</p><p modal_box_feedBack>" + notOwned + " assigned tasks are waiting for the owner action.</p>");
    Modalbox.resizeToContent();
}
var lastClick = 0;
tempo = null;

function clickTest(id) {
    var time = new Date().getTime();
    v = time - lastClick;
    if (time - lastClick < 2000) {
        editTaskTitle(id);
        lastClick = 0;
        clearTimeout(tempo);

    }
    else {

        lastClick = time;
        setTimeout("ShowTask(" + id + ")", 250);

    }

}



function ShowTaskWithTimeOut(id) {

    if (tempo == null) {
        tempo = setTimeout("ShowTask(" + id + ")", 350);
    }

}



function ShowTask(id) {
    closeProjectListIfOpen(id);
    closePriorityListIfOpen(id);
    closeCalendarIfOpen(id);
    elName = $('task_' + id);
    target = $(elName).select('.task_body').first();
    visible = target.visible();
    //$$('.task_body').invoke('hide');
    if (visible == false) {
        target.show();
        displayTime($('task_' + id));

    }
    if (visible == true) {
        target.hide();
    }
    window.clearTimeout(tempo);
    tempo = null

}



function displayTime(el) {
//	tzo = new Date().getTimezoneOffset()*60000
    beginAttr = el.readAttribute('begin');
    endAttr = el.readAttribute('end');
    begin = prettyDate(beginAttr * 1000);
    end = prettyDate(endAttr * 1000);
    begin_end = el.select('.task_date');
    begin_end[0].innerHTML = begin;
    begin_end[1].innerHTML = end;

}



function prettyDate(time) {
	timezo = new Date().getTimezoneOffset()*60000

    if ((time / 1000) < 0) return "";


    diff = (( (new Date().setHours(0,0,0,0) -timezo)  - (time+0)) / 1000),
//alert(diff/3600);
   (diff < 0) ? (day_diff=Math.ceil(diff / 86400)) : (day_diff=Math.ceil(diff / 86400))

  
    date = new Date(time+timezo);
//alert(date)
    if (day_diff < -5 || day_diff >= 31) return Calendar.printDate(date, "%A  %d %B");
    if (day_diff == 0) return 'today';
    if (day_diff == -1) return 'tomorrow';
    if (day_diff == -1 || day_diff == -2 || day_diff == -3 || day_diff == -4 || day_diff == -5) return Calendar.printDate(date, "%A");
    if (day_diff == 1) return 'yesterday';
    if (day_diff < 7) return day_diff + " days ago";
    if (day_diff < 31) return Math.ceil(day_diff / 7) + " weeks ago";

}



function createTask() {
    row = $('left_column').select('div[markSelected=yes]').first();
    if (row) indexString = row.readAttribute('index');
    else indexString = '11';
    index = parseInt(indexString);
    if (index == 0 || index == 2 || (index < 19 && index > 9)) {
        MarkSelected('01');
        indexString = '01';
    }
    opt = {
        method: 'post',
        postBody: 'index=' + indexString
    }
    new Ajax.Request('/home/create_task', opt);

}



function createProject() {
    quitEditMode();
    closeProjectNameEditings();
    opt = {
        method: 'post'
    };
    new Ajax.Request('/home/new_project', opt);

}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}


function sort(tag) {

    if (tag == 'priority') array = $$('.task').sort(sortPriority);
    if (tag == 'begin') array = $$('.task').sort(sortBegin);
    if (tag == 'end') array = $$('.task').sort(sortEnd);

    

    array.each(function (el) {

        Element.insert('display', {
            bottom: el
        });


    });

}



function sortPriority(elA, elB) {
	     
    a = elA.readAttribute('priority');
    b = elB.readAttribute('priority');

    return b - a;

}



function sortBegin(elA, elB) {
    a = elA.readAttribute('begin');
    b = elB.readAttribute('begin');

    answer = a - b;

    if (a == -1 || b == -1) answer = 1;

    return answer;
}



function sortEnd(elA, elB) {
    a = elA.readAttribute('end');
    b = elB.readAttribute('end');

    answer = a - b;

    if (a == -1 || b == -1) answer = -1;

    return answer;

}

function checkIfEditMode(index){

	if (index < 20) {quitEditMode();return true}
	else{
		
	if ($('drawer2').readAttribute('editMode')==1) return false 	
	else{
		return true
	}
		
	} 
	
	
	
}

function editProjects(option) {

    editMode = $('drawer2').readAttribute('editMode');
    if (editMode == 1 && option==null) {
        quitEditMode()

    }

    else {

       $('drawer2').select('.project_edit').invoke('hide')
		$('drawer2').select('span').invoke('show')
     
        Sortable.create('drawer2', {
            tag: 'div',
            onUpdate: function () {
                array = $('drawer2').select('div.sort_div').pluck('id');
                opt = {
                    method: 'post',
                    postBody: 'array=' + array
                };
                new Ajax.Request('/home/reorder_projects', opt);

            }

        });
		
        deleteControl = "<a class='deleteControl'><img src='/images/delete_project.png' onClick=deleteProject(this);Event.stop(event)></a>"
        $('drawer2').writeAttribute({
            editMode: 1
        });
        $('drawer2').select('a div').each(function (el) {

            el.select('img.left_column_img').invoke('writeAttribute', {
                src: "/images/rowSort.png"
            });
            el.select('p.counter').invoke('hide');
            Element.insert(el, {
                bottom: deleteControl
            });
            //el.setStyle({backgroundColor: '#a9adb7'});
            //	el.down('div').writeAttribute('setStyle',{backgroundColor: '#a9adb7'});
        });
    }
}



function quitEditMode() {
    $('drawer2').writeAttribute({
        editMode: 0
    });

    $('drawer2').select('a div').each(function (el) {
        Sortable.destroy('drawer2');
        el.select('img.left_column_img').invoke('writeAttribute', {
            src: "/images/2.png"
        });
        el.select('p.counter').invoke('show');
        el.select('a.deleteControl').invoke('remove');
        //el.setStyle({backgroundColor: '#a9adb7'});
        //	el.down('div').writeAttribute('setStyle',{backgroundColor: '#a9adb7'})
    });
}



function showHideCompleted() {
    el =$('display')

	if (el)
	{
   	display='yes'
    completedMode = el.readAttribute('showCompleted');

    completedMode == '1' ? (new_mode = 0) : (new_mode = 1);
    $('display').writeAttribute('showCompleted', new_mode);
    index = $$('div[markSelected=yes]').first().readAttribute('index');

    if (index != '02') {
        if (completedMode == 0) $$('.task').invoke('show');
        if (completedMode == 1) $$('.task[completed=1]').invoke('hide');

    }
}

    else{display='no'}
    opt = {
        method: 'post',postBody: 'display_presence='+display
    };
    new Ajax.Request('/home/switch_completed_mode', opt);
}



function ConfirmDeleteProject(id, task_count) {

    Modalbox.show("<p>All tasks from this project will alsor be removed.</p>" + "<span class='form_button' onclick=deleteProject(" + id + ")>Yes</span>", {
        title: "<p>Delete projects and it tasks</p>",
        width: 400
    });

}



function deleteProject(t) {

    row = t.up('div').up('div');
    project_id = t.up('div').readAttribute('project_id');

    $(row).slideUp();
    $(row).fade();
$('main_display').update("");
    opt = {
        method: 'post',
        postBody: 'id=' + project_id
    };
    new Ajax.Request('/home/delete_project', opt);


}



function checkUncheckTask(id) {
    el = $('task_' + id);
    completed = el.readAttribute('completed');

    if (completed == 1) newStatus = '0';
    else {
        newStatus = '1';
        $('leftColumnLine02').highlight();
    }
    el.writeAttribute({
        completed: newStatus
    })
    //cssClass = el.className;
    //if (cssClass == 'task'){el.removeClassName('task');el.toggleClassName('task_logged') };
    //if (cssClass == 'task_logged'){el.removeClassName('task_logged');el.toggleClassName('task') };
    $('check_uncheck_' + id).select('img').invoke('toggle');
    opt = {
        method: 'post',
        postBody: 'id=' + id
    };
    new Ajax.Request('/home/check_uncheck_task', opt);
}



function editTaskTitle(id) {
    window.clearTimeout(tempo);
    tempo = null;
    elName = 'task_' + id;
    text = $(elName).select('.task_title').first().toggle().innerHTML.stripTags().strip();
    $(elName).select('.task_title_edit').first().show().down('input').value = text;

}



function saveTaskTitle(id) {
    elName = 'task_' + id;
    new_value = $(elName).select('.task_title_edit').first().hide().down('input').value.stripTags().strip();
    $(elName).select('.task_title').first().show().update(new_value);
    opt = {
        method: 'post',
        postBody: 'id=' + id + '&id2=' + new_value
    };
    new Ajax.Request('/home/save_task_title', opt);
}



function cancelTaskTitleEditing(id) {
    elName = 'task_' + id;
    $(elName).select('.task_title_edit').first().hide();
    $(elName).select('.task_title').first().show();
}



function listTasks(index) {
    opt = {
        method: 'post',
        postBody: 'id=' + index
    };
    new Ajax.Request('/home/list_tasks', opt);
    MarkSelected(index);
}

// LEFT COLUMN
// Project 

function showDescriptionControl(id) {
    elName = 'task_' + id;
    $(elName).select('.task_description_edit').first().show();

}



function saveTaskDescription(id) {
    elName = 'task_' + id;
    area = $(elName).select('.task_description').first().down('textarea');
    new_value = area.value;
    opt = {
        method: 'post',
        postBody: 'id=' + id + '&id2=' + new_value
    };
    new Ajax.Request('/home/save_description', opt);
    new Effect.Highlight(area);
    closeDescriptionControl(id);
}



function closeDescriptionControl(id) {
    elName = 'task_' + id;
    $(elName).select('.task_description_edit').first().hide();
}



function rowDoubledClicked(index) {

    editMode = $('drawer2').readAttribute('editMode');
    if (editMode == 1) {
        quitEditMode()
		return

    }


    if (index > 19) {
        quitEditMode();
        MarkAllUnselected();
		$('drawer2').select('.project_edit').invoke('hide')
		$('drawer2').select('span').invoke('show')

        elName = "leftColumnLine" + index;
        text = $(elName).down('span').innerHTML.stripTags().strip();

        $(elName).select('.project_edit').first().down('input').value = text;
        text ? null : text = "";

        $(elName).writeAttribute({
            markSelected: 'no'
        });

        $(elName).down('span').hide();
        $(elName).down('p').hide();

        $(elName).select('.project_edit').first().show();

        $(elName).select('.project_edit').first().down('input').focus();

    }
}



function saveProjectName(id, index) {
    elName = "leftColumnLine" + index;
    new_value = $(elName).select('.project_edit').first().toggle().down('input').value.stripTags();
    $(elName).down('span').update(new_value).toggle();
    $(elName).down('p').show();
    opt = {
        method: 'post',
        postBody: 'id=' + id + '&id2=' + new_value
    };
    new Ajax.Request('/home/save_project_name', opt);
}



function cancelProjectEditing() {
    MarkAllUnselected();

}



function checkIfProjectCanBeDeleted(id) {
    opt = {
        method: 'post',
        postBody: 'id=' + id
    };
    new Ajax.Request('/home/check_if_project_can_be_deleted', opt);
}



function closeProjectListIfOpen(id) {
    elName = 'task_' + id;
    visible = $(elName).select('.task_project_edit').first().visible();
    if (visible == true) {
        $(elName).select('.task_project_edit').first().hide();
        $('project_list_' + id).previous().hide();
        return true;

    }
    if (visible == false) {
        return false
    };

}



function closePriorityListIfOpen(id) {
    elName = 'task_' + id;
    visible = $(elName).select('.task_priority_edit').first().visible();
    if (visible == true) {
        $(elName).select('.task_priority_edit').first().hide();
        $('priority_list_' + id).previous().hide();
        return true;

    }
    if (visible == false) {
        return false
    };

}



function openProjectList(id) {
    closeCalendarIfOpen(id);
    closePriorityListIfOpen(id);
    if (closeProjectListIfOpen(id) == false) {
        taskEl = 'task_' + id;
        list = $(taskEl).select('.task_project_edit').first().show();
        $('project_list_' + id).previous().show();
        list.update("");
        header = "<p class='list_header'><span>My projects</span><img src='/images/close_list.png' onClick=closeProjectList(" + id + ",event) /></p><br/>";
        Element.insert(list, {
            bottom: header
        });
        content2 = "<p onclick='saveProjectOfTask(" + id + ",0); Event.stop(event)'>Clear Project</p>";
        Element.insert(list, {
            bottom: content2
        });

        $('drawer2').select('div').each(function (el) {
            index = el.readAttribute('index');
            if (index) {
                text = el.down('span.left_column_header_text').innerHTML;
                content3 = "<p onclick='saveProjectOfTask(" + id + "," + index + "); Event.stop(event)'>" + text + "</p>";
                Element.insert(list, {
                    bottom: content3
                });
            }

        });

    }

}



function openPriorityList(id) {
    if (closePriorityListIfOpen(id) == false) {
        closeCalendarIfOpen(id);
        closeProjectListIfOpen(id);
        elName = 'task_' + id;
        $('priority_list_' + id).show();
        $('priority_list_' + id).previous().show();
    }
}



function closePriorityList(id, event) {
    elName = 'task_' + id;
    $(elName).select('.task_priority_edit').first().hide();
    $(elName).select('.box_arrow')[0].hide();
    Event.stop(event);

}

//this function is called after the server has updated the page with the list

function closeProjectList(id, event) {

    elName = 'task_' + id;
    $(elName).select('.task_project_edit').first().hide();
    $('project_list_' + id).previous().hide();
    Event.stop(event);
}



function saveProjectOfTask(taskId, index) {
    if (index == 0) index = '01';
    value = $('leftColumnLine' + index).down('span.left_column_header_text').innerHTML;
    if (index == '01') value = "no project";
    elName = 'task_' + taskId;
    $(elName).select('.task_project').first().update(value);
    $('project_list_' + taskId).previous().hide();
    $(elName).select('.task_project_edit').first().hide();

    row = $('leftColumnLine' + index).highlight();
    opt = {
        method: 'post',
        postBody: 'task_id=' + taskId + '&project_index=' + index
    };
    new Ajax.Request('/home/change_task_project', opt);

}



function savePriorityOfTask(taskId, numericValue, stringValue) {
    elName = 'task_' + taskId;
    $(elName).select('.task_priority').first().update(stringValue);
    $(elName).select('.task_body_img')[1].writeAttribute({
        src: "/images/taskimg/" + numericValue + ".png"
    });
    $('priority_list_' + taskId).previous().hide();
    $(elName).select('.task_priority_edit').first().hide();
    opt = {
        method: 'post',
        postBody: 'task_id=' + taskId + '&priority=' + numericValue
    };
    new Ajax.Request('/home/change_task_priority', opt);
}



function closeCalendarIfOpen(id) {

    elName = 'task_' + id;

    visible1 = $(elName).select('.iphonic').first().visible();
    visible2 = $(elName).select('.iphonic').last().visible();

    if (visible1 == true || visible2 == true) {
		$('calendar_begin_'+ id).up('div').previous().hide()
		$('calendar_end_'+ id).up('div').previous().hide()
        $(elName).select('.iphonic').first().update("").hide();
        $(elName).select('.iphonic').last().update("").hide();
        return true;

    }

    if (visible == false) {
        return false
    };

}



function callDynarchCalendar(id, type) {

	
    closeProjectListIfOpen(id);
    closePriorityListIfOpen(id);
  elName = 'task_' + id;
    visible1 = $(elName).select('.iphonic').first().visible();
    visible2 = $(elName).select('.iphonic').last().visible();    
	closeCalendarIfOpen(id) 
    if((type=='begin' && visible1== false)||(type=='end' && visible2== false))
 	{
        dateAttr = $('task_' + id).readAttribute(type);
		$('calendar_' + type + '_' + id).up('div').previous().show()

        date = new Date(dateAttr * 1000);
        if (dateAttr == -1) {
            date = new Date()
        }
        Calendar.setup({
            cont: ('calendar_' + type + '_' + id),
            weekNumbers: false,
            bottomBar: false,
            selectionType: Calendar.SEL_SINGLE,
            date: date,
            // select today
            selection: date,
            onSelect: function () {
				tzo = new Date().getTimezoneOffset()
                date = this.selection.get();
                date2 = Calendar.intToDate(date).setHours(0);

                closeCalendarIfOpen(id);

                el = $('task_' + id);

                if (type == 'begin') el.writeAttribute({
                    begin: ((date2/ 1000) - tzo*60)
                });
                if (type == 'end') el.writeAttribute({
                    end: ((date2/ 1000) - tzo*60)
                });
				$('calendar_' + type + '_' + id).up('div').previous().hide()
              displayTime(el)
                opt = {
                    method: 'post',
                    postBody: 'id=' + id + '&id2=' + date2 / 1000 + '&type=' + type +'&tzo=' +tzo
                };
                new Ajax.Request('home/update_duetime', opt);

            }

        });

        $('calendar_' + type + '_' + id).show();

    }
}

function openPreferences(){
	opt = {
        method: 'post'     
    };
    new Ajax.Request('/home/open_preferences', opt);
	
	
}


function editAccountInformation() {
    closeTopMenu();
    Modalbox.show(
    $('account_information_edit'), {
        title: "<p>Edit here your account.</p>",
        width: 330,
        height: 200
    });
}



function errorOnEditAccount(errorMessage) {

    $("form_error").replace("<div id='form_error'>Format error</div>");
    $("form_error").highlight();
}



function unfoldPanel(id, panelName) {
    opt = {
        method: 'post',
        postBody: 'task_id=' + id + '&panel_name=' + panelName
    };
    new Ajax.Request('/home/show_panel', opt);
}



function deleteThisNote(id, t) {
	
	if (!Prototype.Browser.IE) {

	    t.previous().hide();
	    t.hide();
	}
	else {
		
		$('delete_note_'+id).hide();
		$('task_thread_'+id).hide();

	}
	


    opt = {
        method: 'post',
        postBody: 'id=' + id
    };
    new Ajax.Request('/home/delete_this_note', opt);

}



function editThread(note_id, task_id) {

    thread = $('task_thread_' + note_id);
    if (note_id == '0') {
        value = "";
    }
    else {
        value = thread.innerHTML;
    }
    $('panel_1').down('textarea').value = value;
    $('panel_1').writeAttribute({
        note_id: note_id
    });
    $('panel_1').writeAttribute({
        task_id: task_id
    });
    $$('.panel').invoke('hide');
    $('panel_1').show();
    markPanelSelected(1);

}



function showPanel(index) {
    $$('.panel').invoke('hide');
    $('panel_' + index).show();
    Modalbox.resizeToContent();
    type = $('panel_1').down('textarea').readAttribute('type');
    if (! (type == "new_post")) {
        ($('panel_1').down('textarea').value = "");
    }
    markPanelSelected(index);

}



function saveNote() {
    edit_panel = $('panel_1');
    task_id = edit_panel.readAttribute('task_id');
    note_id = edit_panel.readAttribute('note_id');

    text = edit_panel.down('textarea').value;
    opt = {
        method: 'post',
        postBody: 'task_id=' + task_id + '&note_id=' + note_id + '&text=' + text
    };
    new Ajax.Request('/home/save_note', opt);

}



function cancelNoteEditing() {
    edit_panel = $('new_thread_db');
    task_id = edit_panel.readAttribute('task_id');
    opt = {
        method: 'post',
        postBody: 'task_id=' + task_id
    };
    new Ajax.Request('/home/show_threads', opt);
    $('html_db').hide();
    $('html_db').insert(edit_panel).hide();

}



function markPanelSelected(id) {

    $$('div.panel_menu[markPanelSelected="yes"]').invoke('writeAttribute', 'markPanelSelected', 'no');
    elName = 'panel_menu_' + id;
    $(elName).writeAttribute({
        markPanelSelected: 'yes'
    });

}



function MainDisplayclicked() {
    $$('.iphonic').invoke('hide');
    $$('.task_project_edit').invoke('hide');

}