/* CVS: $Id: common.js,v 1.21 2011/02/14 19:12:18 declan Exp $ */

var Verification_Window = null;

var StickyNoteObserver = Class.create({
  onEndMove: function(eventname, w){
    StickyNotes.saveWindowParams(w);
  },
  
  onEndResize: function(eventname, w){
    StickyNotes.saveWindowParams(w);
  }
});

var StickyNotes = Class.create({
  initialize: function(){
    this.window_id = null;
  },
  
  showNewNoteWindow: function(window_id, ajax_url){
    this.window_id = window_id;
  
    Verification_Window = new Window({id: window_id, className: "alphacube", recenterAuto:false});
    Verification_Window.setTitle('Add Sticky Note'); 
    Verification_Window.setSize(344, 361);
    Verification_Window.setAjaxContent(ajax_url, {method: 'get'}, false, false);
    Verification_Window.setDestroyOnClose();
    Verification_Window.setLocation(10, 10);
             
    Verification_Window.show();
  },
  
  doAddStickNote: function(formid, ajax_url){
    var pform = $(formid);
    var win_element = $(this.window_id);
   
    // grab position of window 
    var pos = '?x=' + win_element.style.left + '&y=' + win_element.style.top;
    var url = ajax_url + pos;
            
    new Ajax.Request(url, {
      method: 'post',
      parameters: pform.serialize(),
      onSuccess: this.eventDoAddStickyNoteSuccess
    });
  },
  
  deleteStickyNote: function(id){
    var sticky_win = Windows.getWindow('sticky' + id);
    var url = StickyNotes.url_DeleteStickyNote;    
    
    new Ajax.Request(url, {
      method: 'post', 
      parameters: { id: id },
      onSuccess: function(t){ 
        sticky_win.destroy(); 
      } 
    });
  }, 
  
  // show edit textarea for a sticky note
  showEditStickyNote: function(id){
    $('edit-sticky-' + id).style.display = '';
    $('edit-sticky-comment-' + id).style.display = 'none'; 
    $('save-sticky-link-' + id).style.display = '';
    $('edit-sticky-link-' + id).style.display = 'none';
    $('cancel-sticky-link-' + id).style.display = '';
  },
  
  // do the actual saving
  editStickyNote: function(id){
    var sticky_form_params = $('edit-sticky-form-' + id).serialize();
    
    new Ajax.Request(StickyNotes.url_EditStickyNote, {
      method: 'post',
      parameters: sticky_form_params,
      onSuccess: function(t) {
        // update the contents
        sticky_win = Windows.getWindow('sticky' + id);
        sticky_win.getContent().update(t.responseText);
      }
    });
  },
  
  cancelEditStickyNote: function(id){
    $('edit-sticky-' + id).style.display = 'none';
    $('edit-sticky-comment-' + id).style.display = ''; 
    $('save-sticky-link-' + id).style.display = 'none';
    $('edit-sticky-link-' + id).style.display = '';
    $('cancel-sticky-link-' + id).style.display = 'none';
  },
      
  eventDoAddStickyNoteSuccess: function(transport){
    // close down window
    Verification_Window.destroy();
  },
  
  hasStickyNotes: function(blogpostid){
  },
  
  loadBlogpostNotes: function(ajax_url, blogpost_id){
    new Ajax.Request(ajax_url, {
      method: 'post',
      parameters: { blogpostid: blogpost_id },
      onSuccess: StickyNotes.displayAllStickys
    });
  },
  
  // @static
  displayAllStickys: function(t){
    var stickyArray = eval(t.responseText);
    Windows.closeAll();
        
    stickyArray.each(function(o){
      var e_id = 'sticky' + o.id;
                                      
      StickyWin = new Window({id: e_id, className: "alphacube", recenterAuto:false});
      StickyWin.setTitle('Sticky Note');
      StickyWin.setSize(o.w, o.h);
      StickyWin.setLocation(o.y, o.x);
      StickyWin.getContent().update(o.content);
      StickyWin.setDestroyOnClose();
      StickyWin.setCloseCallback(StickyNotes.saveWindowParams);
      StickyWin.show();        
    });
    
    Windows.addObserver(new StickyNoteObserver());
  },
  
  // @static
  saveWindowParams: function(w){
    var id = w.element.id.replace('sticky', '');
    var p = {
	     x: w.element.style.left,
	     y: w.element.style.top,
	     w: w.getSize().width,
	     h: w.getSize().height,
	    id: id
    };
    var url = StickyNotes.url_UpdateStickyParams;
    
    new Ajax.Request(url, { 
      parameters: p, 
      method: 'post'
    });
        
    return true;
  }  
});

var EditorControls = Class.create({
  initialize: function(){
  },
  
  initStandardEditor: function(textareaid){
    tinyMCE.init({
      mode: "exact",
      language: "en",
      elements: textareaid,
      plugins: "advimage,advlink,spellchecker",
      spellchecker_languages: "+English=en",
      spellchecker_rpc_url: g_spellcheck_url,
      theme: "advanced",
      theme_advanced_toolbar_location: "top",
      theme_advanced_toolbar_align: "left",
      theme_advanced_path_location: "bottom",
      theme_advanced_buttons1: "justifyleft,justifycenter,justifyright,justifyfull,separator,bold,italic,strikethrough,separator,sub,sup,separator,bullist,numlist,separator,outdent,indent,separator,undo,redo,separator,link,unlink,separator,cleanup,removeformat,separator,code",
      theme_advanced_buttons2: "spellchecker,formatselect,fontselect,fontsizeselect",
      theme_advanced_buttons3: "",
      extended_valid_elements: "img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name]",
      relative_urls: false,
      remove_script_host : false,
      debug: false
    });
  },
  
  initCalendar: function(triggerid, inputid){
   $(triggerid).disabled = false;
    Calendar.setup({
      inputField : inputid,
      ifFormat : "%d-%m-%Y",
      daFormat : "%d-%m-%Y",
      button : triggerid
    });
  }
}); 

