/*
* Aether javascript collection
*/

function openPictureSelector( pictureWidth, pictureHeight, thumbWidth, thumbHeight, idElement, thumbElement, categoryTypeIdName, categoryId, database ){
    var categoryTypeIdName = categoryTypeIdName || "";
    var categoryId = categoryId || "";
    var database = database || "primary";
    var callBackName = 'callback_' + idElement.replace("[","").replace("]","");
    
    
    
    // create callback if we haven't done so already
    if (typeof(window[callBackName]) != "function"){
        eval("window." + callBackName + " = function(pid){" +
        "$('"+idElement+"').value = pid;" +
        "$('"+thumbElement+"').src = 'image.php?pid='+pid+'&width="+thumbWidth+"&height="+thumbHeight+"&db="+database+"';" +
      "};");
    }
    
    // open the picture chooser
    var w = window.open('?page=picture&action=show&actiontype=popup&width='+pictureWidth+'&height='+pictureHeight+'&callback='+callBackName + '&categoryTypeIdName='+categoryTypeIdName + '&categoryId=' + categoryId + '&database=' + database, '_blank');
}

function deletePicture ($iPictureId, $sCategoryIdName, $sCategoryId,$oPicture) 
{
  if (!confirm('Week u zeker dat u de afbeelding wilt verwijderen?'))
    return false;
  $sDeleteUrl = 'index.php?page=picture&action=delete&actiontype=ajax&pid=' + $iPictureId + '&category_id_name=' + $sCategoryIdName + '&category_id='+$sCategoryId;
  new Ajax.Request($sDeleteUrl,
  {
    method:'get',
    onSuccess: function(transport){
      var $sResponse = transport.responseText || "No response text";
     
      if ($sResponse == '1')
      {
        $oPicture.style.display = 'none';
      }
      else
      {
        alert ('De afbeelding kan niet worden verwijderd.');
      }
    },
    onFailure: function(){ alert('Something went wrong while removing the picture!'); }
  }

  );
}

function deletePictureFromModule ($iPictureId, $sModuleName, $nItemId,$oPicture) 
{
  if (!confirm('Week u zeker dat u de afbeelding wilt verwijderen?'))
    return false;
  $sDeleteUrl = 'index.php?page=picture&action=deletefrommodule&actiontype=ajax&pid=' + $iPictureId + '&module_name=' + $sModuleName + '&item_id='+$nItemId;
  new Ajax.Request($sDeleteUrl,
  {
    method:'get',
    onSuccess: function(transport){
      var $sResponse = transport.responseText || "No response text";
     
      if ($sResponse == '1')
      {
        $oPicture.style.display = 'none';
      }
      else
      {
        alert ('De afbeelding kan niet worden verwijderd.');
      }
    },
    onFailure: function(){ alert('Something went wrong while removing the picture!'); }
  }

  );
}

function doOnload(func){
  var oldOnload = window.onload;

	if (typeof(window.onload) != "function")
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			oldOnload();
			func();
		}
	}
}


function submitForm( formid ){  
  $(formid).onsubmit();
  $(formid).submit();   
}

function onloadFocus(elementId){
  doOnload(function(){$(elementId).focus();});
}

function clearIfDefault ($obj,$value)
{
  if ($obj.value == $value)
  {
    $obj.value = '';
  }
}

function restoreIfDefault ($obj,$value)
{
  if ($obj.value == '')
  {
    $obj.value = $value;
  }
}
function clearIfDefaultPassword ($obj,$value)
{
  if ($obj.value == $value)
  {
    var id = $obj.id;
    $obj.value = '';
    var newInput = $obj.cloneNode(true);
    newInput.type = 'password';
    $obj.parentNode.replaceChild(newInput,$obj);
    setTimeout(function(){$(id).focus();}, 200);
  }
}

function multiLangSelect ($sIdPrefix, $sLanguage)
{
  $aFields = $($sIdPrefix + 'holder').getElementsByTagName('p');
  for ($i = 0; $i < $aFields.length; $i++)
  {
    $aFields[$i].style.display = 'none';
    if (Element.hasClassName($aFields[$i], $sIdPrefix + $sLanguage))
    {
      $aFields[$i].style.display = 'block';
    }
  }
  
  $aSelectors = document.getElementsByClassName('active_lang');
   for ($i = 0; $i < $aSelectors.length; $i++)
  {
    $aSelectors[$i].removeClassName('active_lang');
    $aSelectors[$i].addClassName('lang');
  }
  if ($('select_lang_' + $sLanguage))
  {
    $('select_lang_' + $sLanguage).removeClassName('lang');
    $('select_lang_' + $sLanguage).addClassName('active_lang');
  }
}

/**
 * breaks up the contents of a span in segments.
 * The default break token is '[nextpage]'.
 * The first segment is shown and the others can be reached by clicking a link.
 * This link is automatically inserted below the text.
 */    
 
