function showFormByType(select_id){
    for( var i=0; i<$(select_id).options.length;i++){
        $($(select_id).options[i].value).className='form-row-hidden';
    }
    $($(select_id).options[$(select_id).options.selectedIndex].value).className='form-row';
}
function addTableRow(length, table){
    var table = $(table);
    var num_rows = table.rows.length;
    var row = table.insertRow(num_rows);
    for( var i =1; i<=length; i++){
       var newcell = row.insertCell(i-1);
       var t = document.createTextNode($('text_'+i).value);
       newcell.appendChild(t);
    }
}

function hideFlash(){
    if ($('flash')) {
     new Effect.Fade('flash', {'duration': 3});
    }
}
/*
* Generates an html table from a json string.
* Format: {headers: [],data:[[],[],[]]}
*/
function jsonToTable(form_element_id, json_string, delete_buttons){//alert(json_string);
    var my_table_data = json_string.parseJSON();
    var table = Builder.node('table', {"class": "Table-FORM-TABLE", 
                                         width: "100%", 
                                         border: "1",
                                         cellspacing: "0",
                                         cellpadding: "0"});
    var thead = Builder.node('thead');
    var tbody = Builder.node('tbody');
    var trh = Builder.node('tr');
    var headers_count = my_table_data["headers"].length;
    var th_width = (100 / (headers_count+1)).toString() + '%';
    for( var i=0, header; header = my_table_data["headers"][i]; i++){
        var th = Builder.node('th', {align: 'left', width: th_width});
        var tn = document.createTextNode(header);
        th.appendChild(tn);
        trh.appendChild(th);
    }
    var th = Builder.node('th', {align: 'left'});
    var tn = document.createTextNode("Action");
    //var add_tr = Builder.node('th', {id: 'row_add_to_table'});
    th.appendChild(tn);
    trh.appendChild(th);
    thead.appendChild(trh);
    thead.appendChild(trh);
    for( var i=0, dataset; dataset = my_table_data["data"][i]; i++){
        var tr = Builder.node('tr');
        for(var j=0, data; data = dataset[j]; j++){
            var td = Builder.node('td');
            var tn = document.createTextNode(data);
            td.appendChild(tn);
            tr.appendChild(td);
        }
        if(delete_buttons){
            var td = Builder.node('td', {"class": "overflow"});
            var delete_input = Builder.node('input', 
                                  {type: 'button',
                                  onclick: 'deleteTableRow('+form_element_id+', '+i+')',
                                  value: 'Del'});
            td.appendChild(delete_input);
            tr.appendChild(td);
        }
        tbody.appendChild(tr);
    }
    table.appendChild(thead);
    table.appendChild(tbody);
    return table;
}

function insertAtCursor(myField, myValue) {
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
	} else {
		myField.value += myValue;
	}
}

function markdownImage(formObj, url) {
	insertAtCursor(formObj, '![]('+url+')')
}

function markdownLink(formObj, url) {

	var ret = prompt('Please enter the link title');

	if(ret) {
		insertAtCursor(formObj, '['+ret+']('+url+' "'+ret+'")');
	}
}

function getWindowHeight() {
    var windowHeight=0;
    if (typeof(window.innerHeight)=='number') {
        windowHeight=window.innerHeight;
    }
    else {
        if (document.documentElement&&
            document.documentElement.clientHeight) {
                windowHeight=    document.documentElement.clientHeight;
            }
        else {
            if (document.body&&document.body.clientHeight) {
                windowHeight=document.body.clientHeight;
            }
        }
    }
    return windowHeight;
}
function returnBrowserDimensions() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth,myHeight];
}
function displaySiteMap(){
    var b_dim = returnBrowserDimensions();
    $('site_map').style.display="block";
    $('site_map_overlay').style.display="block";
    var browser_width = b_dim[0];
    var browser_height = b_dim[0];
    var height = Element.getHeight('site_map');
    var horizontal_indent =  ((browser_width-600)/2)/browser_width*100;
    var vertical_indent = ((browser_height-height)/2)/browser_height*100;
    var horizontal_overlay_indent = horizontal_indent + 2;
    var vertical_overlay_indent = vertical_indent + 2;
    
    $('site_map').style.left = horizontal_indent.toString()+"%";
    //$('site_map').style.top = vertical_indent.toString()+"%";
    
    $('site_map_overlay').style.left = "0%";
    $('site_map_overlay').style.top = "0%";
    $('site_map_overlay').style.height = browser_height.toString()+"px";
    $('site_map_overlay').style.width = browser_width+"px";
}
function hideSiteMap(){
   $('site_map').style.display="none";
   $('site_map_overlay').style.display="none";
}

