// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// the current project
var _cp = null;

// some patterns for matching urls
var expression_url = /^((http[s]?|feed):\/\/)?([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,6}(:[0-9]{1,5})?\/?[a-zA-Z0-9_\-\?\,\'\/\\+&%\$#\=\~\.]*$/
var expression_post = /^(http:\/\/)?(www.|([0-9a-zA-Z]|-|_)+\.){0,2}([0-9a-zA-Z]|-|_)+\.[a-zA-Z]{2,4}(\/|\/([0-9a-zA-Z]|-|_)+)?\/?$/
var expression_feed = /index.xml|index.rdf|rss.xml|\/feed\/?[^atom]$|\/rss\/|\/_rss\/|\/feeds\.|=rss$|=rss2$|\.rss|atom.xml|\/feed\/atom\/?$|\.atom|\/feeds\/.+[^=rss]$/i

// is the dom loaded ?
var dom_loaded = false;

// a function to build a URL that includes the current project if it exists
function cp_url(url) {
  if (_cp != null) {
    return '/cp/' + _cp + url;
  }
  else {
    return url;
  }
}

var Timezone = {
  set : function() {
    var date = new Date();
    var timezone = "timezone=" + -date.getTimezoneOffset() * 60;
    date.setTime(date.getTime() + (1000*24*60*60*1000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = timezone + expires + "; path=/";
  }
}

// return true if ie
function ie() {
  var browserName=navigator.appName; 
  if (browserName=="Microsoft Internet Explorer") {
    return true ;
  }
  else {
    return false ;
  }
}

//
// Dynamically loads an (external) Javascript file .
//
function load_javascript(js_file) {
  var headID = document.getElementsByTagName("head")[0];         
  var newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  newScript.src = js_file;
  headID.appendChild(newScript);
}

// return true if ie6
function ie6() {
  var browserName=navigator.appVersion; 
  if (browserName.indexOf("MSIE 6")!=-1) {
    return true ;
  }
  else {
    return false ;
  }
}

// return true if ie7
function ie7() {
  var browserName=navigator.appVersion; 
  if (browserName.indexOf("MSIE 7")!=-1) {
    return true ;
  }
  else {
    return false ;
  }
}

// return minus auto scroll value (for postolist, help, proxy)
function minus_auto_scroll() {
  return ie() ? 5 : 5;
}

function fireMouseEvent(control,myevent) { 
  // On IE
  if (document.all) { 
    control.fireEvent('on'+myevent); 
  } 
  // On Gecko based browser
  else { 
    var clickEvent = window.document.createEvent("MouseEvent"); 
    clickEvent.initEvent(myevent, false, true); 
    control.dispatchEvent(clickEvent); 
  }
}

// to be overidden when resizing for full screen
function do_resize() {
  
}

// return true if the window has a scrollbar
function scrollbar() {
  return (document.body.offsetHeight > document.viewport.getHeight())
}

// array with width et height
function windowSize() {
  var myWidth = 0, myHeight = 0;
  myWidth = document.viewport.getWidth();
  myHeight = document.viewport.getHeight();
  mySize = new Array();
  mySize['width'] = myWidth;
  mySize['height'] = myHeight;
  return mySize
}

function divHeight(div) {
  if ($(div)) {
    return $(div).offsetHeight;
  }
  else {
    return 0 ;
  }
}

function divWidth(div) {
  if ($(div)) {
    return $(div).offsetWidth;
  }
  else {
    return 0 ;
  }
}

function containerHeight() {
  return divHeight('container') ;
}

function footerHeight() {
  return divHeight('footer') ;
}

function workHeight() {
  return divHeight('work') ;
}

function sidebarHeight() {
 return divHeight('sidebar') ;
}

function headerHeight() {
  return divHeight('header') ;
}

function toolbarHeight() {
  return divHeight('toolbar') ;
}

function noticeHeight() {
  return divHeight('notice_area') ;
}

//activate blog-note for ie6
Event.observe(window, 'load', function() {
   if (ie6()) {
      // IE6, older browsers       //new HoverBehavior('tr');
      $$('.blog-note').each( function(e) {
         Event.observe(e, 'mouseover', function() {
         Element.addClassName(e, 'hover');
         });
         Event.observe(e, 'mouseout', function() {
         Element.removeClassName(e, 'hover');
         });
      });
   }
});

function findPos(obj) {
  var curleft = obj.offsetLeft || 0;
  var curtop = obj.offsetTop || 0;
  while (obj = obj.offsetParent) {
    curleft += obj.offsetLeft
    curtop += obj.offsetTop
  }
  return { x:curleft, y:curtop };
}
		
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( window.pageYOffset && typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop )) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return {x:scrOfX,y:scrOfY};
}
// note is opened for edit
var noteLock = new Array();

// display the note when user mouse over the logo
function noteShow(event, id) {
  if (noteLock[id] == null) {	
  	$('container-' + id).addClassName('display');
		// not the same calculation for postolist and others views
		// pos_y is the lenght with the top of the page/or the div for postolist
		// div_height is the size of the window or the size of the div for postolist
		// div_width is the width of the window / or the width of the div who contain the postolist
		if ($('entries-scroll')) {
			pos_y = findPos($('container-' + id).parentNode)['y'] - headerHeight() - 85 - $('entries-scroll').scrollTop;
			div_height = divHeight('entries-scroll');
			div_width = divWidth('entries-scroll');
			// put the window at the left of the screen
			pos_x = -99999
		} else {
			pos_y = findPos($('container-' + id).parentNode)['y'] - getScrollXY()['y'];
			div_height = windowSize()['height'];
			div_width = windowSize()['width'];
			pos_x = findPos($('container-' + id).parentNode)['x']
		}
		
		element_height = divHeight('container-' + id);
		element_width = divWidth('container-' + id);
		
		
		if (pos_y + element_height > div_height) {
			top_value = (div_height - pos_y) - element_height;
			if ((pos_y + top_value) < 0) {
				top_value = -pos_y+1;
			}
			$('container-' + id).setStyle({'top': top_value + 'px'});
		}

		if (pos_x + element_width > div_width) {
			top_value = (div_width - pos_x) - element_width-30;
			$('container-' + id).setStyle({'left': ''+top_value+'px'});
		}
  }
}

function noteHide(id) {
  if (noteLock[id] == null) {
  	$('container-' + id).removeClassName('display');
  }
}

// edit a note for div with ID
// called when user click on edit the note
// display the form for editing
function noteEdit(object, id) {
	// lock for show
  noteLock[id] = true
	// display edit area and hide view area
  $('container-' + id).removeClassName('display');
  $('form-' + id).addClassName('display');
	// not the same calculation for postolist and others views
	// pos_y is the lenght with the top of the page/or the div for postolist
	// div_height is the size of the window or the size of the div for postolist
	if ($('entries-scroll')) {
		pos_y = findPos($('form-' + id).parentNode)['y'] - headerHeight() - 85 - $('entries-scroll').scrollTop;
		div_height = divHeight('entries-scroll');
	} else {
		pos_y = findPos($('form-' + id).parentNode)['y'] - getScrollXY()['y'];
		div_height = windowSize()['height'];
	}

	// size of note
	element_height = divHeight('form-' + id);
	
	// display on the page if the note is out
	if (pos_y + element_height > div_height) {
		top_value = (div_height - pos_y) - element_height;
		$('form-' + id).setStyle({'top': top_value + 'px'});
	}
}

// called when edit in finish
// show the view and hide the form
// unlock the current note
function noteEditEnd(id) {
  $('container-' + id).removeClassName('display');
  $('form-' + id).removeClassName('display');
  noteLock[id] = null
}

function on_async_loading() {
 if ($('spinner')) {
  $('spinner').style.visibility = 'visible';
 }
}

function on_async_complete() {
  if ($('spinner')) {
    $('spinner').style.visibility = 'hidden';
  }
}

function clean_notice_area() {
  $('notice_area').innerHTML = "&nbsp;"
  $('notice_area').hide()
}

//Check url and put a message in the DIV id_div_error
function check_for(url, id_div_error) {
	if(id_div_error==null) id_div_error = 'warning_for_source';
	
  if (!url || url.strip() == '') {
    $(id_div_error).update("<div class='error'>Error: Empty URL !</div>");
  }
  else if (!expression_url.test(url)) {
    $(id_div_error).update("<div class='warning'>Warning: Check the syntax of this URL !</div>");
  }
	else if(!expression_post.test(url) & !expression_feed.test(url)) {
	  $(id_div_error).update("<div class='warning'>Warning: Check if the URL above is the source URL and not one of its conversations.</div>");
	}
	else {
	  $(id_div_error).update('');
	}
}

function getSelText(){
  var txt = '';
  var _window = window
  if ($('blog-frame')) {
    _window = $('blog-frame').contentWindow;
  }
  try {
    if (_window.getSelection) {
      txt = _window.getSelection();
    }
    else if (document.getSelection) {
        txt = document.getSelection();
    }
    else if (document.selection) {
        txt = document.selection.createRange().text;
    }
  }
  catch (error) {}
  return  txt;
}

function hide_default(div,input) {
  $(div).hide();
  $(input).focus();
}

// Triggers the given function when the DOM is loaded.
function observeDomLoaded(fn) {
  if (ie7()) {
    Event.observe(window, 'load', fn);
  }
  else {
    document.observe('dom:loaded', fn);
  }
}

// Executes the given function immediately if the DOM is already loaded or
// only when the DOMM will be loaded (equivalent for jQuery.ready())
function domLoaded(fn) {
  if (dom_loaded == true) {
    fn.call();
  }
  else {
    observeDomLoaded(fn);
  }
}

// Flags that the DOM is loaded when it is.
function flagDomLoaded() {
  observeDomLoaded(function() { dom_loaded = true; });
}
