/****************************************************************************
        BEGINNING OF CLASS AutoComplete list
*****************************************************************************/

var HiddenDropDownLists = 'selection,dpdYears';

var list1 ;
var booPostBack ;

var gOut = null;
var wordsAll = null;

function produceAutoCompleteList (bindToFld, indexElement, arWords, PostBack, Title, NavigPosition, XPosition, YPosition, NavSeparatorColor,PathToJavascript, PathToPictures, CurrEvent) {
	booPostBack = PostBack;
	
	if(typeof(list1) != 'object') list1 = new AutoCompleteList(Title) ;
    
	if (list1.isIE4) {
		if (XPosition < 0) list1.posX = window.event.clientX + document.body.scrollLeft + 12 ;
		else list1.posX = XPosition;
		if (YPosition < 0) list1.posY = window.event.clientY + document.body.scrollTop - 10 ;
		else list1.posY = YPosition;
		list1.isNe = true;
	}
	else if (navigator.appVersion.indexOf("Safari") != -1) {
		//FIX FOR SAFARI
		//SAFARI does not support arguments.callee.caller adequatly. So we have to add a new parameters
		//to the call of the function to pass the event
		if (XPosition < 0) list1.posX = CurrEvent.pageX + 12;
		else list1.posX = XPosition;
		if (YPosition < 0) list1.posY = CurrEvent.pageY - 10;
		else list1.posY = YPosition;
	}
	else {
		var theEvent= arguments.callee.caller.arguments[0];
		if (XPosition < 0) list1.posX = theEvent.pageX + 12;
		else list1.posX = XPosition;
		if (YPosition < 0) list1.posY = theEvent.pageY - 10;
		else list1.posY = YPosition;
	}

	// If the AutoCompleteList is visible and the same button was pressed as was pressed
	// to create the AutoCompleteList then Hide the AutoCompleteList and exit the Sub
	if( list1.visible && (bindToFld == list1.bindToElement ) ) {
		list1.hide() ;
		return ;
	}
	else {
		list1.bindToElement = bindToFld ;

	}
	//Set the list of words
	//we receive a list a this style: ,code1;ville1:,code2;ville2:, .... :,codeN;villeN:
	if (arWords != null) {
			wordsAll= arWords;
			//Go trhough all string and remove ",", ";",and number([0-9])
			var re = new RegExp ('[,|;|\\d]', 'gi') ;
			arWords = arWords.replace(re,"")
			words = arWords.split(":");
	}
	
	//To handle AutoCompleteList properties parameters
	list1.indexElement = indexElement;
	list1.NavigPosition = NavigPosition ;
	list1.twidth = 400;
	list1.NavSeparatorColor = NavSeparatorColor;
	list1.PathToJavascript = PathToJavascript;
	list1.PathToPictures = PathToPictures;
	//list1.bindWord = getBindedWord();	
	
	list1.BuildAutoCompleteList() ;
	//list1.getElementById('typedCity').focus()
}


function positionAutoCompleteList(f) {

	var x = f.txtPosX.value;
	var y = f.txtPosY.value;

	if(typeof(list1) != 'object') produceAutoCompleteList();

	if( isNaN(x) || isNaN(y) ) {
		alert('You can only enter numbers for the x/y co-ordinates') ;
		return ;
	}
	else {
		list1.moveTo(x,y);
	}

}

//This function return the date that is binded to the claendar (if any)
function bindWord () {
	var objFld = eval("document.forms[0]." + list1.bindToElement) ;
	
	// Clear the value of our form field.
	objFld.readonly = false ;
	objFld.value = '' ;
	objFld.readonly = true ;
	// hide the AutoCompleteList object.
	list1.hide() ;
}

function calCloseList () {
	list1.hide() ;
}

