var addthis_config = {
     ui_cobrand: "Générotrons"
}



var nbDataset = 0;
var nbItems = {};



function initotron()
{
	var i = 1;
	var dataset = document.getElementById('genDataset'+i+'Select');
    
  while( dataset != null ){
    
    nbDataset++;
    
    var j=0;
    while( dataset.options[j] != null ){
       j++;
    }
  
    nbItems[i] = j;
    
    i++;
    dataset = document.getElementById('genDataset'+i+'Select');
  }
}



/**
 * Takes each selected dataset and concatenates their values to generate the sentence
 */ 
function generotron()
{ 
	chaine = '' ;
	var values = new Array();
	var indexes = new Array();

  // ---------------------------------------------------------------------------
  // 1) Extract tha raw data from datasets (combo boxes)
  for(i=0; i<nbDataset; i++) {
    // take the selected value
    var item = document.getElementById('genDataset'+(i+1)+'Select');
    
    indexes[i] = 0;
    values[i] = new Array();
    values[i][0] = item.options[item.selectedIndex].value;
  }

  // ---------------------------------------------------------------------------
  // 2) Analyse data to extract special infos (skip, genres, ...)
  for(i=0; i<values.length; i++) {
  
    var genres = new Array();
    var isSingleGenre = true;
    
    var value = values[i][0];
    if(value.charCodeAt(value.length-1)==10){
      value = value.substring(0,value.length-1);
    }


    // ">" at the end : the next item will be ignored
    if( value.indexOf(">") == value.length-1 ){
      value = value.substring(0,value.length-1); // string to add to the sentence = value alone without the skip flag
      indexes[i+1] = -1;
    }
    
    // the value has a specific genre : 
    // @1 = "MasculinSingulier"
    // @2 = "FémininSingulier"
    // @3 = "MasculinPluriel"
    // @4 = "FémininPluriel"
    if( value.indexOf("@") == 1 ){
      var genreBefore = value.substring(0,1); // genre identifier
      value = value.substring(2,value.length); // string to add to the sentence = value alone without genre flag
      indexes[i-1] = genreBefore-1;
    }
    if( value.indexOf("@") == value.length-2 && value.indexOf("@") >= 0 ){
      var genreAfter = value.substring( value.length-1,value.length); // genre identifier
      value = value.substring(0,value.length-2); // string to add to the sentence = value alone without genre flag
      indexes[i+1] = genreAfter-1;
    }    
   
    // the value have several items (for different genres)
    if( value.indexOf("/") != -1 ){
      isSingleGenre = false;
      genres = value.split( new RegExp("[/]+", "g") );
    }
    
    if(isSingleGenre){
      // the value have only one item (should be correct for all genres)
      genres[0] = value;
    }
    
    values[i] = genres;
  }

  // ---------------------------------------------------------------------------
  // 3) Build the final sentence
  for(i=0; i<values.length; i++) {
    var index = indexes[i];
    if( index >= 0 ){
      if( index < values[i].length ){
        chaine += values[i][index] + ' ';
      }else{
        chaine += values[i][0] + ' ';
      }
    }
  }

  // Set the final sentence in the result message
  var result = normalizeResultString(chaine);
	document.getElementById('generotronResult').innerHTML = result;
	
	// Updates links
	var generotronName = document.getElementById('generotronName').innerHTML;
	var subject = 'Résultat du générotron : ' + generotronName;
	var body = result+'     (http://generotron.tooliphone.net)';
	//var body = result+' %0d%0a '+generotronName+' http://generotron.tooliphone.net';
	
  // Mail
	chaineMail = 'mailto:?subject='+encodeURIComponent(subject)+'&body='+encodeURIComponent(body);
	document.getElementById('mailFriend').getElementsByTagName('a')[0].setAttribute('href', chaineMail);
  if( document.getElementById('mailFriendOutlook')!=null ){
	  chaineMailOutlook = 'mailto:?subject='+escape(subject)+'&body='+escape(body);    //Outlook
	  document.getElementById('mailFriendOutlook').getElementsByTagName('a')[0].setAttribute('href', chaineMailOutlook);
	}
	
  // SMS
  if( document.getElementById('smsFriend')!=null ){
  	chaineSms = 'sms:0000000000?body='+encodeURIComponent(body);
    document.getElementById('smsFriend').getElementsByTagName('a')[0].setAttribute('href', chaineSms);
  }
}          

           



function randomotron()
{
	if (navigator.appCodeName == "Mozilla" && eval(navigator.appVersion.substring(0,3)) >= 3)
	{
    for(i=1;i<=nbDataset;i++) {
      var item = document.getElementById('genDataset'+i+'Select');
      item.selectedIndex = getRandomNumber(nbItems[i]);
    }
  	generotron() ;
	}
	else
	{
    alert("\nDésolé, la version automatique de ce générotron n'est pas compatible avec votre navigateur...\nSeule la version manuelle est disponible.") ;
  }	
}	


function switchGenerotronManualChoiceDisplay()
{    
  for(i=1; i<=nbDataset; i++) {
    switchCheckDisplay('manualChoice', 'genDataset'+i);
  }
}

function switchCheckDisplay(checkItem, itemToSwitch)
{    
  var checkbox = document.getElementById(checkItem+'Input');
  var item = document.getElementById(itemToSwitch);
  
  if( checkbox.checked == true ){item.style.display = 'block';}
  else{item.style.display = 'none';}     
}

function switchDisplay(itemToSwitch)
{ 
  var item = document.getElementById(itemToSwitch);
  if( item!=null && item.style.display == 'block' ){
    item.style.display = 'none';
  } else {
    item.style.display = 'block';
  }
}

function getRandomNumber(max)
{
  var rand = Math.floor(1000 * Math.random());
  return rand % max; 
}

function normalizeResultString(result)
{
	voyels = 'aeiouyhéè' ;

  var resultString = "";
 
  var specialChar = result.indexOf("#"); 
  while( specialChar != -1 ){
    resultString += result.substring(0,specialChar);
    result = result.substring(specialChar+2,result.length);

    liaison = false;
	  for (j = 0 ; j<voyels.length ; j++){
      if (result.charAt(0) == voyels.charAt(j)) {
        liaison = true;
        break;  
      }
    }
    if (liaison){
      resultString += "'" ;
    } else{
      resultString += "e " ;
    }
    
    specialChar = result.indexOf("#");   
  }
  
  resultString += result;
  return resultString;
}

