var isIeb = util_isIeP();
var isMac = util_isMacP();
if (isIeb) {
	css = "<link rel=STYLESHEET TYPE=\"Text/CSS\" HREF=\"../style/explorerstyle.css\">";
} else {
	css = "<link rel=STYLESHEET TYPE=\"Text/CSS\" HREF=\"../style/netscapestyle.css\">";
}
document.write(css);

// INIT
var usedLang = 0;
var DateType = 0;
var startIdx = -1;
var isFromSearch = 1;
var numPage = 1;
var error = "";
var a = new Array();
var p = new Array();
var o = new Array();
var d = new Array();

var objidArr = new Array();
var resultArray = new Array();
var pdfImage = "../pics/pdf.gif";

var showmode = 0;
var lastArticleClicked = null;

//the array is set in LOOP below it will look like this:
//resultArray[1]= new Array(8,6,'C05','The Courier Journal','20070130','','full','nitf');

if (parent.contents && parent.contents.pdfImage && parent.contents.pdfImage != "") pdfImage = parent.contents.pdfImage;

// if popup
if (opener && opener.parent && opener.parent.button) {
   window.moveTo(0,0);
   window.focus();
}

// get customization
if (parent.contents && parent.contents.getLanguage) usedLang = parent.contents.getLanguage();
else if (opener && opener.parent.contents && opener.parent.contents.getLanguage) usedLang = opener.parent.contents.getLanguage();

if (parent.contents && parent.contents.getDateType) DateType = parent.contents.getDateType();
else if (opener.parent.contents && opener.parent.contents.getDateType) DateType = opener.parent.contents.getDateType();

/* Functions */
function search_getObjIdArr() {
   var toRet = "";
   for (var i=0;i<objidArr.length;i++) {
      toRet += objidArr[i];
      if (i<objidArr.length-1) { toRet += ","; }
   }   
   return toRet;
}   
function search_downloadPDF(lFile) {

   var inFile;
   var theFile;
   var pos;
   
   //alert("phodir:"+lFile);

   inFile = lFile.toLowerCase();
   inFile = path_normalize(inFile);
   pos = inFile.lastIndexOf(".pdf.");
   if ( pos>0 ) {
      theFile = inFile.substring(0,pos+4);
      var pdfURL  = "../php-script/down_pdf.php?file=" + escape(theFile);
      var archiveName = parent.contents.getFormObj("list").options[parent.contents.getFormObj("list").selectedIndex].value;
      pos = theFile.lastIndexOf("/");
      filename = theFile;
      if (pos>-1) {
         filename = theFile.substr(pos+1);
      }
      archiveName += "_"+filename;
      archiveName = archiveName.replace(" ","_");
      archiveName = archiveName.toLowerCase();
 
      pdfURL += "&filename="+archiveName;
      pdfURL += "&startDownload=1&pSetup="+parent.contents.pSetup;
      window.open(pdfURL,"Download","WIDTH=330,HEIGHT=100");
      window.close();
   }
}

function pd_getNum(p) {
   var i, toRet, maxPage;
   var endPos, incPage;
   var maxPage;

   toRet = new Array();
   for(i=0;i<p.length;i++) {
      //  place roman numerals at end
      if ( parent.contents && parent.contents.isRomanNumber && parent.contents.isRomanNumber(p[i].page) ) {
         maxPage = parent.contents.calcMaxPage();
         pageIndex = parent.contents.convertRomanNumber(p[i].page) + maxPage;  
      //calculate new section weight 
      } else if ( parent.contents && parent.contents.calculateLetterWeight &&
           parent.contents.isLetter && parent.contents.isLetter(p[i].page) ) {
           pageIndex = parent.contents.calculateLetterWeight(p[i].page.charCodeAt(0)) + parseInt(p[i].page.substring(1,p[i].page.length),10);  
           //alert("letter:" + pageIndex);
      } else {
         pageIndex = parseInt(p[i].page,10);
         //alert("normal:" + pageIndex);
      }
      
      toRet[pageIndex] = i;
      //if(p[i].type == 1){ 
      if(p[i].type >= 1){ 
         toRet[pageIndex + 1] = i;
         type1 = true;  //there
         //alert ("DOUBLE PAGE " + p[i].page);
      }
      //alert(toRet[pageIndex]+ "\n" + pageIndex);
   }
   return toRet;
}

function pd_downloadcheckedPDF() {
   if (document.all) 
   	document.body.style.cursor = 'wait';
      
   document.dwnForm.pSetup.value= parent.contents.pSetup;
   //if (rules == "tn") document.dwnForm.rules.value ="tn";

/*   
   var archiveData = parent.contents.getFormObj("selDate").options[parent.contents.getFormObj("selDate").selectedIndex].value;
   pos = archiveData.lastIndexOf("/");
   if(pos != -1) { archiveData = archiveData.substring(pos+1); }
*/
   var archiveName  = parent.contents.getFormObj("list").options[parent.contents.getFormObj("list").selectedIndex].value;
   archiveName     += "_"+ tosearch +"_"+ fromdate +"_"+ todate;
   archiveName = archiveName.replace(" ","_");   
   archiveName = archiveName.toLowerCase();
      
   document.dwnForm.archiveName.value= archiveName;  
   
   document.dwnForm.language.value= parent.contents.Lang;
   
   //document.dwnForm.action='../php-script/multipleDownloadPdf.php';
   document.dwnForm.action='../php-script/down_selected.php';
      
   document.dwnForm.submit();
}

