
//framebreaker

if (self != top) {
  parent.location.href=self.location.href;
}

// onload stuff

function onWinLoad() {
  var search_input = $('sw_search_input');
  if (search_input) {
    search_input.focus();
  }
  var nav_search_input = $('nav_search_input');
  if (nav_search_input) {
    nav_search_input.value = 'Search';
    nav_search_input.style.color = '#ccc'
    Event.observe(nav_search_input, 'focus', function(event) {nav_search_input.value = '';nav_search_input.style.color = '#333';});
  }

  var base_url = window.location.protocol + '//' + window.location.host;
  
  var links = $A(document.getElementsByTagName('a'));
  links.each(function(link) {
    if (base_url + '/contact/' == link.href) {
      link.title = "Contact form";
      Event.observe(link, 'click', function(event) {Modalbox.show(link.href + '?is_popup=1', {title: link.title, width: 696}); event.stop();})
    }
    if (base_url + '/accounts/logout/' == link.href) {
      link.title = "Click to log out";
      Event.observe(link, 'click', function(event) {Modalbox.show(link.href + '?is_popup=1', {title: '', width: 696, afterHide: function() { window.location.reload()} }); event.stop();})
    }
    if (base_url + '/accounts/login/' == link.href) {
      link.title = "Log in with your username and password";
      Event.observe(link, 'click', function(event) {Modalbox.show(link.href + '?is_popup=1', {title: link.title, width: 696, afterLoad: function() { $('id_username').focus()}}); event.stop();})
    }
    if (base_url + '/accounts/register/' == link.href) {
      link.title = "Create new account";
      Event.observe(link, 'click', function(event) {Modalbox.show(link.href + '?is_popup=1', {title: link.title, width: 696}); event.stop();})
    }
  });

  var admin_form = $('admin-tb-form');
  if (admin_form) {
    var inputs = $A(admin_form.getElementsByTagName('input'));
    inputs.each(function(input) {
      if (input.name == 'anon_download_access' && input.checked)
        $('id_auth_download_access').disabled = true;
      Event.observe(input, 'click', function(event) {admin_form.submit()})
    });
  }
}

Event.observe(window, 'load', onWinLoad);

// Ratings stuff

function SetRating(event) {
  var stars = $('rating_stars');
  Event.observe(stars, 'mouseout', CheckRating)
  var link = Event.element(event);
  Event.observe(link, 'mousedown', SetRatingInput)
  var rating = link.innerHTML;
  var divs = stars.childElements();
  for (var i=0; i<divs.length; i++) {
    if (i<rating)
      divs[i].style.backgroundPosition = "bottom center";
    else
      divs[i].style.backgroundPosition = "top center";
  }
}

function SetRatingInput(event) {
  var link = Event.element(event);
  var rating = link.innerHTML;
  var input = $('id_rating1_'+ (rating-1));
  input.checked = true;
  $('rating_stars')['rating'] = rating;
}

function CheckRating(event) {
  var stars = $('rating_stars');
  var rating = 0;
  if (stars['rating'])
    rating = stars['rating'];
  var divs = stars.childElements();
  for (var i=0; i<divs.length; i++) {
    if (i<rating)
      divs[i].style.backgroundPosition = "bottom center";
    else
      divs[i].style.backgroundPosition = "top center";
  }
}

//tag completion stuff

function moveTagAutocomplete(element) {
  Element.extend(element);
  Event.observe(element, 'blur', function()
    {$('tag-autocomplete').hide();})
  $('tag-autocomplete').style.left = (element.positionedOffset()[0] + 'px')
  $('tag-autocomplete').style.top = (
    (element.positionedOffset()[1] + element.getHeight()) + 'px')
  Event.observe(element, 'keydown', browseTagSuggest)
  Event.observe(element, 'keyup', function(event) {sendProjTag(event, element)})
  Event.observe(element, 'keypress', blockBadTagChars)
}

function blockBadTagChars(event) {

  if (event.keyCode== 34 || event.keyCode == 58)
    event.stop()

  //Check if we need to add more inputs
  var div = $('add-tag-field');
  var inputs = div.select('input');
  var isEmpty = false;
  for (var i = 0; i < inputs.length; i++) {
    if (!inputs[i].value) {
      isEmpty = true;
      break;
    }
  }
  if (!isEmpty)
    addMoreTags()
}

function sendProjTag(event, element) {
  if (!element["oldValue"])
    element["oldValue"] = '';
  if ((element["oldValue"] == element.value) || element.value == '')
    return
  if (element["oldValue"].length && (element.value.length > element["oldValue"].length) && element['responseLength'] == 0)
    return
  element["oldValue"] = element.value;
  new Ajax.Request('/software/project_tag_search/',
  {method:'post', asynchronous:true, postBody:'value='+element.value,
    onSuccess: function(res) {
      var data = res.responseText.evalJSON();
      element["responseLength"] = data.length;
      if (data.length) {
        var ul = new Element('ul', {id: 'tag-auto-ul'});
        ul['input'] = element;
        for (var i=0;i<data.length;i++) {
          var li = new Element('li', {id: 'tag-auto-li'+i}).update(data[i])
          Event.observe(li, 'mouseover', mouseTagSuggest);
          Event.observe(li, 'mousedown', mouseTagClick);
          ul.appendChild(li);
        }
        $('tag-autocomplete').update(ul);
        new Effect.Appear('tag-autocomplete', {duration:0.4});
      }
      else {
        $('tag-autocomplete').hide();
      }
    }
  });
}