function AutoCompleteList(t) {
    
	if (typeof(_AutoCompleteList_prototype_called) == 'undefined') {
		_AutoCompleteList_prototype_called = true ;
        
		// Object methods
		this.BuildAutoCompleteList = _createList ;
		this.createCanvass = _createCanvassList ;
		this.showAutoCompleteList = _showAutoCompleteList ;
		this.moveTo = _positionCanvassList ;
		this.hide = _hideList ;
		this.show = _showList ;
		this.init = _initList ;
		this.headerSelection = t ;

	}
    
	// Object properties
	this.name = 'default' ;
	this.rowBGColor = 'palegoldenrod' ;
	this.visible = false ;
	this.posX = 10 ;
	this.posY = 10 ;
	this.isIE4 = '';
	this.isNav4 = '' ;
        
	// If you set hasEvents fo FALSE then the AutoCompleteList face is dumbed out.
	this.hasEvents = true ;
        
	this.canvass = '' ; // The DIV || LAYER that we display the AutoCompleteList on.
	this.bindToElement = '' ;  // Bind to an ELEMENT on the page.
	this.indexElement = '' ;  // Bind to an ELEMENT on the page.
    
	// Call the Initialize() event.
	this.init() ;
}

// This function displays the objects canvass.
function _showList() {
	

	list1.totalheight = 200;
	
	this.canvass.style.left = this.posX ;
	this.canvass.style.top = this.posY ;
		
  	fctHideSelectElementsList();
	/*if ( this.canvass.style.visibility=='hidden')
	{	
		fctHideSelectElementsList();
	}
	{
		alert("not hiden!");
	}
	*/
	this.canvass.style.visibility = 'visible' ;
	this.canvass.style.visibility = 'hidden' ;
	this.canvass.style.visibility = 'visible' ;
	
	this.visible = true ; 
	
	// code added by nik to get the focus on the textbox
	var varObject = document.getElementById('typedCity');
	//alert(varObject);
	//Avec 2 IE le bouffe pour de bon
	varObject.focus();
	varObject.focus();
	// end added	

}

// This function hides the objects canvass.
function _hideList() {

	this.canvass.style.visibility = 'hidden' ;
	//alert(this.canvass.style.visibility);
	restoreSelectElementsList();
	this.visible = false ;

}

function _initList() {
	if (parseInt(navigator.appVersion.charAt(0)) >= 4) {
		this.isNav4 = (navigator.appName == "Netscape") ? true : false ;
		this.isIE4 = (navigator.appName.indexOf("Microsoft") != -1) ? true : false ;
	}
    
	/* The constructor optionally accepts m && y parameters if none are supplied, the AutoCompleteList defaults to the current month */
	this.flag = "ON";
	 
	// Create the canvass that we will be displaying the AutoCompleteList on
	this.createCanvass() ;
	obj = null ;
}

function _createCanvassList() {
	var objDiv = document.createElement("DIV") ;
	objDiv.style.position = "absolute";
	document.body.appendChild (objDiv) ;
	this.canvass = objDiv ;
	this.canvass.style.left = this.posX ;
	this.canvass.style.top = this.posY ;
}

function _positionCanvassList(x,y) {
	// if either x || y were not supplied, default to the current settings.
	if(x==null || y==null) { x=this.posX; y=this.posY ; return ;}
    
	if( isNaN(x) || isNaN(y) ) {
		alert('You can only enter numbers for the x/y co-ordinates') ;
		return ;
	}
    
	this.canvass.style.left = this.posX = x ;
	this.canvass.style.top = this.posY = y ;
}

function _showAutoCompleteList (s) {
	this.canvass.innerHTML = s ;
	this.show() ;
}

function clickhandlerList(flagList) {
	if (flagList != null) {
		var idx;
		var code;
		var arrElements = document.getElementsByTagName('select'); 
		for (var i = 0; i < arrElements.length; i++) {
			if ( arrElements[i].name == 'selection') {
					idx = arrElements[i].selectedIndex;
					code = arrElements[i].options[idx].value;
			}
		}
		
		if (idx >= 0) {
			var objFld = eval("document.forms[0]." + list1.bindToElement);
			var objIndex = eval("document.forms[0]." + list1.indexElement);
			
			// Update our form field.
			//objFld.readonly = false ;
			objFld.value = code //words[idx];
			objFld.selectedIndex = idx +1
			//objFld.readonly = true ;
			objIndex.readonly = false ;
		    objIndex.value = code;
		    objIndex.readonly = true ;		   
			//HandleCityChange();		        
			if (booPostBack == 'True') {
				__doPostBack(list1.bindToElement,'');
			}

		}
	}		
	// hide the AutoCompleteList object.
	list1.hide() ;
	
}