var checkAllPdf = true;

function toggleCheckedPdf()
{
   var checks=document.getElementsByName("checkedpdf[]");
  
   for(i=0;i<checks.length;i++){
      checks[i].checked = checkAllPdf;   
   }
   
   checkAllPdf = checkAllPdf ? false : true;
}

function search_drawPage(toSearch, resultPerPage, page, showEclip) {
   var toW = "";
   var text2Write = "";
   var text2write2 = "";
   var js2write = ""; //this is to be used to load a particular index.
   js2write += "<script language=\"javascript\">\n";

   var now, now2;
   
   if (parent.opener && parent.opener.searchLoaded) {
      parent.opener.searchLoaded(1);
   } else {
      if (parent.contents.searchLoaded) {
         parent.contents.searchLoaded(1);
      }
   }
   
   //alert("PAGE: "+page);
   
   if(page > 0){
   
   	var searchArray = parent.contents.getSearchArrays();
   	o=searchArray[0];
   	p=searchArray[1];
   	a=searchArray[2];
	   d=searchArray[3];
   	page=page-1;
  	
	}

	firstResult= 0;
	lastResult = 0;

	if(hits > 0){
		firstResult= page*resultPerPage;
		lastResult = firstResult + resultPerPage;
	}
	
	//alert("FIRST"+firstResult);
	//alert("LAST"+lastResult);
   
   //alert("HITS: "+hits );

   toW+="<form name=dwnForm method=post action='../php-script/down_selected.php'>";
   toW+="<input type=hidden name=rules value=''>";
   toW+="<input type=hidden name=pSetup value=''>";
   toW+="<input type=hidden name=archiveName value=''>";
   toW+="<input type=hidden name=language value=''>";
   toW+="<input type=hidden name=file value=''>";
      
   if (hits > 0) {
	   toW += '<table border="0" cellpadding="3" cellspacing="3" width="100%">\n';
   } else {
	   toW += '<table border="0" cellpadding="3" cellspacing="3">\n';
   }
   toW += '<tr><td valign="top" colspan="4"><br></td></tr>\n';
   if (hits > 0) {
   	if(lastResult > hits)
   		lastResult=hits;
      text2Write = "";
      
      switch (usedLang) {
         case 1 : text2Write = "Trovato(i) " + hits + " articolo(i)"; break;
         case 2 : text2Write = "Gefunden: " + hits + " Artikel"; break;
         case 3 : text2Write = "Trouvé: " + hits + " articles"; break;
         case 4 : text2Write = "Gevonden: " + hits + " artikel(en)"; break;
         case 7 : text2Write = "Hittad: " + hits + " articles"; break;
         case 8 : text2Write = "fundet: " + hits + " arikel"; break;
         case 0 :
         default: text2Write = "Found " + hits + " article(s)"; break; //e-
      }
      
      if(hits>=iMaxResults) { 
         switch (usedLang) {
            case 1 : alertNumber = "Vengono mostrati solo i primi " + iMaxResults + " risultati"; break;
            case 2 : alertNumber = "Nur die erste " + iMaxResults + " Artikel werden gezeigt"; break;
            case 3 : alertNumber = "Trouvé: " + iMaxResults + " articles"; break;
            case 7 : alertNumber = "Hittad: " + iMaxResults + " articles"; break;
            case 8 : alertNumber = "fundet: " + iMaxResults + " arikel"; break;
            case 0 :
            default: alertNumber = "Only first " + iMaxResults + " results are showed"; break; //e-
         }
         hits=iMaxResults;
         text2Write=alertNumber+"<br><br>"+text2Write;
      }
   	toW += '<tr><td colspan="4" align="left" valign="bottom" class="testorossobold">' + text2Write;
   	if (todate!="" && fromdate !="") {
   	   text2Write = "";
   	   switch (DateType) {
   	      case "1" : text2Write = fromdate.substring(4,6) + '/' + fromdate.substring(6,8) + '/' + fromdate.substring(0,4); break;
   	      case "2" : text2Write = fromdate.substring(4,7) + ' ' + fromdate.substring(0,4); break;
   	      case "0" :
   	      default: text2Write = fromdate.substring(6,8) + '/' + fromdate.substring(4,6) + '/' + fromdate.substring(0,4); break;

   	   }
   	   switch (usedLang) {
   	      case 1 : toW += " dal " + text2Write; break;
   	      case 2 : toW += " von " + text2Write; break;
   	      case 3 : toW += " de " + text2Write; break;
   	      case 4 : toW += " van " + text2Write; break;
  	         case 7 : toW += " från " + text2Write; break;
   	      case 0 :
   	      default: toW += " from " + text2Write; break; //e-

   	   }

   	   text2Write = "";
   	   switch (DateType) {
   	      case "1" : text2Write = todate.substring(4,6) + '/' + todate.substring(6,8) + '/' + todate.substring(0,4); break;
   	      case "2" : text2Write = todate.substring(4,7) + ' ' + todate.substring(0,4); break;
   	      case "0" :
   	      default: text2Write = todate.substring(6,8) + '/' + todate.substring(4,6) + '/' + todate.substring(0,4); break;

   	   }
   	   switch (usedLang) {
   	      case 1 : toW += " al " + text2Write; break;
   	      case 2 : toW += " bis " + text2Write; break;
   	      case 3 : toW += " à " + text2Write; break;
   	      case 4 : toW += " tot " + text2Write; break;
   	      case 7 : toW += " till " + text2Write; break;
   	      case 0 :
   	      default: toW += " to " + text2Write; break; //e-

   	   }
      } else if (datelim!="" && datelim.length == 8) {
	  
			text2Write = "";	   
			switch (DateType) {
				case "1" : text2Write = datelim.substring(4,6) + '/' + datelim.substring(6,8) + '/' + datelim.substring(0,4); break;
				case "2" : text2Write = datelim.substring(4,7) + ' ' + datelim.substring(0,4); break;
				case "0" :
				default: text2Write = datelim.substring(6,8) + '/' + datelim.substring(4,6) + '/' + datelim.substring(0,4); break;
			}
	  
   	   switch (usedLang) {
				case 1 : toW += " del " + text2Write; break;
				case 2 : toW += " of " + text2Write; break;
				case 3 : toW += " du " + text2Write; break;
   	      case 0 :
				default: toW += " of the " + text2Write; break;
   	   }
   	}
      toW += '</td></tr>\n';
   }

   switch (usedLang) {
    case 1 :
      checkUnchecklabel = "Seleziona/Deseleziona tutti i PDF";
      downCheckLabel = "Scarica pdf selezionati"; break;
    case 2 :
      checkUnchecklabel = "Markieren/Entmarkieren alle PDF";
      downCheckLabel = "Markierte Seiten herunterladen"; break;
    case 3 :
      checkUnchecklabel = "Cocher/Décocher toutes les PDF";
      downCheckLabel = "Téléchargez les pages sélectionnées"; break;
    case 4 :
      checkUnchecklabel = "Check/Uncheck all PDF";
      downCheckLabel = "Download geselecteerde pdf"; break;
    case 5 :
      checkUnchecklabel = "Check/Uncheck all PDF";
      downCheckLabel = "Download selected pdf"; break;
    case 6 :
      checkUnchecklabel = "Check/Uncheck all PDF";
      downCheckLabel = "Last ned valgt pdf"; break;
    case 7 :
      checkUnchecklabel = "Check/Uncheck all PDF";
      downCheckLabel = "Nerladda vald pdf"; break;
    case 8 :
      checkUnchecklabel = "Check/Uncheck all PDF";
      downCheckLabel = "download udvalgte pdf"; break;
    case 0 :
    default: 
      checkUnchecklabel = "Check/Uncheck all PDF";
      downCheckLabel = "Download selected pdf"; break;
   }

   if (typeof(downloadPDF) != 'undefined' && parseInt(downloadPDF,10)>0) {
	   toW += '<tr><td colspan="4" align="left" valign="bottom" class="testorossobold">';
	   toW += '<a href="javascript:toggleCheckedPdf();">'+ checkUnchecklabel +'</a><br />';
	   toW += '<a href="javascript:pd_downloadcheckedPDF();">' + downCheckLabel + '</a>';
	   toW += '</td></tr>\n';
   }
   var hstyle = "class=\"art\"";
   //if (isIeb) hstyle = "style=\"color: black; text-decoration: none;\"";
   var prevDay = "";
   if (startIdx < 0) startIdx = 1;
   startIdx= firstResult +1;
   //for (var i=0;i<a.length;i++) {
   for (var i=firstResult;i<lastResult;i++) {
      var title = day = id = aCat = suptit = subtit = "";
      var type="full";
      var filetype="";
      var imgUrl = "";
      var baseUrl = "";
      /* Extract from d array the right url */
      var pathIndex = o[i].substr(0, 1);
      //alert(pathIndex);
      var filePath = o[i].substr(2);
      if (pathIndex<d.length) {
         baseUrl = d[pathIndex];
         //alert(pathIndex+"-"+baseUrl);
         arr = o[i].substr(2).split("/");
         var datepath = arr[arr.length-3];
         // Change URL when it's on archive
         //alert(datepath);
         if (pathIndex>2) {
            filePath = "";
            for (x=0; x<arr.length; x++) {
               if (x!=0) { filePath += "/"; }
               if (x!=arr.length-3) { 
                  filePath += arr[x]; 
               } else {
                  filePath += arr[x].substr(0,4)+"/"+arr[x].substr(4,2)+"/"+arr[x]; 
               }
            }
         }
         //alert(baseUrl);
      }
      //if isdigit()
      
      //alert(baseUrl + filePath + 'low.jpg');
      imgUrl = baseUrl + filePath + 'low.jpg';
      //alert(a);
      sec = "";
      suptit = "";
      title = "";
      subtit = "";
      day = "";
      id  = 0;
      aCat = "";
      numPage = page = 0;
      filetype = "";
      for (var k=0; k<a[i].e.length;k++) {
         switch (a[i].e[k].type) {
            case 10: { suptit = util_clearBlanks(p[a[i].e[k].link].S[0].textV) ; break ; }
            case 11: { title = util_clearBlanks(p[a[i].e[k].link].S[0].textV) ; if(p[a[i].e[k].link].S[1]) type="light"; break ; }
            case 12: { subtit = util_clearBlanks(p[a[i].e[k].link].S[0].textV) ; break ; }
            case 3: { day = p[a[i].e[k].link].S[0].textV ; break ; }
            case 4: { id = p[a[i].e[k].link].S[0].textV ;  break ; }
            case 6: { aCat = parseInt(p[a[i].e[k].link].S[0].textV,10) ; break ; }
            case 7: { numPage = page = p[a[i].e[k].link].S[0].textV ; break ; }
            case 9: { sec = p[a[i].e[k].link].S[0].textV ; break ; }
            case 13: { filetype = util_clearBlanks(p[a[i].e[k].link].S[0].textV) ; break ; }
            default : break;
         }
         //alert("ID IS " + id);
      }


      //****************************************//
      if ((datelim!="" && todate=="" && fromdate=="") || prevDay == day) {
         toW += "<tr bgcolor=\"#F2F2F2\">\n";
      } else {
         toW += "<tr bgcolor=\"#F2F2F2\"><td class=\"testorossobold\" colspan='4' align='center'>";
   	   text2Write = "";
   	   switch (DateType) {
   	      case "1" : text2Write = day.substring(4,6) + "/" +day.substring(6,8) + "/" + day.substring(2,4); break;
   	      case "2" : text2Write = day.substring(4,7) + "  " + day.substring(0,4); break;
   	      case "0" :
   	      default: text2Write = day.substring(6,8) + "/" +day.substring(4,6) + "/" + day.substring(2,4); break;

   	   }

         toW += "<b>" + text2Write + "</b></td></tr>";
         toW += "<tr bgcolor=\"#F2F2F2\">\n";
      }
         toW += "<td align=\"left\" valign=\"top\" ><b>" + (startIdx++) + ")</b></td>";

      text2Write = "";
      switch (usedLang) {
         case 1 : text2Write = "Pag. "; break;
         case 2 : text2Write = "Seite "; break;
         case 3 : text2Write = "Page "; break;
         case 4 : text2Write = "Pagina "; break;
         case 7 : text2Write = "Sida "; break;
         case 0 :
         default: text2Write = "Pg "; break; //e-
      }
      
      var eclipframe="";
      if(showEclip == 1){
      	var re = new RegExp('"','g');
      	//var toS= toSearch.replace(re,'\\"');
      	var toS= toSearch.replace(re,'--');      		
      	eclipframe="reloadEclipFrame('"+pSetup+"','"+o[i]+"','"+toS+"');";
      	  
      }
      
      if (type!="full") {
         toW += "<td align=\"left\" valign=\"top\">";
         toW += "<A href=\"#\" class=\"testorossobold\" onClick=\""+eclipframe+"loadart("+ i + "," + id + ",'" + page + "','" + sec + "','" + day + "','" + aCat + "','" + type + "','" + filetype + "');return false;\">";
         toW += "<img src='"+imgUrl+"'>";
         toW += "</a></td>";
      }
      

      toW += "<td align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"testorossobold\">";
      if (typeof(downloadPDF) != 'undefined' && parseInt(downloadPDF,10)) {
         toW += "<a href='javascript:search_downloadPDF(\"" +o[i]+ "\")'><img border='0' width='16' src='" + pdfImage + "' alt='" + "downloadLabel" + "' ></a>\n";
         try {
            tmpstr = o[i].replace(/\/$/, '');
            var parts = tmpstr.split('/');
            tmppdfurl = parts[0] + '/' + parts[1] + '/' + parts[2] + '/' + parts[3] + '#' + day + '_' + page + '_' + sec;
         } catch(e) {}
         toW += "<input name=\"checkedpdf[]\" type=\"checkbox\" value=\"" +tmppdfurl+ "\"  /> ";
      }
      toW += "</td>";


      toW += "<td ";
      //if (sec == "") { toW += " nowrap=\"nowrap\" "; }
      toW += " nowrap=\"nowrap\"";
      toW += " align=\"left\" valign=\"top\" class=\"testorossobold\">";
      
      if (parent && parent.contents && parent.contents.pageNumberTransposition){ 
         pageNumberTransposition = parent.contents.pageNumberTransposition; // array with transposition of old page numbers at key locations of there new page number
         page = pageNumberTransposition[removeExtraZeros(page)];
         page = removeExtraZeros(page)
      }
      toW += "<A href=\"#\" class=\"testorossobold\" onClick=\""+eclipframe+"loadart("+ i + "," + id + ",'" + page + "','" + sec + "','" + day + "','" + aCat + "','" + type + "','" + filetype + "');return false;\">" + text2Write + page;
      if (sec != "") { toW += " <br /> " + unescape(sec); } 
      toW += "</a>";
      toW += "</td>";
      prevDay = day;


      switch (aCat) {
         case 4 : {
            //alert("../php-script/get_image.php?pSetup=" + pSetup+ "&file=" + escape(o[i]) +"&artId=" + id);
            toW += "<td align=\"left\" valign=\"top\"><A href=\"#\" " + hstyle + " onClick=\""+eclipframe+"loadart("+ i + "," + id + ",'" + page + "','" + sec + "','" + day + "','" + aCat + "','" + type + "','" + filetype + "');return false;\">";
            toW += "<img border=\"0\" src='../php-script/get_image.php?pSetup=" + pSetup+ "&file=" + escape(o[i]) +"&artId=" + id + "'></A></td>"; 
            break;
         }   
         default: { 
            // If tilte == Title get information from remote_xText call
            if (title == 'Title' || title == 'title') {
               if (parent.contents.saveCalled[i]) {
                  title = parent.contents.saveCalled[i];
               } else {
                  //if (i==10) {
                     addFileToRemotexText(i, o[i]);
                     title = 'Loading....';
                  //}
               }
            }
   
            if(type=="full"){
               //resultArray[1]= new Array(8,6,'C05','The Courier Journal','20070130','','full','nitf');
               
               js2write += "resultArray["+ i +"] = new Array("+ i + "," + id + ",'" + page + "','" + sec + "','" + day + "','" + aCat + "','" + type + "','" + filetype + "');\n";
               toW += "<td align=\"left\" valign=\"top\"><A href=\"#\" " + hstyle + " onClick=\""+eclipframe+"loadart("+ i + "," + id + ",'" + page + "','" + sec + "','" + day + "','" + aCat + "','" + type + "','" + filetype + "');return false;\">\n"; 
               if (suptit !="") toW += suptit + "<BR>";
               toW += "<b>" + title + "</b><BR>";
               if (subtit !="") toW += subtit;
               toW += "</A></td>";
            }else{
               toW += "<td align=\"left\" " + hstyle + " valign=\"top\">\n"; 
               toW += "<div id=\"remote_xtext_" + i + "\">" + title + "</div><BR>";
               toW += "</td>";
            }
            break;
         }   
      }            

      //toW += "<td align=\"left\" valign=\"top\"><A href=\"#\" " + hstyle + " onClick=\"loadart("+ i + "," + id + ",'" + page + "','" + sec + "','" + day + "');return false;\">\n";
      //if (suptit !="") toW += suptit + "<BR>";
      //toW += "<b>" + title + "</b><BR>";
      //if (subtit !="") toW += subtit;
      //toW += "</A></td></tr>";
      toW += "</tr>";
   }
   //alert(a.length);
   if (!a.length) {
      if (hits == -1) {
         text2Write = "";
         switch (usedLang) {
            case 1 : text2Write = "Troppi articoli trovati"; break;
            case 2 : text2Write = "Too many articles found!"; break;
            case 3 : text2Write = "Trop d'articles trouvés!"; break;
            case 4 : text2Write = "Er zijn te veel artikelen gevonden!"; break;
            case 7 : text2Write = "För många artiklar har hittats!"; break;
            case 0 :
            default: text2Write = "Too many articles found!"; break; //e-
         }
         toW += "<tr><td colspan='2' class=\"testorossobold\"><b>" + text2Write + "</b></td></tr>";

         text2Write = "";
         switch (usedLang) {
            case 1 : text2Write = "Riformula la ricerca"; break;
            case 2 : text2Write = "Please refine the search."; break;
            case 3 : text2Write = "Reformuler la recherche."; break;
            case 4 : text2Write = "Verfijn a.u.b. uw zoekopdracht aan"; break;
            case 7 : text2Write = "Var snäll och förbättra sökningen."; break;
            case 0 :
            default:text2Write = "Please refine the search."; break; //e-
         }
         toW += "<tr><td colspan='2'><b>" + text2Write + "</b><br></td></tr>";
      } else {
         text2Write = "";
         switch (usedLang) {
            case 1 : text2Write = "Nessun articolo trovato"; break;
            case 2 : text2Write = "Kein Artikel Gefunden:"; break;
            case 3 : text2Write = "Aucun article trouvé:"; break;
            case 4 : text2Write = "Er zijn geen artikelen gevonden"; break;
            case 7 : text2Write = "Ingen artikel har hittats:"; break;
            case 0 :
            default:text2Write = "No articles found:"; break; //e-
         }
         toW += "<tr><td colspan='2' class=\"testorossobold\"><b>" + text2Write + "</b><br><BR></td></tr>";
      }
      if (toSearch != "") {
         text2Write = "";
         switch (usedLang) {
            case 1 : text2Write = "Testo cercato: "; break;
            case 2 : text2Write = "Gesuchter Text: "; break;
            case 3 : text2Write = "Texte recherché: "; break;
            case 4 : text2Write = "Gezocht naar: "; break;
            case 7 : text2Write = "Sökt text: "; break;
            case 0 :
            default: text2Write = "Searched text: "; break; //e-
         }
         toW += "<tr><td>" + text2Write + "</td><td>\"" + toSearch + "\"<BR></td></tr>\n";
      }
      if (datelim!="" && datelim.length == 8) {
         switch (usedLang) {
            case 1 : text2Write = "Data   : "; break;
            case 2 : text2Write = "Datum  : "; break;
            case 3 : text2Write = "Date: "; break;
            case 0 :
            default: text2Write = "Date   : "; break; //e-
         }
         switch (DateType) {
            case '0' : toW += "<tr><td>" + text2Write + "</td><td>" + datelim.substring(6,8) + '/' + datelim.substring(4,6) + '/' + datelim.substring(0,4) + "</td></tr>\n"; break;
            case '1' : toW += "<tr><td>" + text2Write + "</td><td>" + datelim.substring(4,6) + '/' + datelim.substring(6,8) + '/' + datelim.substring(0,4) + "</td></tr>\n"; break;
            case '2' : toW += "<tr><td>" + text2Write + "</td><td>" + datelim.substring(4,6) + ' ' + datelim.substring(0,4) + "</td></tr>\n"; break;
            case '3' : toW += "<tr><td>" + text2Write + "</td><td>" + datelim + "</td></tr>\n"; break;
            default: toW += "<tr><td>" + text2Write + "</td><td>" + datelim.substring(6,8) + '/' + datelim.substring(4,6) + '/' + datelim.substring(0,4) + "</td></tr>\n"; break;
         }
      }
   }
   if (typeof(downloadPDF) != 'undefined' && parseInt(downloadPDF,10)>0) {
      toW += '<tr><td colspan="3" align="left" valign="bottom" class="testorossobold">';
      toW += '<a href="javascript:pd_downloadcheckedPDF();">' + downCheckLabel + '</a>';
      toW += '</td></tr>\n';
   }
   toW += "</table>";
   toW += "</form>";
   js2write += "</script>\n";
   toW = js2write + toW;

   remote_xTextCall(pSetup, tosearch);
   // For Debug toW += "<textarea>" + toW+ "</textarea>";
   //toW += "<textarea>" + toW+ "</textarea>";
   document.write(toW);
   
}
function fixBasePath(basePath, id) {
   // basePath contains always a / at thend
   // /data/newsmem_archive/nouvelliste/20080418/page.pdf.0/
   var toret = basePath;
   var arr = basePath.split("/");
   //alert(basePath+"-"+arr.length);
   if (id>2 && arr.length>3) {
      var newDate = arr[arr.length-2];
      newDate = newDate.substr(0, 4)+"/"+newDate.substr(4, 2)+"/"+newDate;
      arr[arr.length-2] = newDate;
      toret = "";
      for (var i=0; i<arr.length; i++) {
         toret += arr[i];
         if (i<arr.length-1) { toret+="/"; }
      }
      //alert(toret);
   }
   return toret;
}

