var draggablesUrls = $H();
var droppablesUrls = $H();
var windowsUrls = $H();

function setAlternativeVisibility(currentAlternative,alternativeGroup){

   var divisions = document.getElementsByTagName('div');
   for(i=0;i<divisions.length;i++){
       if((divisions[i].getAttribute('alternative')!=null) && (divisions[i].getAttribute('alternative') == alternativeGroup)){
              if(divisions[i].id != currentAlternative){
                  //console.log(divisions[i]);
                  divisions[i].style.display="none";
              }
       }
  }
}

function getCheckedValue(radioObj) {

	if(!radioObj)
		return '';
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return '';
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
      

function getMultiselectionFieldAsCheckboxValues(multiObj) {
	if(!multiObj)
		return '';

  var total="";
  for(var i=0; i < multiObj.length; i++){
    
    if(multiObj[i].checked){
      if(i > 0 && total != ''){
        total += ",";
      } 
      total += multiObj[i].value       
    }
    
  }         
  return total;
} 

      
function getMultiselectionFieldAsSelectValues(multiObj) {
	if(!multiObj)
		return ''

  var total="";
  for(var i=0; i < multiObj.length; i++){
    if(multiObj.options[i].selected){
      if(i > 0 && total != ''){
        total += ",";
      } 
      total += multiObj.options[i].value;       
    }
  }           
  return total;
}


function searchCells(text,matchSequence,unitSequence){

  var cells = text.split(matchSequence);
  cells = $A(cells);
  cells = cells.reject(function (elem) {return elem.indexOf(unitSequence) < 0});
  return cells;
}

function searchUnits(text){
  var unit= new Array();
  var content= new Array();
  var map = $H();
  text.each(function (list, index1){

  if(index1 != 0){
    if(index1 % 2 != 0){  
         
          unit.push(list);
    }
    else{
          
          content.push(list);                 
    }
   }            
  }
  );
  map = map.merge({"id":unit});
  map = map.merge({"content":content});
  return map;
}
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function updateUnits(idunits,contentunits){
  idunits.each(function(element,index){
if($(element)){
    if($(element).getAttribute('unit')){
      var fieldsCode = contentunits[index].split('!!!!');
      
      ////console.log("xxxx"+trim(fieldsCode[0])+"yyyy")
      if(trim(fieldsCode[0])!=''){
      ////console.log($(element))
        ////console.log(element + "ddddd" + fieldsCode[0] + "fff");      
        Element.update($(element), fieldsCode[0]);
      }
      var fields = new Array();
      var fieldsContent= new Array();
      
      fieldsCode.each(function (list, indice){
      
          if(indice != 0){
            if(indice % 2 != 0){  
                
                  fields.push(list);
            }
            else{
                  
                  fieldsContent.push(list);                 
            }
           }  
      });
      fields.each(function (list, indice2){
        
        if($(list)){ 
        
        ////console.log("Sto aggiornando il campo " + list);
         ////console.log($(list));
         ////console.log(fieldsContent[indice2]);
          Element.update($(list), fieldsContent[indice2]);
          
        }
      });
    
    }else{
      ////console.log("Aggiorno la unit " + element);
      
      ////console.log($(element));
      ////console.log(contentunits[index]);
      
      Element.update($(element), contentunits[index]);
    } 
  }});
}

function computeRequest(request) {
  
  var response = request.responseText;
  
  var submitLinks = response.split("$!$!")[1]; 
  
  if($('submit-links'))
  {Element.update($('submit-links'),submitLinks);}
  
  var cellsCode = searchCells(response,'***','||||');
  
  var cellContent=''; 
  var cell='';
  cellsCode.each(function (code) {

    var temp = code.split('||||');
    temp.each(function(temp1, index){
      if(index==1){
         cell=$(temp1);
      }
      if(index == 2){
  
        cellContent = temp1;  

        var subpages = cellContent.indexOf('@@@@');
        var alternatives = cellContent.indexOf('%%%%');
        //se non ci sono sottopagine
        if((subpages == -1) && (alternatives == -1)){
          ////console.log("Non ci sono sottopagine ne alternative");
          //cerco le unit
          if(cellContent.indexOf('####')!=-1){            
              var unitsCode = cellContent.split('####');
              var m = searchUnits(unitsCode);
              ////console.log(unitsCode);
              ////console.log(m["id"]);
              ////console.log($(m["id"]));
              
              updateUnits(m["id"],m["content"]);

         }
        }else if(alternatives != -1){
           ////console.log("Ho trovato alternative");
           var alternativeCode = cellContent.split('%%%%');
           ////console.log(alternativeCode);
           var alternativeName = '';
           var alternativeContent = '';
           alternativeCode.each(function(alternative,indice){
               if(indice != 0){////console.log("sono ciclo");
                  if(indice % 2 != 0){
                  ////console.log("sono if");
                     alternativeName = alternative;
                     
                  }else{
                  ////console.log("sono else");
                     alternativeContent = alternative;
                     //console.log(alternativeName);
                     //console.log(alternativeContent);
                     
                     
                     var gruppo = $(alternativeName).getAttribute('alternative');
                     setAlternativeVisibility(alternativeName,gruppo);                                     
                     $(alternativeName).style.display="block";
                     
                    var preamboloName = '';
                    var preamboloCode =''; 
                    if(alternativeContent.indexOf('????')!= -1 ){
          
                       var t = alternativeContent.split('????');
                       preamboloName = t[1];
                       preamboloCode = t[2];
                       preamboloCode = preamboloCode.substring(0, preamboloCode.indexOf('$$$$'));
                      
                       if (preamboloCode != ''){
                       Element.update($(preamboloName),preamboloCode);
                       }
                    }  
                    if(alternativeContent.indexOf('$$$$')!=-1){
                        var subCellsCode = searchCells(response,'$$$$','++++');
                        var subCellContent=''; 
                        var subCell='';
                        
                        subCellsCode.each(function (code,index3) {             
                        var temp = code.split('++++');             
                        temp.each(function(temp1, index){
                          if(index==1){
                             subCell=$(temp1);
                          }
                          if(index == 2){
                            
                            subCellContent = temp1; 
                            if(subCellContent.indexOf('^^^^')!=-1){
                            ////console.log("Ho trovato un alternative dentro ad un alternative");
                     var alternativeCode = cellContent.split('^^^^');
                     ////console.log(alternativeCode);
                     var alternativeName = '';
                     var alternativeContent = '';
                     alternativeCode.each(function(alternative,indice){
                         if(indice != 0){////console.log("sono ciclo");
                            if(indice % 2 != 0){
                            ////console.log("sono if");
                               alternativeName = alternative;
                               
                            }else{
                            ////console.log("sono else");
                               alternativeContent = alternative;
                               ////console.log(alternativeName);
                               ////console.log(alternativeContent);
                               var gruppo = $(alternativeName).getAttribute('alternative');
                               setAlternativeVisibility(alternativeName,gruppo);                                     
                               $(alternativeName).style.display="block";

                                       var preamboloName = '';
                  var preamboloCode =''; 
                  if(alternativeContent.indexOf('????')!= -1 ){
                     ////console.log("preambolo");
                     
                     var t = alternativeContent.split('????');
                     preamboloName = t[1];
                     preamboloCode = t[2];
                     preamboloCode = preamboloCode.substring(0, preamboloCode.indexOf('$?$?'));
                    
                     if (preamboloCode != ''){
                     Element.update($(preamboloName),preamboloCode);
                     }
                  }  if(alternativeContent.indexOf('$?$?')!=-1){
                        var subCellsCode = searchCells(response,'$?$?','----');
                        var subCellContent=''; 
                        var subCell='';
                        ////console.log(subCellsCode);
                        subCellsCode.each(function (code,index3) {             
                        var temp = code.split('----');             
                        temp.each(function(temp1, index){
                          if(index==1){
                             subCell=$(temp1);
                          }
                          if(index == 2){
                            
                            subCellContent = temp1;  
                           
                              if(subCellContent.indexOf('####')!=-1){            
                                  var unitsCode = subCellContent.split('####');
                                  var m = searchUnits(unitsCode);
                                  ////console.log("chiamo update");
                                  updateUnits(m["id"],m["content"]);
                                  
                                 
                            }
                          }
                        }
                       );  
                      });
                    }
                            
                            }
          
                          
                         }
                          
                     });                        
                                  
                              }
                              else if(subCellContent.indexOf('####')!=-1){            
                                  var unitsCode = subCellContent.split('####');
                                  var m = searchUnits(unitsCode);
                                  updateUnits(m["id"],m["content"]);
                                  
                                 
                            }
                          }
                        }
                       );  
                      });
          }
                  
                  }

                
               }
                
           });
        }else{        
          
          var subpagesCode = cellContent.split('@@@@');
         
          var subpageName = '';
          var subpageContent = '';
          subpagesCode.each(function(subpage,index2){
            if(index2 == 1){
              subpageName = $(subpage);
            }
            if(index2 == 2){
              subpageContent = subpage;
            }
          
          });
          
         
        var preamboloName = '';
        var preamboloCode =''; 
        if(subpageContent.indexOf('????')!= -1 ){
          
           var t = subpageContent.split('????');
           preamboloName = t[1];
           preamboloCode = t[2];
           preamboloCode = preamboloCode.substring(0, preamboloCode.indexOf('$$$$'));
          
           if (preamboloCode != ''){
           Element.update($(preamboloName),preamboloCode);
           }
        }  if(subpageContent.indexOf('$$$$')!=-1){
              var subCellsCode = searchCells(response,'$$$$','++++');
              var subCellContent=''; 
              var subCell='';

              subCellsCode.each(function (code,index3) {             
              var temp = code.split('++++');             
              temp.each(function(temp1, index){
                if(index==1){
                   subCell=$(temp1);
                }
                if(index == 2){
                  
                  subCellContent = temp1;  
                    if (subCellContent.indexOf('^^^^')!=-1){
                        ////console.log("Ho trovato un alternative in una sottopagina");
                        
           var alternativeCode = cellContent.split('^^^^');
           ////console.log(alternativeCode);
           var alternativeName = '';
           var alternativeContent = '';
           alternativeCode.each(function(alternative,indice){
               if(indice != 0){////console.log("sono ciclo");
                  if(indice % 2 != 0){
                  ////console.log("sono if");
                     alternativeName = alternative;
                     
                  }else{
                  ////console.log("sono else");
                     alternativeContent = alternative;
                     ////console.log(alternativeName);
                     ////console.log(alternativeContent);
                     var gruppo = $(alternativeName).getAttribute('alternative');
                     setAlternativeVisibility(alternativeName,gruppo);                                     
                     $(alternativeName).style.display="block";
            
                 
                             var preamboloName = '';
        var preamboloCode =''; 
        if(alternativeContent.indexOf('????')!= -1 ){
           ////console.log("preambolo");
           
           var t = alternativeContent.split('????');
           preamboloName = t[1];
           preamboloCode = t[2];
           preamboloCode = preamboloCode.substring(0, preamboloCode.indexOf('$?$?'));
          
           if (preamboloCode != ''){
           Element.update($(preamboloName),preamboloCode);
           }
        }  if(alternativeContent.indexOf('$?$?')!=-1){
              var subCellsCode = searchCells(response,'$?$?','----');
              var subCellContent=''; 
              var subCell='';
              ////console.log(subCellsCode);
              subCellsCode.each(function (code,index3) {             
              var temp = code.split('----');             
              temp.each(function(temp1, index){
                if(index==1){
                   subCell=$(temp1);
                }
                if(index == 2){
                  
                  subCellContent = temp1;  
                 
                    if(subCellContent.indexOf('####')!=-1){            
                        var unitsCode = subCellContent.split('####');
                        var m = searchUnits(unitsCode);
                        ////console.log("chiamo update");
                        updateUnits(m["id"],m["content"]);
                        
                       
                  }
                }
              }
             );  
            });
          }
                  
                  }

                
               }
                
           });                        
                        
                    }
                    else if (subCellContent.indexOf('####')!=-1){            
                        var unitsCode = subCellContent.split('####');
                        var m = searchUnits(unitsCode);
                        updateUnits(m["id"],m["content"]);
                        
                       
                  }
                }
              }
             );  
            });
          }
        }
      }
    }
   );  
  }
  
  );

  if(Dialog != null){
    Dialog.closeInfo();
  }
  }
  
function createWindow(window, title, style, resizable, closable, minimizable, maximizable, draggable, modal) {
  var init = new Date();
  var res = true;
  var min = true;
  var max = true;
  var close = true;
  var drag = true;
  var mod = false;
  var css = "dialog";
  
  if(resizable == "false"){
    res = false;
  }
  if(closable == "false"){
    close = false;
  }
  if(minimizable == "false"){
    min = false;
  }
  if(maximizable == "false"){
    max = false;
  }
  if(draggable == "false"){
    drag = false;
  }
  if(style != ''){
    css = style;
  }  
  if(modal == 'true'){
    mod = true;
  }  
  
  
  var win = new Window(window, {className: css,  zIndex: 1000000000, resizable: res, maximizable: max, minimizable:min, closable:close,   title: title, hideEffect:Element.hide, showEffect:Element.show, draggable:drag})              
  
  var nn = window + "Content";
  win.setContent(nn, true, true);        
  win.toFront();            
  win.setDestroyOnClose();   
  win.showCenter(mod);   
  // Set up a windows observer, check ou debug window to get messages 
  myObserver = { 
    onDestroy: function(eventName, w) { 
      if(w == win) {
        w = null; 
        $(nn).style.display="none";
        Windows.removeObserver(this); 

      }
    } 
    } 
    
 
    Windows.addObserver(myObserver); 
    var date = new Date();

}



function addDroppable(id, linkId, page, style) {
  if($(id)!=null){
    
    Droppables.add(id, {hoverclass: style , onDrop: 
      function(element, droppableElement) {
       var queryString = $H();
       var linkSource = linkId != null ? linkId : "";
       var draggedUrl = element.id + 'queryString';
       
       var droppedUrl = droppableElement.id + linkSource +'queryString';
       var dragQueryString = draggablesUrls[draggedUrl];
       var dropQueryString = droppablesUrls[droppedUrl];
       if (dragQueryString.to == dropQueryString.to) {
        queryString = queryString.merge(dragQueryString);
        queryString = queryString.merge(dropQueryString);

        new Ajax.Request(dropQueryString.to, {postBody: queryString.toQueryString(),onSuccess: function(request) {
            computeRequest(request);
          }
        });
       } else {
       }
      }
  
  });
  }
}