function clearv(id, txt){
  var e = $(id);
  
  if (e.value == txt){       
    e.value = '';
    e.style.color = '#000';
  }
}

/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

function selectobjects(name, opt){
  var tag = 'input';
  var opt_list = [ 'all', 'none', 'inverse', 'only' ];
  var klass = tag +  '.' + name;
  var elements = $$(klass);
  
  if (opt == 'only'){
    for (var i =0; i< elements.length; i++){
      element = elements[i];
      if (!element.disabled){
        element.checked = true;
      }
    } 
  }  
    
  if (opt == 'all'){
    for (var i =0; i< elements.length; i++){
      element = elements[i];
      if (!element.disabled){
        element.checked = true;
      }
    }
  }
  
  if (opt == 'none'){
    for (var i =0; i< elements.length; i++){
      element = elements[i];
      if (!element.disabled){
        element.checked = false;
      }
    }
  }
  
  if (opt == 'inverse'){
    for (var i =0; i< elements.length; i++){
      element = elements[i];
      if (!element.disabled){
        element.checked = !element.checked;
      }
    }
  }   
}



function confirm_delete(msg, func_ok, func_cancel){
  Dialog.confirm(msg, {
    zIndex: 100,
    width: 300, 
    okLabel: "Yes", 
    buttonClass: "myButtonClass", 
    id: "confirmAction", 
    cancel: func_cancel, 
    ok: func_ok 
  }); 
}

function alternate(id){
  if(document.getElementsByTagName){  
   var table = document.getElementById(id);  
   var rows = table.getElementsByTagName("tr");  
   
   for(i = 0; i < rows.length; i++){          
	   if (rows[i].className ==  'head'){
	     continue;
	   }
	   
	   // manipulate rows
	   if(i % 2 == 0){
       rows[i].className = "even";
     } else {
       rows[i].className = "odd";
     }      
   }
 }
}

function toggleBlogpostLock(id){
  var link = $('lock-toggle-' + id);
  var url = '/blog/ajaxToggleLock?blogpostid=' + id;
  
  new Ajax.Request(url, {
    method: 'post',
    parameters: '',
    onSuccess: function(t){
      link.update(t.responseText);
    }
  });
}

/* goto a url */
function goTo(url){
  var a = document.createElement('a');
  if(!a.click) { //only IE has this (at the moment);
    window.location = url;
    return;
  }
 
  a.setAttribute("href", url);
  a.style.display = "none";
  $("body").appendChild(a); //prototype shortcut
  a.click();
}

function openRptWindow(url, width, height){
  return openNewWindow(url, width, height)
}

function openUploadResourceWindow(url){
  var myRef = window.open(url, 'uploadwin', 'left=20,top=20,width=730,height=480,toolbar=0,resizable=1,scrollbars=1');
  return myRef;
}

function openGadgetPreviewWindow(url){  
  return window.open(url, 'Preview', 'left=20,top=20,width=730,height=480,toolbar=0,resizable=1,scrollbars=1');
}

function openNewWindow(url, width, height){
  var w = width || 1000;
  var h = height || 700;
  var ref = window.open(url, 'uploadwin', 'left=20,top=20,width=' + w + ',height=' + h + ',toolbar=0,resizable=1,scrollbars=1');
  return ref;
}

function hideflash(){
    //$$('.audio').each(function(el){el.hide()});
    //$$('.video').each(function(el){el.hide()});
    //$$('.audio').each(function(el){new Effect.Move(el, { x: -15000, y: 0, mode: 'relative' });});
    $$('.audio').each(function(el){tmpal = parseInt(el.getStyle('left'));if(isNaN(tmpal)||tmpal>=0){new Effect.Move(el, { x: -15000, y: 0, mode: 'relative' });}});
    $$('.video').each(function(el){tmpvl = parseInt(el.getStyle('left'));if(isNaN(tmpvl)||tmpvl>=0){new Effect.Move(el, { x: -15000, y: 0, mode: 'relative' });}});
}

function showflash(){
    //$$('.audio').each(function(el){el.show()});
    //$$('.video').each(function(el){el.show()});
    //$$('.audio').each(function(el){new Effect.Move(el, { x: 15000, y: 0, mode: 'relative' });});
    $$('.audio').each(function(el){tmpal = parseInt(el.getStyle('left'));if(tmpal<0){new Effect.Move(el, { x: 15000, y: 0, mode: 'relative' });}});
    $$('.video').each(function(el){tmpvl = parseInt(el.getStyle('left'));if(tmpvl<0){new Effect.Move(el, { x: 15000, y: 0, mode: 'relative' });}});
}

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

function eventRemoveAsset(id) { am.getAssetManager().eventRemoveAsset(id); }
function eventRemoveBlogpostAsset(id) { am.eventRemoveAsset(id); }