function setPageName(which) {
   
   var toret = -1;
   var pathIndex = o[which].substr(0, 1);
   //alert(pathIndex);
   if (pathIndex<d.length) {
      baseUrl = d[pathIndex] + o[which].substr(2);
      //alert(baseUrl);
   }
   
   basePath = "";
   pos = baseUrl.substr(0, baseUrl.length-1).lastIndexOf('/');
   if (pos>-1) {
      //alert("0 "+pos);
      basePath = baseUrl.substr(0, pos);
      name = baseUrl.substr(pos+1);
      name = name.replace("/", "");
      pos2 = basePath.indexOf(".com");
      if (pos2>-1) {
         basePath = basePath.substr(pos2+4, pos-(pos2+4))
      }
      basePath += "/";
      //alert(basePath+" - "+name);
      //basePath = "/data" + basePath;
      basePath = fixBasePath(basePath, pathIndex);
      rightFrame.setBasePathFlash(basePath);
      rightFrame.sendPageName(name, 0);
      //var text = p[5+7*which].S[0].textV;
      var text = parent.contents.saveCalled[which];
      /* Search all the occurencies of _Wcoord(163,178,9,5) and _Bcoord(140,146,195,237) */
      //alert(text);
      search1_highlight(text, 0, "_Bcoord(", tosearch);
      search1_highlight(text, 1, "_Wcoord(", tosearch);
      search1_highlight(text, 1, "_Scoord(", tosearch);
      toret = 0;
   }
   //alert("name: "+name);
   return name;
}