function getBindedWord() {
	
	var objFld = eval("document.forms[0]." + list1.bindToElement) ;
	return objFld.value;
	
}

function bindWord () {
	
	var objFld = eval("document.forms[0]." + list1.bindToElement) ;
	    
	// Clear the value of our form field.
	objFld.readonly = false ;
	objFld.value = '' ;
	objFld.readonly = true ;
	// hide the AutoCompleteList object.
	list1.hide() ;
}

function _showAutoCompleteList (s) {
	this.canvass.innerHTML = s ;
	this.show() ;
}

// Create and Display AutoCompleteList.
function _createList() {	
	// String to store AutoCompleteList output.
    var sOut = new String();
 
	if (gOut == null) 
	{   
		
		this.flag = "ON" ;
		
		sOut = "<table cellpadding=1 cellspacing=0 class='AllCalendrier'>" ;
		//  Write the header seletion message
		
		sOut += "<tr>";
		sOut += "<td CLASS='TitleCL'colspan=1 align=right>&nbsp;</td>" ;
		sOut += "<td CLASS='TitleCL' align=center colspan=1>" + this.headerSelection + "</td>" ;

		// Selection du bouton close ou du 'X'
		sOut += "<td CLASS='TitleCL' colspan=1 align=right>&nbsp;</td>" ;
		sOut += "<td CLASS='TitleCL' ALIGN='right'><A HREF='javascript:;' class='CloseButton' onClick='calCloseList();'><span class='CloseButton'>&#215;</span></A></td>" ;

   		sOut += "</tr>" ;
	   	
   		//if (this.isIE4) sOut += "<tr><td colspan=4 class='Separator'></td></tr>";
		//else sOut += "<tr><td colspan=4 bgcolor='" + this.NavSeparatorColor + "'><img src='" + this.PathToPictures + "Pixel.gif' width='1px' height='1px' ></td></tr>";
		
		sOut += "<tr>" ;
		//sOut += "<td CLASS='TitleNavigation' colspan=1 align=right>&nbsp;</td>" ;
		sOut += "<td CLASS='TitleNavigation' colspan=4 align=center>" ;
		// modification by nik : change the name='typedCity' in the next line to : id='typedCity' to get the focus on the textbox
		sOut += "<input class='typedCity' type=text name='typedCity' id='typedCity' size='35' onkeyup='OnEnter(this.value,event);'>" ;
		sOut += "</td>" ;
		// sOut += "<td CLASS='TitleNavigation' colspan=1 align=right>&nbsp;</td>" ;
		sOut += "</tr>" ;

   		//if (this.isIE4 ) sOut += "<tr><td colspan=4 class='Separator'></td></tr>";
		//else sOut += "<tr><td colspan=4 bgcolor='" + this.NavSeparatorColor + "'><img src='" + this.PathToPictures + "Pixel.gif' width='1px' height='1px' ></td></tr>";
	   
		//  Write the list
		sOut += "<tr class='TitleAutoCompleteList'>" ;
		//sOut += "<td colspan=1 align=right>&nbsp;</td>" ;
		sOut += "<td colspan=4 align=center>" ;
		sOut += "<SELECT class='CitySelect' name='selection' size='9' STYLE='width: 158px' ondblclick='clickhandlerList(1);calCloseList();'>" ;
	
		//Add word to the list and to the tree: RegExp is used for 
		//We have to receive ,code1;ville1:,code2;ville2:, .... :,codeN;villeN:
		var optionsList;
		var re = new RegExp (',', 'gi') ;
		optionsList = wordsAll.replace(re,"<OPTION value=");
		re = new RegExp (';', 'gi') ;
		optionsList = optionsList.replace(re,">");
		re = new RegExp (':', 'gi') ;
		sOut += optionsList.replace(re,"</OPTION>");
		
		sOut += "</SELECT>";
		sOut += "</td>" ;
		// sOut += "<td colspan=1 align=right>&nbsp;</td>" ;
		sOut += "</tr>" ;
		
		//if (this.isIE4 ) sOut += "<tr><td colspan=4 class='Separator'></td></tr>";
		//else sOut += "<tr><td colspan=4 bgcolor='" + this.NavSeparatorColor + "'><img src='" + this.PathToPictures + "Pixel.gif' width='1px' height='1px' ></td></tr>";
	 
	    //sOut += "<tr CLASS='TitleNavigation'>" ;
	  	//sOut += "<td colspan=1 align=center>&nbsp;</td>" ;
		
		//sOut += "<td colspan=2 align=center>" ;
	
		//  Write buttons
		//sOut += "<table cellpadding=1 cellspacing=0 width='100%' >" ;
		//sOut += "<tr CLASS='TitleNavigation'>" ;
		//sOut += "<td colspan=1 align=center>" ;
		//sOut += "<input type=button id=btnOk value='&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;' class='boutonbas' onClick='clickhandlerList(1);'>&nbsp;" ;
		//sOut += "<input type=button id=btnClose value='Fermer' class='boutonbas' onClick='clickhandlerList(null)'>" ;
		//sOut += "</td></tr></table>" ;
		// END buttons
		//sOut += "<td colspan=1 align=right>&nbsp;</td>" ;
		sOut += "</td></tr></table>" ;
		
		//Cache stream out for future used...
		gOut = sOut;
		
	}

	// Render the AutoCompleteList
    this.showAutoCompleteList (gOut) ;
   }
 
  function OnEnter(textValue,event) 
  {  
  
	var code = 0;
    
    if (window.event) {
		code = window.event.keyCode;
	}
    else {
        code = event.which;
    }
    if (code==13) {
        clickhandlerList(1);
    }
    else {    
	  var word;
	  var idx;
	 
		word = GetWordsFromLetters(textValue);
		
		//select word into list
		var arrElements = document.getElementsByTagName('select'); 
	    for (var i = 0; i < arrElements.length; i++) {
		  if ( arrElements[i].name == 'selection') 
				arrElements[i].selectedIndex = GIndex;       
		}
	}
}

