var globals = new Array();

function closeSuggest(suggest) {
  jQuery('#'+suggest).css('display', 'none');
}

function sendSuggest(base, field) {
  var status = base+'-status';  
  jQuery('#'+status).html('loading...');
  
  var request = base+'-'+field+'-request';
  globals[request] = $.get('/unis/'+base+'-'+field+'/'+jQuery('#'+base+'-'+field).val(), {
    }, function(response) {
      var suggest = base+'-suggest';
      jQuery('#'+status).html('done.');
      jQuery('#'+suggest).css('display', 'block');
      jQuery('#'+suggest).html('<div class="suggest-inner">'+response+'</div><a class="control" onclick="closeSuggest(\''+suggest+'\'); return false;">hide</a>');
  });
}

function ajaxSuggest(base, field) {
  var request = base+'-'+field+'-request';
  if (globals[request]) {
    globals[request].abort();
    globals[request] = null;
  }
  
  var status = base+'-status';
  var suggest = base+'-suggest';
  
  jQuery('#'+status).html('');
  jQuery('#'+suggest).css('display', 'none');
  
  var timer = base+'-'+field+'-timer';
  if (globals[timer]) clearTimeout(globals[timer]);
  globals[timer] = setTimeout('sendSuggest("'+base+'", "'+field+'")', 1000);    
}

function suggestItem(base, sender, edit) {
  $('#'+base+'-suggest').css('display', 'none');
  var itemId = sender.id.substring(sender.id.lastIndexOf('-')+1, sender.id.length);
  
  // that one should be sent to server before appending
  $.get('/cms', {
      action: 'ajax',
      instance: 'add-'+base,
      id: itemId
    }, function(response) {
      if (jQuery('#'+base+'-list .no-data').html()) {
        jQuery('#'+base+'-list').empty();
      }
      var row = '<li id="'+base+'-item-'+itemId+'">'+sender.innerHTML+'<span class="controls">';
      if (edit) {
        row+= '<a href="?action='+base+'&id='+itemId+'">edit</a>';
      }
      row+= '<a onclick="removeItem(\''+base+'\', '+itemId+');" href="#">delete</a></span>'+'</li>';
      jQuery('#'+base+'-list').append(row);
  });
}

function suggestSlug(sender) {
  
  form = sender;
  do {
    var form = form.parentNode;
  } while (form.tagName != "FORM");
  
  jQuery(".slug", form)[0].value = sender.value.replace(/\W+/g, '-'); 
}

function suggestField(sender) {
  //if (sender.value.length < 3) return true;
  var id = sender.id.split('-');
  ajaxSuggest(id[0], id[1]);
}

function fillWith(field, sender) {
  jQuery('#'+field)[0].value = sender.id.substr(6, sender.id.length-6);
  var temp = field.split('-');
  closeSuggest(temp[0]+'-suggest');
}

function selectUniChange(sender) {
  var chunks = window.location.href.split('/');
  chunks.pop();
  chunks.push(sender.options[sender.selectedIndex].value);
  window.location.href = chunks.join('/');
}

function eventCatsChange(sender) {
  sender.className = "category "+sender.options[sender.selectedIndex].value;
}

function deleteEvent(sender) {

  var form = sender.form;

  if (confirm('OK to delete `'+form['form[e_title]'].value+'` ?')) {
    form.eaction.value = 'delete';
    form.submit();
  }
}

function roundCorners() {
  // will not work without dojo
  var rounded = dojo.query('.rounded');

  dojo.forEach(rounded, function(victim, index) {
    var leftBottom = dojo.doc.createElement('div');
    leftBottom.innerHTML = victim.innerHTML;
    victim.innerHTML = '';

    var style = dojo.style(victim);
    dojo.style(leftBottom, {
      'paddingLeft': style.paddingLeft,
      'paddingRight': style.paddingRight,
      'paddingTop': style.paddingTop,
      'paddingBottom': style.paddingBottom      
    });
    dojo.style(victim, {
      'paddingLeft': '0px',
      'paddingRight': '0px',
      'paddingTop': '0px',
      'paddingBottom': '0px'
    });

    if (parseInt(style.height) > 0) {
      dojo.style(leftBottom, {'height': style.height});
      dojo.style(victim, {'height': 'auto'});
    }
    
    dojo.addClass(leftBottom, 'left bottom');

    var rightBottom = dojo.doc.createElement('div');
    rightBottom.appendChild(leftBottom);
    dojo.attr(rightBottom, 'class', 'right bottom');

    var rightTop = dojo.doc.createElement('div');
    rightTop.appendChild(rightBottom);
    dojo.attr(rightTop, 'class', 'right top');

    var leftTop = dojo.doc.createElement('div');
    leftTop.appendChild(rightTop);
    dojo.attr(leftTop, 'class', 'left top');
    victim.appendChild(leftTop);
  });
}

function fSubmitDojoForm(dijitForm) {
    if ( dojo.isString(dijitForm) ) dijitForm = dijit.byId(dijitForm);
    if ( dijitForm.validate() ) {
        if ( dojo.isFF ) {
            var aDijits = dijitForm.getDescendants();
            var dijitChild, sName, sValue, eTextarea;
            for ( var i=0, max=aDijits.length; i<max; i++ ) {
                dijitChild = aDijits[i];
                if ( dijitChild.domNode.className.indexOf('RichTextEditable')!=-1) {
                    sName = dijitChild.domNode.getAttribute('widgetid');
                    var namelist = sName.split('-');
                    namelist.pop();
                    var taName = 'form['+namelist.join('-')+']';
                    sValue = dijitChild.getValue();
                    eTextarea = document.createElement('textarea');
                    dijitForm.domNode.appendChild(eTextarea);
                    eTextarea.name = taName;
                    eTextarea.value = sValue;
                    eTextarea.style.display = 'none';
                }
            }
        }
        dijitForm.submit();
    }
    return false;
}
/*
function linkExternals() {
  dojo.require("dojo.behavior");
  dojo.behavior.add({
    '#external a': {
      'onclick': function(obj) {
        obj.preventDefault(); // this one does usual return false!
        window.open(obj.target.href, '_blank' + Math.random());
        return false; // does nothing actually, just for clarity
      }
    }
  });
}
*/

function linkExternals() {
	jQuery('#external a').click(function() {
		window.open(this, '_blank');		
		return false;
	});
}

function syncUsers() 
{
  var status = dojo.query('.sync-user');
  
  dojo.require('dojo.io.iframe');
  dojo.io.iframe.send({
    method: 'POST',
    url: 'http://spoonfed.co.uk',
    content: {
      q: 'get'
    },
    load: function(response) {
      //console.debug(response);
      alert(1);
    }
  });
  
  /*
  dojo.forEach(status, function(victim, index) {
    //victim.innerHTML = '<img src="/images/ajax-loader.gif" alt="" />';
    // need email
    var id = dojo.attr(victim, 'id').split('-').pop();
    var email = dojo.byId('user-email-'+id).innerHTML;
    
    dojo.require('dojo.io.iframe');
    dojo.io.iframe.send({
      method: 'GET',
      url: 'http://spoonfed.co.uk',
      timeout: 5000,
      load: function(response) {
        victim.innerHTML = response;
        return response;
      }
    });
  });
  */
}