function show_Wcoord(i, x, y, a, b) {
   var rightFrame=parent.article;
   //alert(rightFrame);
   if (rightFrame!=null && typeof(rightFrame)!="undefined") {
      //alert("showWord: "+x+" - "+y);
      //alert("setPageName :"+i);
      setPageName(i);
      rightFrame.showWord(x, y);
   }
}
   
function loadArtIdx(){
	//alert("NEW FUNC CALLED");	
	idx = -1;
	if(parent.contents && parent.contents.srchIdx){
		idx = parent.contents.srchIdx;
	}
	
	
	if(idx >0 && idx <=(resultArray.length)){
		loadart(resultArray[idx][0],resultArray[idx][1],resultArray[idx][2],resultArray[idx][3],resultArray[idx][4],resultArray[idx][5],resultArray[idx][6],resultArray[idx][7]);	
	}else{
		//alert("RESULT ARRAY LENGTH " + resultArray.length + " IDX " + idx);
	}
}

var filesToRemotexText = new Array();

function addFileToRemotexText(i, tafilename) {
   var tmpObj = new Object();
   tmpObj.id = 'remote_xtext_' + i;
   tmpObj.tafilename = tafilename;
   filesToRemotexText.push(tmpObj);
}

function remote_xTextCall(pSetup, searched_string)
{
   var postParameters = "";
   
   if (filesToRemotexText.length == 0) {
      return;
   }
   
   filesToRemotexText.each(function(e) {
      postParameters += '&filepages[' + e.id + ']=' + e.tafilename
   });
   
   postParameters += '&searched_string=' + searched_string;

   //alert(postParameters);
   
   new Ajax.Request('remote_xtext.php?pSetup=' + pSetup, {
      
      method: 'post',
      parameters: postParameters,

      onSuccess: function(transport, json) {
         //alert(json);
         json = transport.responseText.evalJSON();
         for(var el in json) {
            //alert(el + "\n::::\n" + json[el]);
            var i = el.match(/\d+$/);
            $(el).update(json[el]);
            parent.contents.saveCalled[i] = json[el];
         }
      },
      
      onFailure: function() {
         $(id).update('Error featching text from remote server...');
      }
   });
}