//---------------------------------------------------------------------------------------//
//*******			Object declaration and associated function					*********//
//---------------------------------------------------------------------------------------//
var GTree;		//Global tree	
var GIndex;		//Index of the last word got into the list: updated when GetWordsFromLetters
				// is called
var loop = 100;	//how many loops before releasing CPU when building tree
GTree = new Tree("_", false,-1);	//Main node
var codeRegions; //variable _codeRegionStr is received from aspx page and hold all region codes

function Tree(letter, isWord ,idx) {
	this.letter = letter;
	this.isWord = isWord;
	this.index = idx;
	if (idx >= 0) {
		this.regCode = codeRegions[idx];
	}
}

//We receive list of this style: ,code1;ville1:,code2;ville2:, .... :,codeN;villeN:
function preLoadWords()
{	//Used to populate popup later..
	wordsAll = wordsStr;
	
	//Now we remove unecessary caracther to populate the tree
	if (wordsStr != null) {
		//Go trhough all string and remove ",", ";",and number([0-9])
		var re = new RegExp ('[,|;|\\d]', 'gi') ;
		wordsStr = wordsStr.replace(re,"")
		words = wordsStr.split(":");
		codeRegions = _codeRegionStr.split(",");
		addWord(0,loop);
		
	}
}

function addWord(idx,looptimes)
{
		//Add word to the list and to the treee
		for(i=idx;i <= words.length-1 && looptimes > (i - idx) ;i++) {	
			addWords(GTree,words[i].toLowerCase(),i);
		}
		//If not done, we timeout the function
		if (looptimes <= (i - idx)) {
			setTimeout("addWord(" + i + "," + looptimes + ");", 300);
		}
}		