function toggleShowSiteMap(){
    var url = '/users/toggle_panel';
    var myAjax = new Ajax.Request(url, {
        method: 'get', 
        parameters: '',
        onSuccess: function(originalRequest){},
        onFailure: function(){alert('Technical error.');}
    });
}

function filterByProject(count){
    url = '/calendar/?';
    url += 'project_filter=' + $('project_filter').options[$('project_filter').selectedIndex].value;
    url += '&contributor_filter=' + $('contributor_filter').options[$('contributor_filter').selectedIndex].value;
    self.location = url;
}

function filterByContributor(count){
    url = '/calendar/?';
    url += 'contributor_filter=' + $('contributor_filter').options[$('contributor_filter').selectedIndex].value;
    url += '&project_filter=' + $('project_filter').options[$('project_filter').selectedIndex].value;
    self.location = url;
}

function enableProvinces(){
    if($('country_id').options[$('country_id').selectedIndex].value==197){
        $('province_id').disabled=false;
    }
}

function redirect(url){
    self.location = url;
}

function filterContacts(url){
    var order = $('order').options[$('order').selectedIndex].value;
    url += '?order=' + order;
    if($('search_phrase')){
        if($('search_phrase').value != ''){
            url += '&search_phrase=' + $('search_phrase').value;
        }
    }
    if($('forms_filter')){
        if($('forms_filter').value != ''){
            url += '&forms_filter=' + $('forms_filter').value;
        }
    }
    if($('projects_filter')){
        if($('projects_filter').value != ''){
            url += '&projects_filter=' + $('projects_filter').value;
        }
    }
    if($('concat_filter')){
        if($('concat_filter').value != ''){
            url += '&concat_filter=' + $('concat_filter').value;
        }
    }
    self.location = url;
}

function getFilterQueryString(){
    var order = $('order').options[$('order').selectedIndex].value;
    var url = '&order=' + order;
    if($('search_phrase')){
        if($('search_phrase').value != ''){
            url += '&search_phrase=' + $('search_phrase').value;
        }
    }
    if($('forms_filter')){
        if($('forms_filter').value != ''){
            url += '&forms_filter=' + $('forms_filter').value;
        }
    }
    if($('projects_filter')){
        if($('projects_filter').value != ''){
            url += '&projects_filter=' + $('projects_filter').value;
        }
    }
    return url;
}


function linkContactToProject(contact_id, project_id, sub_process_id){
    self.location = '/projects/link_contact_to_project/' + contact_id + '/' + project_id + '/' + sub_process_id + '/' + getFilterQueryString();
}

function unlinkContactFromProject(contact_id, project_id, sub_process_id){
    self.location = '/projects/unlink_contact_from_project/' + contact_id + '/' + project_id + '/' + sub_process_id + '/' + getFilterQueryString();
}

function delete_contact(){
    $('form').action='/contacts/save/delete';
    $('form').submit();
}

//Dashboard project filter
function order_dashboard(field){
    var order = field.options[field.selectedIndex].value;
    if(order!=-1){
        self.location = '/dashboard/?order=' + order;
    }
}

//Dashboard project filter
function filter_dashboard(field){
    var filter = field.options[field.selectedIndex].value;
    if(filter!=-1){
        self.location = '/dashboard/?filter=' + filter;
    }else{
        self.location = '/dashboard/?filter=all';
    }
}

function collapseAll(){
    var expanded = document.getElementsByClassName('visible_div');
    if(!expanded.length==0){
        for(var i=0, list; list=expanded[i]; i++){
            $(list).className = 'invisible_div';
            $(list).style.display = 'none';
        }
    }
}

function showDiv(id){
    $(id).style.display = 'block';
    $(id).className = 'visible_div';
}

function selectAll(select_elm){
    for(var i=0, opt; opt = select_elm.options[i]; i++){
        opt.selected=true;
    }
}
function selectNone(select_elm){
    for(var i=0, opt; opt = select_elm.options[i]; i++){
        opt.selected=false;
    }
}

function showEmailTeam(elem){
    var value = elem.options[elem.selectedIndex].value;
    if(value !=-1){
        $('email_team').style.display="block";
    }else{
        $('email_team_elem').checked = false;
        $('email_team').style.display="none";
    }
}

function moveToSelectBox(from, to){
    for( var i=0, elem; elem = from.options[i]; i++){
        if(elem.selected ==true){
            to.options[to.options.length] = new Option(elem.text, elem.value);
            from.options[i] = null;
        }
    }
}


function toggleVisibility(id){
    $(id).style.display = $(id).style.display=='none'?'block':'none';
    return false;
}

function delete_comment(a_object){
    alert(a_object);
}