function openFrame() {
   if (parent.contents && parent.contents.openCloseSearchFrame) {
      if (parent.contents.searchOpen) {
         parent.contents.openCloseSearchFrame();
         parent.contents.openCloseSearchFrame();
      } else {
         parent.contents.openCloseSearchFrame();
      }
   }
}

function closeSearch() {
   if (opener && opener.parent && opener.parent.button) {
      window.close();
   } else if (parent.contents.openCloseSearchFrame) {
      parent.contents.openCloseSearchFrame();
   }
   if (parent.contents && parent.contents.setArticleFrame) {
      parent.contents.setArticleFrame(1);
   }
}

function loadart(which,artId,page,sec,pDate,categ,type,filetype) {
   
   //alert("TYPE: "+type);
   var toret="";
   var evt = window.event;
   var isCTRLkey = 0;
   var debug = 0;
   
	// If the same article is clicked twice in a row, switch viewing modes
	if(lastArticleClicked == artId + "_" + page) {
		showmode = showmode ^ 1;
	}
	lastArticleClicked = artId + "_" + page;
	
	if(debug) {
		alert("1");
	}
	
   if (evt && evt.ctrlKey) {
      isCTRLkey = 1;
   }   
   
   //var showURL = "../php-script/getxmlart.php?pSetup=" + pSetup + "&paper="+ paper + "&base=" + baseDataPath + "&file=" + path_normalize(escape(o[which]) + "/../newsart/arts") + artId + ".xml&search=" + tosearch + "&page=" + escape(page) + "&section=" + sec + "&date=" + date + "&showmode=" + showmode;
   if(numPage.indexOf(" ") >= 0){
      numPage = numPage.replace(" ", "");
   }
   
   if (debug) { alert("2"); }
   //alert("SEC"+sec);

   var showURL = "../php-script/xmlart.php?pSetup=" + pSetup + "&paper="+ paper + "&file=" + escape(o[which]) + "&search=" + tosearch + "&page=" + escape(page) + "&artid=" + artId + "&section=" + sec + "&date=" + pDate + "&showmode=" + showmode + "&numPage=" + numPage + "&categ=" + categ + "&isctrlKey=" +isCTRLkey+"&filetype="+filetype;
   
   if (debug) { alert("3"); }
   if(type=="light") {
      showURL = "";
      //showURL = "../php-script/fpoppage.php?pSetup=" + pSetup + "&paper="+ paper + "&file=" + escape(o[which]) + "&search=" + tosearch + "&page=" + escape(page) + "&artid=" + artId + "&section=" + sec + "&date=" + pDate + "&showmode=" + showmode + "&numPage=" + numPage + "&categ=" + categ + "&isctrlKey=" +isCTRLkey;
   }
   //alert("CIAO" + showURL);
   //alert("PAGE: "+page);
   //alert("owichi: "+o[which]);
   
   //parent.button.curArticle = artId;
   
   if (debug) { alert("4"); }
   var parentFrame = parent;
   if (opener && opener.parent && opener.parent.button) parentFrame = opener.parent;

	if (parentFrame.button && parentFrame.button.updateParam) {
      parentFrame.button.updateParam("parent.page",artId,1,o[which],o[which],page,sec,pDate);
      parentFrame.button.pageChange();
   }
   
   if (debug) { alert("5"); }
   //alert("CURART"+parent.button.curArticle);
   if (showURL!="") {
      util_loadPage(parentFrame.article,showURL);
   } else {
      rightFrame=parent.article;
      if (rightFrame!=null && typeof(rightFrame)!="undefined") {
         if (rightFrame.PageViewer_isloaded(0)) {
            
            var pathIndex = o[which].substr(0, 1);
            //alert(pathIndex);
            if (pathIndex<d.length) {
               baseUrl = d[pathIndex] + o[which].substr(2);
               //alert(baseUrl);
            }
            
            basePath = "";
            pos = baseUrl.substr(0, baseUrl.length-1).lastIndexOf('/');
            if (pos>-1) {
               //alert("0 "+pos);
               basePath = baseUrl.substr(0, pos);
               name = baseUrl.substr(pos+1);
               name = name.replace("/", "");
               pos2 = basePath.indexOf(".com");
               if (pos2>-1) { 
                  basePath = basePath.substr(pos2+4, pos-(pos2+4))
               }
               basePath += "/";
               //alert(basePath+" - "+name);
               basePath = fixBasePath(basePath, pathIndex);
               rightFrame.setBasePathFlash(basePath);
               rightFrame.sendPageName(name, 0);
               //var text = p[5+7*which].S[0].textV;
               var text = parent.contents.saveCalled[which];
               /* Search all the occurencies of _Wcoord(163,178,9,5) and _Bcoord(140,146,195,237) */
               //alert(text);
               search1_highlight(text, 0, "_Bcoord(", tosearch);
               search1_highlight(text, 1, "_Wcoord(", tosearch);
               search1_highlight(text, 1, "_Scoord(", tosearch);
            }
            
         }
      }
   }
   if (debug) { alert("6"); }

   //if(parent && parent.contents) { parent.contents.setArticleFrame(1); }
}