//This function add a word to the dictionary : 
function addWords(tree,word,idx)
{	
	var cletter;
	var pos;
	var code;
	
	if (word.length >= 1)  {
		cletter = word.charAt(0);
		
		//si caracteres speciaux
		if (cletter == "&") //Should not happen: wasn't sure so it took no chance!
		{	
			pos = word.indexOf(";") + 1;
			if (pos >= 1) {
				code = getUnicodeCode(word.substring(0,pos))
			}
			if (tree[code] == null) {
				//Check if it was a word
				tree[code] = new Tree(code,(word.length == pos) ? true : false, idx);
			}
			if (word.length >= 2) {
				addWords(tree[code],word.substring(pos), idx);
			}
		}
		else {						
			if (tree[cletter.charCodeAt(0)] == null) {
				//Check if it was a word
				tree[cletter.charCodeAt(0)] = new Tree(cletter,(word.length == 1) ? true : false, idx);
			}
			if (word.length >= 2) {
				addWords(tree[cletter.charCodeAt(0)],word.substring(1),idx);
			}
		}
	}
}

function GetWordsFromLetters(letters)
{	
	return GetNextWords(GTree,letters.toLowerCase(),letters);
}

function GetNextWords(tree, word, originWord)
{	var cletter;
	if (word.length >= 1) {
		cletter = word.charAt(0);		
		var tp = tree[cletter.charCodeAt(0)];
		if (tp == null) {
		
		Gindex = -1
		return "";
		}else {
			if (word.length <= 1) {
				if (tp.isWord == true) {
					
					GIndex = tree.index;
					return originWord;
				} else {
					//alert("go for next!");
					return getNext(tp,originWord);	
				}								
			}else {
				return GetNextWords(tp,word.substring(1),originWord);
			}
		}
	}
}

function getNext(tree, letters) {
	var cpt = 0;
	var fLetter = null; 
	var fTree;
	var tmpLetter;
	var i;
	var upperIndex;
	
	//We go through a large set of caracther 
	//(not an issue since going through the tree is already fast)
	for(i = 20; i <= 255; i++) {
		if (tree[i] != null) {
			cpt++;
			if (fLetter == null) {
				fTree = tree[i];
				fLetter = String.fromCharCode(i);
				if (fTree.isWord == true) {
					GIndex = fTree.index;
					return letters + fLetter;
				}
				else {
					letters = letters + fLetter;
				}
			}
		}
	}
		
	if (fTree!=null)	{
		return getNext(fTree, letters);
	} else {
		return letters;
	}
}

function getUnicodeCode(htmlCode)
{	
	switch (htmlCode) {
		case "&Agrave;" :
			return "192";
			break;
		case "&agrave;" :
			return "224"; 
			break;
		case "&Acirc;" : 
			return "194";
			break;
		case "&acirc;" : 
			return "226";
			break;
		case "&Auml;" : 
			return "196"; 	
			break;
		case "&auml;" : 
			return "228"; 	
			break;
		case "&Ccedil;" : 
			return "199";
			break;
		case "&ccedil;" : 
			return "231"; 	
			break;
		case "&Egrave;" : 
			return "200";
			break;
		case "&egrave;" : 
			return "232";
			break;
		case "&Eacute;" : 
			return "201";
			break;
		case "&eacute;" : 
			return "233"; 	
			break;
		case "&Ecirc;" : 
			return "202";
			break;
		case "&ecirc;" : 
			return "234";
			break;
		case "&Euml;" : 
			return "203"; 	
			break;
		case "&euml;" : 
			return "235"; 	
			break;
		case "&Igrave;" : 
			return "204"; 	
			break;
		case "&igrave;" :
			return "236"; 	
			break;
		case "&Icirc;" :
			return "206"; 	
			break;
		case "&icirc;" : 
			return "238";
			break;
		case "&Ugrave;" : 
			return "217"; 	
			break;
		case "&ugrave;" : 
			return "249"; 	
			break;
		case "&Ucirc;" : 
			return "219";
			break;
		case "&ucirc;" :
			return "251";
			break;
		case "&Uuml;" : 
			return "220";
			break;
		case "&uuml;" : 
			return "252";
			break;
	}
}
//---------------------------------------------------------------------------------------//
//*******			END Object declaration and associated function				*********//
//---------------------------------------------------------------------------------------//