function browseTagSuggest(event) {
  var element = Event.element(event);
  var ul = $('tag-auto-ul');
  if (!ul)
    return
  var curSel = -1;
  if (!isNaN(ul['curSel']))
    curSel = ul['curSel'];
  if(event.keyCode == Event.KEY_UP || event.keyCode == Event.KEY_DOWN) {
    var lis = ul.childElements();
    if(event.keyCode == Event.KEY_UP)
      var newSel = curSel - 1;
    else
      var newSel = curSel + 1;
    if (newSel > lis.length - 1)
      newSel = 0;
    else if (newSel < 0)
      newSel = lis.length - 1;
    if (lis[curSel])
      lis[curSel].setStyle({backgroundColor: '#efefef', color: '#333333'});
    lis[newSel].setStyle({backgroundColor: '#0099ff', color: 'white'});
    element['newValue'] = lis[newSel].innerHTML;
    ul['curSel'] = newSel;
  }
  else if (event.keyCode == Event.KEY_RETURN && element['newValue']) {
    element.value = element['newValue']
    $('tag-autocomplete').hide();
    event.stop()
  }
  else if (event.keyCode == Event.KEY_ESC) {
    $('tag-autocomplete').hide();
    event.stop()
  }
}

function mouseTagSuggest(event) {
  var element = Event.element(event);
  var ul = $('tag-auto-ul');
  var lis = ul.childElements();
  for (var i = 0; i<lis.length;i++)
    lis[i].setStyle({backgroundColor: '#efefef', color: '#333333'});
  element.setStyle({backgroundColor: '#0099ff', color: 'white'});
}

function mouseTagClick(event) {
  var li = Event.element(event);
  var ul = $('tag-auto-ul');
  ul['input'].value = li.innerHTML;
}

function addMoreTags() {
  var div = $('add-tag-field');
  var inputs = div.select('input');
  var rowid = 'new_tagrow' + inputs.length
  var row = new Element('div', {id: rowid});
  row.setStyle({display: 'none'});
  for (var i = inputs.length; i < inputs.length + 3; i++) {
    var input = new Element('input', {id:"id_tags_" + i, type:"text", name:"tags_"+i, onfocus:"moveTagAutocomplete(this)", autocomplete:"off"});
    row.appendChild(input);
  }
  div.appendChild(row);
  new Effect.BlindDown(rowid, {duration:0.6})
}

function toolSelChange(input) {
  var element = Form.Element.activate(input.id);
  input = $(input.id.substring(0, input.id.length-1) + '1')
  if (element.getValue() == 'other') {
    new Effect.Appear(Element.extend(input.parentNode));
    Form.Element.activate(input.id).focus();
    Form.Element.activate(input.id).select();
  }
  else
    new Effect.Fade(Element.extend(input.parentNode));

}

function addMoreAttachments(link) {
    var div = $("AttachmentWidget");
    var i = div.select('input').length;
    div.appendChild(new Element('br'))
    var input = new Element('input', {id:"id_file" + i, type:"file", name:"file"+i});
    div.appendChild(input);
}

function FileListChange(event) {
  post=Sortable.serialize('file-list', {name:'id'});
  post = post.replace(/[\&\[\]]/g, '');
  document.location.href = '/software/'+sw_order_what+'/' + post + '/';
}

function DocListChange(event) {
  post=Sortable.serialize('doc-list', {name:'id'});
  post = post.replace(/[\&\[\]]/g, '');
  document.location.href = '/software/'+doc_order_what+'/' + post + '/';
}


// Hide, show edit issue field


function edit_issue_form_show(link) {
if (link.innerHTML.substring(0, 4) == 'Edit') {
  new Effect.Appear($('edit_issue_form'));
  link.innerHTML = 'Hide <img style="vertical-align:middle;" src="/static/img/icons/minus.png" />';
}
else {
  new Effect.Fade($('edit_issue_form'));
  link.innerHTML = 'Edit issue <img style="vertical-align:middle;" src="/static/img/icons/plus.png" />';
}
}

/*
 * update license info
 *   send license id (f.x. "3") to '/software/license_info/'
 *   get string like 
 *     'Your choice of license determines how others are allowed to use your work. '
 *     +
 *     'What is <a href... target="_blank">...</a>?'
 */

function LicenseInfo() {
  new Ajax.Request('/software/license_info/',
  {
    method:'post',
    asynchronous:true,
    postBody:'value='+document.getElementById('id_license').value,
    onSuccess: function(res){
      var data = res.responseText.evalJSON();
      document.getElementById('id-license-help').innerHTML = data;
      }
  });
}


function DisplayLicenses() {
  new Ajax.Request('/software/licenses/',
  {
    method:'post',
    asynchronous:true,
    postBody:'',
    onSuccess: function(res){
      var data = res.responseText;
      document.getElementById('license-display-area').innerHTML = data;
      }
  });

}