function search1_highlight(text, type, tag, tosearch) {
   var index = 0;
   var wPos = 0;
   
   while (index>-1) {
      var endPos = -1;
      wPos = text.substr(index).indexOf(tag);
      if (wPos>-1) {
         endPos = text.substr(index+wPos).indexOf(")");
      }
      //alert(wPos+" - "+endPos);
      if (wPos>-1 && endPos>-1) {
         var string;
         string = text.substr(index+wPos+8, endPos-8);
         //alert(string);
         coords = string.split(",");
         //alert(string+" - "+coords.length);
         if (coords.length>3) {
            //alert("tosearch: "+tosearch);
            //alert(coords[coords.length-4]+" "+coords[coords.length-3]+" "+coords[coords.length-2]+" "+coords[coords.length-1]);
            rightFrame.setHighlightingBox(type, parseInt(coords[coords.length-4], 10), parseInt(coords[coords.length-3], 10), parseInt(coords[coords.length-2], 10)+1, parseInt(coords[coords.length-1], 10)+1, tosearch);
         }
         index += wPos+1;
      } else {
         index = -1;
      }
   }
}

/* Build javascript array result */
function mP(a,b) {
   this.type=a;
   this.sectId=b;
   this.S=new Array();
   return this;
}

function mS(a,b) {
   this.fontId=a;
   this.textV=b;
   return this;
}