/****************************************************************************
        Hide select html controls function
*****************************************************************************/


//Whether the given objects are overlapping 
function isControlsOverlappingList(objOne, objTwo)
{
  var result = true; 

  //we use the calendar object position: need to be set before calling this function  
  var list1Left = list1.posX;
  var list1Top = list1.posY;
  var list1Right = list1Left + parseInt(list1.twidth);
  var list1Bottom = list1Top + parseInt(list1.totalheight);
 
  var obj2Left = get_pageX_pos(objTwo); 
  var obj2Top = get_pageY_pos(objTwo); 
  var obj2Right = obj2Left + objTwo.offsetWidth; 
  var obj2Bottom = obj2Top + objTwo.offsetHeight;

  if (list1Right <= obj2Left || list1Bottom <= obj2Top || 
      list1Left >= obj2Right || list1Top >= obj2Bottom) 
    result = false; 
  
  return result; 
}

// Hides HTML select elements that are overlapping the given menu group 
function fctHideSelectElementsList()
{
  if (document.getElementsByTagName) 
  {
    var arrElements = document.getElementsByTagName('select'); 
     for (var i = 0; i < arrElements.length; i++) 
     {
        if (isControlsOverlappingList(list1.canvass, arrElements[i]))
          if (HiddenDropDownLists.indexOf(arrElements[i].name) < 0)
			arrElements[i].style.visibility = 'hidden';          
	}
  }
}

// Restores all HTML select elements on the page 
function restoreSelectElementsList()
{
  if (document.getElementsByTagName) 
  {
    var arrElements = document.getElementsByTagName('select'); 
   
      for (var i = 0; i < arrElements.length; i++) 
	 {	if (HiddenDropDownLists.indexOf(arrElements[i].name) < 0)
			arrElements[i].style.visibility = 'visible'; 
		else
			arrElements[i].style.visibility = 'hidden'; 
	 }
  }
}

// Calculates the absolute page x coordinate of any element
function get_pageX_pos(element)
{
  var x = 0;
  do 
  {
    if (element.style.position == 'absolute') 
    { 
      return x + element.offsetLeft; 
    }
    else
    {
      x += element.offsetLeft;
      if (element.offsetParent) 
        if (element.offsetParent.tagName == 'TABLE') 
          if (parseInt(element.offsetParent.border) > 0)
          {
            x += 1; 
          }
    }
  }
  while ((element = element.offsetParent));
 
  return x; 
}

// Calculates the absolute page y coordinate of any element
function get_pageY_pos(element)
{
  var y = 0;
  do 
  {
    if (element.style.position == 'absolute') 
    {
      return y + element.offsetTop; 
    }
    else
    {
      y += element.offsetTop;
      if (element.offsetParent) 
        if (element.offsetParent.tagName == 'TABLE') 
          if (parseInt(element.offsetParent.border) > 0)
          {
            y += 1; 
          }
    }
  }
  while ((element = element.offsetParent));
  return y; 
}

function submitForm(page)
{ 
	var sLocation = window.location.pathname;
	var shId = document.getElementById('cboShows').value;
	var ctId = document.getElementById('cboCities').value;
	var yrId1 = document.getElementById('cboYears1').value;
	var yrId2 = document.getElementById('cboYears2').value;
			
	window.location = sLocation + "?showId=" + shId + "&cityId=" + ctId + "&yearId1=" + yrId1 + "&yearId2=" + yrId2 + "&p=" + page;
	
}

function clearForm()
{ 
	var sLocation = window.location.pathname;
	document.getElementById('cboShows').value = "";
	document.getElementById('hiddenCodes').value = "";
	document.getElementById('cboCities').value = "";
	document.getElementById('cboYears1').value = "";
	document.getElementById('cboYears2').value = "";
			
	window.location = sLocation;	
}

//Custom CDS function to prevent certain dates from being 
//selectable

function checkHistoryDates(date,y,m,d){
	TempDay = new Date(y,m,d)
				
	if ((TempDay < minDate) || (TempDay > maxDate)){
		return true;
	}
	else{
		return false;
	}
}	