function breakUpContents (textPrevious, textNext, elements){
  // create global arrays that hold segment-info
  window.break_up_contents_segments = new Hash();
  window.break_up_contents_segments_total = new Hash();
  
  window.break_up_contents_previous_display_text = textPrevious;
  window.break_up_contents_next_display_text = textNext;
    
  for (var i = 0; i < elements.length; i++){
    breakUpElement(elements[i]);
  };
   
}
 
function breakUpElement (elementId){
  var container = $(elementId);
  var completeContent = container.innerHTML;
  
  // the widgeditor probably has wrapped the [nextpage] with a paragraph,
  // remove it.
  var completeContent = completeContent.gsub(/<p([^<]*?)>\[nextpage\]<\/p>/i, '[nextpage]'); 
  
  //alert (completeContent);
  
  var segments = [];
  segments = completeContent.split("[nextpage]");
  //completeContent.scan(/(.*)(\[nextpage\])/i, function(match){ segments.push(match[1])});
  
  
  // store number of segments in global var
  window.break_up_contents_segments_total[elementId] = segments.length;
  // store segments in global var
  window.break_up_contents_segments[elementId] = segments;
  
  if (segments.length > 0){
    showBreakUpSegment(elementId, 0);
  }  
}

function getBreakUpNavigationBar (elementId, segmentIndex, showPrevious, showNext){
  var navTable = '<table width="100%" border="0"><tr><td class="aether_break_up_previous">';
  if (showPrevious){
    navTable += '<a href="javascript:window.showBreakUpSegment(\'' + elementId + '\', ' + (segmentIndex-1) +')">' + window.break_up_contents_previous_display_text + '</a>';
  }
  navTable += '</td><td class="aether_break_up_next">';
  if (showNext){
    navTable += '<a href="javascript:window.showBreakUpSegment(\'' + elementId + '\', ' + (segmentIndex+1) +')">' + window.break_up_contents_next_display_text + '</a>';
  }
  navTable += '</td></tr></table>';
  
  return navTable;
}

function showBreakUpSegment(elementId, segmentIndex){
  var container = $(elementId);
  var newContent = window.break_up_contents_segments[elementId][segmentIndex];
  
  var showPrevious  = segmentIndex >= 1;
  var showNext      = segmentIndex < window.break_up_contents_segments_total[elementId]-1;
  var navTable      = getBreakUpNavigationBar (elementId, segmentIndex, showPrevious, showNext);
  
  newContent += navTable;
  container.update(newContent);  
}

function autoLightbox()
{
  var anchors = document.getElementsByTagName("a");
  var imgex = /\.(jpg|jpeg|gif|png|bmp)$/;
  for (var i = 0; i < anchors.length; i++){
    var anchor = anchors[i];
    if(window.console)
      console.log(anchor);
    if (  anchor.getAttribute('href') && 
          anchor.getAttribute('href').toLowerCase().search(imgex) >= 0 &&
          !anchor.getAttribute('rel') 
        ){
      anchor.setAttribute('rel', 'lightbox');
      
    }
  }
}


function initLightboxFromFlashLink(id) {
  var objLink = $(id);
  Lightbox.prototype.start(objLink);
}

/**
 * returns the value of the selected radio in a group
 */  
function getRadioValue(formId, radioName)
{
  var buttons = $(formId).getInputs('radio', radioName);
  var selectedValue = null;
  for (var i = 0; i < buttons.length; i++)
  {
    var val = buttons[i].getValue();
    if (val != null) selectedValue = val;
    break;
  } 

  return val;  
}

/**
 * load this function on pageload and all external links will be redirected
 * to a new window
 */  
function externalLinksInBlankWin(){
	var hostname = window.location.hostname;
	hostname = hostname.replace("www.","").toLowerCase();
	var a = document.getElementsByTagName("a");	
	var check = function(obj){
		var href = obj.href.toLowerCase();
		return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false;				
	};
	var set = function(obj){
		obj.target = "_blank";
	};	
	for (var i=0;i<a.length;i++){
		if(check(a[i])) set(a[i]);
	};		
}


/**
 * set a cookie value
 */
 function setCookie( name, value, expiresDays, path, domain, secure ) 
{
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime( today.getTime() );
  
  /*
  if the expires variable is set, make the correct 
  expires time, the current script below will set 
  it for x number of days, to make it for hours, 
  delete * 24, for minutes, delete * 60 * 24
  */
  if ( expiresDays )
  {
    expires = expiresDays * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  
  document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
  ( ( path ) ? ";path=" + path : "" ) + 
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
} 

/**
 * Get a cookie value
 * Taken from http://techpatterns.com/downloads/javascript_cookies.php 
 */

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

/**
 * delete a cookie
 */ 
function deleteCookie( name, path, domain ) {
  if ( getCokie( name ) ) document.cookie = name + "=" +
  ( ( path ) ? ";path=" + path : "") +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