function mA(a,b,c,d) {
   this.id=a;
   this.boxlen=b;
   this.den=c;
   this.stdd=d;
   this.e=new Array();
   return this;
}

function mE(a,b){
   this.type=a;
   this.link=b;
   return this;
}
/*
function cre_o(i,pagestr) {
   o[i]=pagestr;
   a[i]=new mA(i,0,0,0);
   p[i*7+0]=new mP(0,-1);
   a[i].e[0]=new mE(3,i*7+0);
   p[i*7+1]=new mP(0,-1);
   a[i].e[1]=new mE(4,i*7+1);
   p[i*7+2]=new mP(0,-1);
   a[i].e[2]=new mE(7,i*7+2);
   p[i*7+3]=new mP(0,-1);
   a[i].e[3]=new mE(9,i*7+3);
   p[i*7+4]=new mP(0,-1);
   a[i].e[4]=new mE(10,i*7+4);
   p[i*7+5]=new mP(0,-1);
   a[i].e[5]=new mE(11,i*7+5);
   p[i*7+6]=new mP(0,-1);
   a[i].e[6]=new mE(12,i*7+6);
}
*/
function cre_o(i,pagestr) {
   
   var numfF = 8;
   
   o[i]=pagestr;
   a[i]=new mA(i,0,0,0);
   p[i*numfF+0]=new mP(0,-1);
   a[i].e[0]=new mE(3,i*numfF+0);
   p[i*numfF+1]=new mP(0,-1);
   a[i].e[1]=new mE(4,i*numfF+1);
   p[i*numfF+2]=new mP(0,-1);
   a[i].e[2]=new mE(6,i*numfF+2);
   p[i*numfF+3]=new mP(0,-1);
   a[i].e[3]=new mE(7,i*numfF+3);
   p[i*numfF+4]=new mP(0,-1);
   a[i].e[4]=new mE(9,i*numfF+4);
   p[i*numfF+5]=new mP(0,-1);
   a[i].e[5]=new mE(10,i*numfF+5);
   p[i*numfF+6]=new mP(0,-1);
   a[i].e[6]=new mE(11,i*numfF+6);
   p[i*numfF+7]=new mP(0,-1);
   a[i].e[7]=new mE(12,i*numfF+7);
}


function reloadEclipFrame(pSetup,file,toSearch){
	
	//alert("TOSEARCH: "+toSearch);
	
	 parent.dataFset.rows='1,1,*';
    parent.frset.cols='320,*,190';
    util_loadPage(parent.eclip, path_normalize('../eclip/eclipframe.php?pSetup='+pSetup+'&file=' + escape(file)+'&fromSearch='+toSearch));
    	
}

function removeExtraZeros(pageNumber){
   var firstNumber=0;
   while (isNaN(pageNumber) && isNaN(pageNumber.charAt(firstNumber)) && firstNumber < pageNumber.length){
      firstNumber++;
   }
   if (firstNumber>0){
      toret1 = pageNumber.substr(0,firstNumber) + parseInt(pageNumber.substr(firstNumber), 10);
   }else{
      toret1 = parseInt(pageNumber, 10);
   }
   return toret1;
}
