/*
 * Author: Francisco Moreno.
 * usednick_at_gmail_dot_com.
 * Copyright: Ekwest Interactive Solutions, Inc. 2006
 *  
 */

// - Dynamic elements's control code
//-- Artist funcs

// Creates a new artist row.
function createNewArtist(countIdx,selectedValue) {
	var row = document.createElement('tr');
	var cella = document.createElement('td');
	var cellaa = document.createElement('td');
	var selector = document.createElement('select');
	selector.setAttribute('name','artist'+countIdx);
	selector.appendChild(document.createElement('option'));
	selector.firstChild.setAttribute('value','-'); 
	selector.firstChild.appendChild(document.createTextNode('---'));

	//gotta change it to use a registered variable instead
	for(var i=0; i<arts.length; i++) {
		var option = document.createElement('option');
		option.setAttribute('value',arts[i].idx);
		if(selectedValue!=null && selectedValue==arts[i].idx)
			option.setAttribute('selected','selected');
		option.appendChild(document.createTextNode(arts[i].name));
		selector.appendChild(option);
	}
	//Row
	row.countIdx=countIdx;
	row.selector=selector;	//Gives a quick access to the element;
	
	//Cell AA
	cellaa.setAttribute('width','15%;')
	cellaa.appendChild(document.createTextNode('Artist '+(countIdx+1)+': '));
	row.appendChild(cellaa);
	row.cellaa=cellaa;	//Gives a quick access to the element;
	//Cell A
	cella.setAttribute('width','85%;')
	cella.appendChild(selector);
	row.appendChild(cella);
	row.cella=cella;	//Gives a quick access to the element;


	if(countIdx>=0) {
		//Cell B
		var cellb = document.createElement('td');
		var link = document.createElement('a');
		//Link
		link.setAttribute('href','javascript: void(0);');
		link.onclick = function () { removeArtist(this.row.countIdx);	};
		link.appendChild(document.createTextNode('Remove'));
		link.row=row;

		cellb.appendChild(link);
		row.appendChild(cellb);
		row.remLink=link;	//Gives a quick access to the element;
	}
	
	document.getElementById('artistTableBody').appendChild(row);
	zebraTableBody(document.getElementById('artistTableBody'),'artist');
	
	//Push the select elements into a global container
	artistRefs.push(row);
}

// - At this point the file containing epoch's array function "arrayIndex"
// - should be available...
// Removes an artist row
function removeArtist(countIdx) {
	var artistList=document.getElementById('artistTableBody');
	try {
		//Remove the select reference from the global array
		var idx=artistRefs.arrayIndex(getRowRef(artistList.childNodes,countIdx));
		artistRefs.splice(idx,1);	
		artistList.removeChild(getRowRef(artistList.childNodes,countIdx));
		//Reorder the idxs
		for(var i=0; i<artistList.childNodes.length; i++) {
			if(artistList.childNodes[i].countIdx && artistList.childNodes[i].countIdx > countIdx) {
				artistList.childNodes[i].countIdx-=1;
				//artistList.childNodes[i].remLink.onclick = function () { window.alert('aux= '+aux); removeArtist(aux); };
				var text = document.createTextNode('Artist '+(artistList.childNodes[i].countIdx+1)+': ');
				artistList.childNodes[i].cellaa.replaceChild(text,artistList.childNodes[i].cellaa.firstChild);

			}
		}
		zebraTableBody(document.getElementById('artistTableBody'),'artist');
	} catch(err) {
		return false;
	};
	
	return true;
}


//-- Est and Performance Functions
function createPresentation(estRef,period,periodDisplay,desc_en,desc_fr,descDisplay, pricemin, pricemax, festival) {
	//if(validatePeriod(period) && estRef.value!=null && estRef.value!='-') {
	if(validateInfo(period,estRef.value,(desc_en+desc_fr))) {
		

		//check if the pricemax<pricemin
		if(pricemax<pricemin)
		{
      pricemax=pricemin;
    }
		
		var estIdx=-1;
		//Register both period and establishments on the global collections.
		
		//periodRefs.push(period);
		if((estIdx=establishments.arrayIndex(estRef.value))==-1)
			establishments.push(estRef.value)
			
		
		//niz added the pricemin and pricemax to the array	
		perfRefs.push(Array(period, estRef.value, desc_en, desc_fr, pricemin, pricemax, document.getElementById("festival_id").value,document.getElementById("place").value));
			
		//make a printout
		/*	for(var i=0;i<perfRefs.length; i++)
      {
				alert(perfRefs[i][1]);
				alert(perfRefs[i][2]);
				alert(perfRefs[i][3]);
				alert(perfRefs[i][4]);
				alert(perfRefs[i][5]);
				
			}*/
		
		//periodEsts.push(Array(estRef.value,period));
	
		//Document objects' creation	
		// - If this establishment has already an event associated with it...
		// - get the establishment's table and insert a new event...
		// - otherwise, create the table and then insert the event...
		if(estIdx>-1) {
			
			var estTableBody	= document.getElementById(estRef.value).tableBody;
			var row						= document.createElement('tr');
			var dateCell			= document.createElement('td');
			var remCell				= document.createElement('td');
			var link					= document.createElement('a');
			
			//dateCell
			//dateCell.appendChild(document.createTextNode(" "+periodDisplay));
			//dateCell.innerHTML=shortenString("&nbsp;"+periodDisplay+"&nbsp;"+descDisplay, 80);
			dateCell.innerHTML="&nbsp;"+periodDisplay+'&nbsp;&nbsp;-&nbsp;<span style="color: #888;">'+shortenString(descDisplay, 80)+"</span>";
			//dateCell.setAttribute('width','90%');

			//remCell
			////Link
			link.setAttribute('href','javascript: void(0);');
			link.delperiod = period;
			link.delestRef = estRef.value;
			link.deldesc_en = desc_en;
			link.deldesc_fr = desc_fr;
			link.onclick = function () {removePeriod(this.delperiod,this.delestRef,this.deldesc_en,this.deldesc_fr);};
			link.appendChild(document.createTextNode('Remove'));
			link.row=row;
			remCell.appendChild(link);
			
			//Row
			row.countIdx=0;
			row.remLink=link;	//Gives a quick access to the element;
			//row.setAttribute('id',period[0].getTime());
			row.setAttribute('id',period[0].getTime()+'|||'+period[1]+'|||'+estRef.value+'|||'+desc_en+'|||'+desc_fr);
			
			
			//row.appendChild(estCell);
			row.appendChild(dateCell);
			row.appendChild(remCell);
			
			//Append it to the table
			estTableBody.appendChild(row);
			
			//zebraTableBody(estTableBody,'perf');
		} else { //First event for the establishment...
			var containingRow		= document.createElement('tr');
			var containingCell	= document.createElement('td');
			var table						= document.createElement('table');
			var tableBody				=	document.createElement('tbody');
			var headerRow				= document.createElement('tr');
			var headerEstCell		= document.createElement('td');
			var headerRemCell		= document.createElement('td');
			var headerLink			= document.createElement('a');
			var row							= document.createElement('tr');
			var dateCell				= document.createElement('td');
			var remCell					= document.createElement('td');
			var link						= document.createElement('a');
			//alert("herey"+estRef.childNodes);
			
			try{
			var children=estRef.childNodes;
			if (children.length == 2) {
				try {
					headerEstCell.appendChild(document.createTextNode(estRef.childNodes[1].text));
				} catch (err) {
					headerEstCell.appendChild(document.createTextNode(estRef.text));
				};
				
			} else {
				
				try {
					headerEstCell.appendChild(document.createTextNode(estRef.childNodes[estRef.selectedIndex].text));
				} catch (err) {
					headerEstCell.appendChild(document.createTextNode(estRef.text));
				};
			}
			}
			catch(err){
				
						headerEstCell.appendChild(document.createTextNode(estRef.text));
			}
			//headerEstCell
			headerEstCell.appendChild(document.createTextNode('        Price range: '+pricemin+' to '+pricemax));
			headerEstCell.appendChild(document.createTextNode('        Festival: '+festival));
			//headerEstCell.appendChild(document.createTextNode('        Venue: '+venue));
			headerEstCell.setAttribute('width','95%');
			headerEstCell.setAttribute('style','font-weight: bold;');
			
      
			//headerRemCell
			////headerLink
			headerLink.setAttribute('href','javascript: void(0);');
			headerLink.onclick = function () {removeEstablishment(this.estRefValue);};
     		headerLink.appendChild(document.createTextNode('Remove'));
			headerLink.row=row;
			headerLink.estRefValue=estRef.value; //Needed to force the use of the value inside the function and not the reference
			headerRemCell.appendChild(headerLink);
			
			
			//headerRow
			headerRow.appendChild(headerEstCell);
			headerRow.appendChild(headerRemCell);
			headerRow.style.backgroundColor = '#c8c8c8';
			//dateCell
			//dateCell.appendChild(document.createTextNode(" "+periodDisplay));
			dateCell.innerHTML="&nbsp;"+periodDisplay;
			
			//remCell
			////link
			link.setAttribute('href','javascript: void(0);');
			//link.onclick = function () {removePeriod(period[0].getTime());};
			link.delperiod = period;
			link.delestRef = estRef.value;
			link.deldesc_en = desc_en;
			link.deldesc_fr = desc_fr;
			link.onclick = function () {removePeriod(this.delperiod,this.delestRef,this.deldesc_en,this.deldesc_fr);};

			link.appendChild(document.createTextNode('Remove'));
			link.row=row;
			remCell.appendChild(link);
			
			//Row
			row.countIdx=0;
			row.remLink=link;	//Gives a quick access to the element;
			row.setAttribute('id',period[0].getTime()+'|||'+period[1]+'|||'+estRef.value+'|||'+desc_en+'|||'+desc_fr);
			//row.appendChild(estCell);
			row.appendChild(dateCell);
			row.appendChild(remCell);
			//row.setAttribute('id',period[0].getTime());
			
			//tbody
			tableBody.appendChild(headerRow);
			tableBody.appendChild(row);
			
			//table
			table.setAttribute('id',estRef.value);
			//table.setAttribute('border','0'); // - Temporal Code... * * * Remember to remove it.
			table.tableBody = tableBody;
			table.appendChild(tableBody);
			table.containingRow=containingRow;
			
			//containing cell
			containingCell.appendChild(table);
			//containing row
			containingRow.appendChild(containingCell);
			
			document.getElementById('performanceTableBody').appendChild(containingRow);
			//zebraTableBody(tableBody,'perf');
			zebraTableBody(document.getElementById('performanceTableBody'),'est');
		}
	} else {
		//Return error signal back to the caller function in order to stop it.
	}
	
	//Clear Everything
	// - Pending -
	
}


//function removePeriod(startTimeStamp) {
function removePeriod(period,estCode,desc_en,desc_fr) {
	/*for(var i=0; i<periodRefs.length; i++)
		if(periodRefs[i][0].getTime()==startTimeStamp) {
			periodRefs.splice(i,1);
			break;
		}*/
		
	//window.alert(''+period[0]+'|||'+period[1]+'|||'+estCode+'|||'+desc_en+'|||'+desc_fr);
	
	aux=perfRefs.perfIndex(period, estCode, (desc_en+desc_fr));
	if(aux>=0) {
		
		perfRefs.splice(aux,1);
	} 
	
	/*for(var i=0; i<periodEsts.length; i++)
		if(periodEsts[i][1][0].getTime()==startTimeStamp) {
			periodEsts.splice(i,1);
			break;
		}*/
	
	//var periodRow = document.getElementById(startTimeStamp);
	//var periodRow = document.getElementById(period[0].getTime());
	var periodRow = document.getElementById(period[0].getTime()+'|||'+period[1]+'|||'+estCode+'|||'+desc_en+'|||'+desc_fr);
	
	if(periodRow.parentNode.childNodes.length<=2) //Only me and the header... then call for complete destruction..
		removeEstablishment(periodRow.parentNode.parentNode.id);
	else {
		periodRow.parentNode.removeChild(periodRow);
		//zebraTableBody(periodRow.parentNode,'perf');
	}
}

function removeEstablishment(estId) {
	//window.alert(estId);
	for(var i=0; i<establishments.length; i++)
		if(establishments[i]==estId) {
			establishments.splice(i,1);
			break;
		}
	
	/*for(var i in periodEsts)
		if(periodEsts[i][0]==estId) {
			
			for(var j=0; j<periodRefs.length; j++)
				if(periodRefs[j][0].getTime()==periodEsts[i][1][0].getTime()) {
					periodRefs.splice(j,1);
					break;
				}

			periodEsts.splice(i,1);

		}*/
	/*for(var i in perfRefs)
		if(perfRefs[i][1]==estId) {
			window.alert(perfRefs[i][1]);
			perfRefs.splice(i,1);

		}*/
		for(var i=perfRefs.length-1; i>=0; i--)
			if(perfRefs[i][1]==estId) {
				window.alert(perfRefs[i][1]);
				perfRefs.splice(i,1);
	
			}
	
	document.getElementById('performanceTableBody').removeChild(document.getElementById(estId).containingRow);
	zebraTableBody(document.getElementById('performanceTableBody'),'est');
}

//-- Other Functions
function getRowRef(arr,countIdx) {
	for(var i=0; i<arr.length; i++)
		if(arr[i].countIdx!=null && arr[i].countIdx == countIdx)
			return arr[i];
	//<- For end.
	return null;
}


// - Legacy function used to verify if a new period overlaps an existing one...
function validatePeriod(period) {
	var valid = true;
	for(var i=0; i<periodRefs.length; i++)
		if((period[0].getTime() >= periodRefs[i][0].getTime() && period[0].getTime() <= periodRefs[i][1].getTime())
				|| (period[1].getTime() >= periodRefs[i][0].getTime() && period[1].getTime() <= periodRefs[i][1].getTime())
				|| (period[0].getTime() <= periodRefs[i][0].getTime() && period[1].getTime() >= periodRefs[i][1].getTime()))
			return valid = false;
	
	//window.alert('HERE');
	return valid;
}

// - Just verifies the info isn't exactly the same....
function validateInfo(period,estId, Desc) {
	var valid = true;
	for (var i=0; i<perfRefs.length; i++)
		if(period[0].getTime() == perfRefs[i][0][0].getTime() && period[1].getTime() == perfRefs[i][0][1].getTime()
				&& estId == perfRefs[i][1]
				&& Desc == (perfRefs[i][2]+perfRefs[i][3]))
			return valid = false;
	
	return valid;
}

function createArts(artstr) {
	var tempArr=artstr.split('%%');
	var theArr=Array();
	for (var i=0; i < tempArr.length; i++) {
		var aux=Object();
		try {
			[aux.idx,aux.name]=tempArr[i].split('||');
		} catch (err) {
			var aux2=Array();
			aux2=tempArr[i].split('||');
			aux.idx=aux2[0];	aux.name=aux2[1];
		};
		theArr.push(aux);
	}//End For
	
	return theArr;
}
// - Dynamic elements's control code -
//----------------------------------------------

// - Calendar related code
function processDatesInfo(array) {

	//If it's a flagged object created a flagged date... ;)
	if(array.permanent!=null && array.permanent) {
		//window.alert('permanent');
		createPresentation(document.getElementById("est_sel"),Array(new Date(2030,11,8,23,11,8,0),new Date(2030,11,8,23,11,8,0)),'Permanent Event...', document.getElementById("perf_desc_en").value, document.getElementById("perf_desc_fr").value, document.getElementById("perf_desc_en").value);
		return 0;
	}
	var periods = compact_dates(array);
	//var periodsToShow=parse_periods(periods,'D M d');
	//parse_periods(periodsarr,format,tconnector,tformat,periodidx)
	//var periodsData=parse_periods_arrs(periods,'Y-m-d','H:i:s');
	for(var i=0; i<periods.length; i++) {
		var periodDisplay = parse_periods(periods,'D M d',' at ','H:i',i);
		//window.alert(document.getElementById("perf_desc_en").value);
		createPresentation(document.getElementById("est_sel"),periods[i],periodDisplay, document.getElementById("perf_desc_en").value, document.getElementById("perf_desc_fr").value, document.getElementById("perf_desc_en").value);
	}

	//TODO:
	//Gotta set it dynamically on callback registration...
	//combo.resetTheWholeThing();
}
//niz- overriding the function
function processDatesInfo(array, pricemin, pricemax, festival) {

	//If it's a flagged object created a flagged date... ;)
	if(array.permanent!=null && array.permanent) {
		//window.alert('permanent');
		oFestivalId = document.getElementById("festival_id");
		var selIndex = oFestivalId.selectedIndex;
			

createPresentation(document.getElementById("est_sel"),Array(new Date(2030,11,8,23,11,8,0),new Date(2030,11,8,23,11,8,0)),'Permanent Event...', document.getElementById("perf_desc_en").value, document.getElementById("perf_desc_fr").value, document.getElementById("perf_desc_en").value,pricemin, pricemax, oFestivalId.options[selIndex].text);
		return 0;
	}
	
	var periods = compact_dates(array);
	//alert("hi"+array.length);
	if (document.getElementById("est_sel").style.display != "none") {
		if(document.getElementById("est_sel").selectedIndex <= 0) {
			alert("Please, select an establishment.");
			return false;
		}
	}
	//if the selected days are in the past
	if(array.length == 0)
	alert("Selected days should be greater than today!")
	



	//var periodsToShow=parse_periods(periods,'D M d');
	//parse_periods(periodsarr,format,tconnector,tformat,periodidx)
	//var periodsData=parse_periods_arrs(periods,'Y-m-d','H:i:s');
	oFestivalId = document.getElementById("festival_id");
	var selIndex = oFestivalId.selectedIndex;
	
	
	for(var i=0; i<periods.length; i++) {
		var periodDisplay = parse_periods(periods,'D M d',' at ','H:i',i);
		//window.alert(document.getElementById("perf_desc_en").value);
		createPresentation(document.getElementById("est_sel"),periods[i],periodDisplay, '', document.getElementById("perf_desc_fr").value, document.getElementById("perf_desc_en").value, pricemin, pricemax, oFestivalId.options[selIndex].text);
	}
	return fCheckEvents();
	//TODO:
	//Gotta set it dynamically on callback registration...
	//combo.resetTheWholeThing();
}
// -
function processDatesChosen(array,form,sdate,edate) {
	var periods = compact_dates(array);
	
	//As I am expecting only one period...
	
	sdate.value = periods[0][0].dateFormat('Y/m/j');
	edate.value = periods[0][1].dateFormat('Y/m/j');
	form.submit();
	/*for(var i=0; i<periods.length; i++) {
		var periodDisplay = parse_periods(periods,'D M d',' at ','H:i',i);
		//window.alert(document.getElementById("perf_desc_en").value);
		createPresentation(document.getElementById("est_sel"),periods[i],periodDisplay, document.getElementById("perf_desc_en").value, document.getElementById("perf_desc_fr").value, document.getElementById("perf_desc_en").value);
	}*/

	//TODO:
	//Gotta set it dynamically on callback registration...
	//combo.resetTheWholeThing();
}


// - Calendar related code -
//----------------------------------------------

// - Sajax Related Code
function procSearchLvlInfo(arr) {	
	var selector= document.getElementById('search_sel');
	var children=selector.childNodes;
	var opt = document.createElement('option');

	opt.setAttribute('value','-');
	opt.appendChild(document.createTextNode('---'));
	while(children.length>0) selector.removeChild(children[0]);
	selector.appendChild(opt); //Much faster than verify each element not to remove i
	/*for(var i=children.length-1; i>=0; i--)
		if(children[i].id!='search_novalue')
			selector.removeChild(children[i]);*/
	
	for(var cellidx in arr) {
		var opt = document.createElement('option');
		opt.setAttribute('value',arr[cellidx]['id']);
		opt.appendChild(document.createTextNode(arr[cellidx]['name']));
	
  	//added by niz to select montreal by default
		//and update the list of establishments
    if(arr[cellidx]['name'] == "Montréal")
    {
    opt.setAttribute('selected', 'selected');
    getEstablishments(arr[cellidx]['id']);
    }		
		selector.appendChild(opt);
	}
}
	
function getEstablishments(searchLvlId) {
	searchLevel1 = searchLvlId;
	
	if(webSite) {
		if(searchLevel1!=null && searchLevel1!='-')
			x_get_establishments(searchLevel1,webSite,procEstInfo);
		else 
			procEstInfo(null);
	}
}

function procEstInfo(arr) {

		var selector= document.getElementById('est_sel');
		var children=selector.childNodes;
		var opt = document.createElement('option');
		
		opt.setAttribute('value','-');
		opt.appendChild(document.createTextNode('---'));
		while(children.length>0) selector.removeChild(children[0]);
		selector.appendChild(opt);
	
		for(var cellidx in arr) {
			var opt = document.createElement('option');
			opt.setAttribute('value',arr[cellidx]['id']);
			opt.appendChild(document.createTextNode(arr[cellidx]['name']));
			selector.appendChild(opt);
		}
}

function changeWebSite(website_id) {
	var selector= document.getElementById('est_sel');
	var opt = document.createElement('option');
	var children=selector.childNodes;

	opt.setAttribute('value','-');
	opt.appendChild(document.createTextNode('---'));
	while(children.length>0) selector.removeChild(children[0]);
	selector.appendChild(opt); //Much faster than verify each element not to remove it.
	
	webSite=website_id;
	
	if(website_id!=null && website_id!='-') {
		x_get_searchlevel1(webSite,procSearchLvlInfo);
		endWebSiteChange();
	} else {
		selector= document.getElementById('search_sel');
		opt = document.createElement('option');
		children=selector.childNodes;

		opt.setAttribute('value','-');
		opt.appendChild(document.createTextNode('---'));
		while(children.length>0) selector.removeChild(children[0]);
		selector.appendChild(opt); //Much faster than verify each element not to remove it.
	}
	/*if(searchLevel1!=null)
		getEstablishments(cityId);*/
}

function startWebSiteChange() {
	document.getElementById('websitename').style.display='none';
	document.getElementById('websitenamelink').style.display='none';
	document.getElementById('website_sel').style.display='inline';	
}

function endWebSiteChange() {
	//+2 <<-- Remember
	document.getElementById('websitename').innerHTML="<b>"+document.getElementById('website_sel').childNodes[document.getElementById('website_sel').selectedIndex+2].text+"</b>"; //added bold
	document.getElementById('websitename').style.display='inline';
	document.getElementById('websitenamelink').style.display='inline';
	document.getElementById('website_sel').style.display='none';
	
}
// - Sajax Related Code -
//----------------------------------------------

// - Data Quality checks & submit
// - At this point the file containing epoch's array function "arrayIndex"
// - should be available...
function QCChecks() {
	var arr=Array('cat_id','name_en','name_fr','desc_en','desc_fr');
	var keepArts=Array();
	var delArts=Array();
	
	for(var i=0; i<arr.length; i++) {
		var element=document.getElementById(arr[i]);
		if (element.type != "hidden") {
			if(element.value==null || element.value=='' || element.value=='-') {
				var nameStr=(element.title)?element.title:element.id;
				window.alert("There's a problem with the "+nameStr+" field.");
				if (element.style.display == "") {
					fShowInfos(1,15,15,16);
					if (element.name == "name_en" || element.name == "cast_en") {
						fShowInfos(35,40,9,10);
						location.replace('#englishinfos');
					} else {
						location.replace('#generals');
					}
				}
				element.focus();
				//window.alert(element.scrollHeight);
				//window.scrollTo(0,element.scrollHeight);
				return false;
			}
		}
	}
	
	//For artists.... Just remove those who don't have any value or appear more than once.
	for(var i=0; i<artistRefs.length; i++)
		if(keepArts.arrayIndex(artistRefs[i].selector.value)>-1 || artistRefs[i].selector.value=='-')
			//Push it onto the delete queue
			delArts.push(artistRefs[i]);
	else
			keepArts.push(artistRefs[i].selector.value);

	for(var i=delArts.length-1; i>=0; i--) {
		removeArtist(delArts[i].countIdx);
	}

	/*
	if(!artistRefs.length) {
		//Oops... no good artist...
		artistCount=0
		createNewArtist(artistCount++);
		window.alert("You must select at least one Artist.");
		artistRefs[0].selector.focus();
		window.scrollTo(0,getTop(artistRefs[0])+10);
		
		return false;
		
	}
	*/
	//For performances... they are already clean... just verify there's at least one...
	//They were... //2006Dec05
	//if(!establishments.length || !periodRefs.length || !periodEsts.length) {
	if(!perfRefs.length) {
		window.alert("At least one performance must be added.");

		if (document.getElementById('website_sel').style.display == "") {
			document.getElementById('website_sel').focus(); 
			window.scrollTo(0,getTop(document.getElementById('website_sel'))+10);
		} else {
			fShowInfos(20,26,30,31);
			location.replace('#performances')
		}
		
		return false;
	}
	
	return true;
	
}

function submitData(URL) {
	if (QCChecks()) {	
		//simple... everything checked... just send the info.
		var arr=Array('name_en','name_fr','desc_en','desc_fr','website','email','phone','cat_id','cast_en','cast_fr');
		//var aux= new info(artistRefs,periodEsts,arr);
		var aux= new info(artistRefs,perfRefs,arr);
		//x_do_submit(info,function(str) { var qqch=''; for(var i in str) qqch+=i+': '+str[i]; window.alert(qqch);});
		//window.alert(justADumpVar(aux));
		//x_do_submit(aux,function(str) {window.alert(str); location.replace('');});
		x_do_submit(aux,URL,whyIE);
	}

}

function editData(URL) {
	if (QCChecks()) {
		//simple... everything checked... just send the info.
		var arr=Array('show_id','name_en','name_fr','desc_en','desc_fr','website','email','phone','cat_id','cast_en','cast_fr');
		var aux= new info(artistRefs,perfRefs,arr);
		x_do_submit(aux,URL,whyIE); //Here we could nicely have used function(str){window.alert(str);location.replace('');} 
		
	}
}

//Created to workaround a LIMITATION!! on IE's javascript machine.
/*function whyIE(str,URL) {
	alert(URL)
	//window.alert(justADumpVar(str)); 
	window.alert(str);
	location.replace(URL);
}*/

function whyIE(str, URL) {
	var arrStr = str.split("|");
	//window.alert(justADumpVar(str)); 
	window.alert(arrStr[0]);
	location.replace(arrStr[1]);
}

function info(artistRefs,periodEsts,otherElementsArr) {
	// %|% First Level Separator
	// >|< Second Level Separator
	// #|# Third Level Separtor
	this.artists='';
	this.performances='';
	this.otherData='';
	
	this.prepareArtists(artistRefs);
	this.preparePerformances(periodEsts);
	this.prepareOtherData(otherElementsArr);
};
//--
info.prototype.prepareArtists = function(artistRefs) {
	var vals=Array();
	for(var i=0; i<artistRefs.length; i++)
		vals.push(artistRefs[i].selector.value);
	
	this.artists=vals.join('>|<');
};
//--
/*info.prototype.preparePerformances = function(periodEsts) {
	var vals=Array();
	for(var i=0; i<periodEsts.length; i++) {
		var str='';
		str+=periodEsts[i][0]+'#|#';
		str+=periodEsts[i][1][0].dateFormat('Y-m-d H:i')+'#|#';
		str+=periodEsts[i][1][1].dateFormat('Y-m-d H:i');
		vals.push(str);
	}
	
	this.performances=vals.join('>|<');
};*/
info.prototype.preparePerformances = function(refs) {
	var vals=Array();
	for(var i=0; i<refs.length; i++) {
		var str='';
		str+=refs[i][1]+'#|#';
		str+=refs[i][0][0].dateFormat('Y-m-d H:i')+'#|#';
		str+=refs[i][0][1].dateFormat('Y-m-d H:i')+'#|#';
		str+=refs[i][2]+'#|#';
		str+=refs[i][3]+'#|#';
		str+=refs[i][4]+'#|#';
		str+=refs[i][5]+'#|#';
		str+=refs[i][6]+'#|#';
		str+=refs[i][7];
		vals.push(str);
	}
	
	this.performances=vals.join('>|<');
};
//--
info.prototype.prepareOtherData = function (otherElementsArr) {
	var vals=Array();
	for(var i=0; i<otherElementsArr.length; i++) {
		var str='';
		str+=otherElementsArr[i]+"#|#";
		str+=document.getElementById(otherElementsArr[i]).value;
		vals.push(str);
	}
	
	this.otherData=vals.join('>|<');
};
//--
info.prototype.toString = function() {
	return ''+this.artists+'%|%'+this.performances+'%|%'+this.otherData;
};
// - Data Quality checks & submit-
//----------------------------------------------


// - Color control...
//----------------------------------------------
//For Colors on rows...
var artistCol;
var artistColors=Array('#fff','#e0e0e0');
function getNextArtistColor() {
	return artistColors[(artistCol=(artistCol)?0:1)];
}
//--
var estCol;
var estColors=Array('#fff','#eaeaea');
var perfCol;
var perfColors=Array(Array('#fff','#e0e0e0'),Array('#eaeaea','#e0e0e0'));
function getNextEstColor() {
	return estColors[(estCol=(estCol)?0:1)];
}
//-
function getNextPerfColor() {
	return perfColors[estCol][(perfCol=(perfCol)?0:1)];
}

function zebraTableBody(tbody,type) {
	switch(type) {
		case 'artist':
			artistCol=0;
			for(i in tbody.childNodes)
				try {
					tbody.childNodes[i].style.backgroundColor=getNextArtistColor();
				} catch (err) {};
				
			break;
		case 'est':
			estCol=0;
			for(i in tbody.childNodes)
				try {
					tbody.childNodes[i].style.backgroundColor=getNextEstColor();
				} catch (err) {};	
			break;
		case 'perf':
			perfCol=1;
			for(i in tbody.childNodes) {
				try {
					//window.alert(i);
					tbody.childNodes[i].style.backgroundColor=getNextPerfColor();
				} catch (err) {};
			}
			break;
		default:
			return false;
	}
}

// - Color control... -
//----------------------------------------------

//- Other stuff -	
//Old Code ***** BEWARE!!! Currently not in use!!!!
function openChooseEstWrapClassic(Opener_ID) {
	window.getItW=window.open('choose_est_wrap.php', 'getItW', 'height=600px,resizable,width=800px',true);
	window.getItW.getItWOp=Opener_ID;
}


function getTop(element) {
    var oNode = element;
    var iTop = 0;
    
    while(oNode.tagName != 'BODY') {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop;
};

function getEventData(dataObj) {

	//array('artists' => $artists, 'perfs' => $perfs, 'otherdata' => $otherdata);
	var artists = dataObj['artists'];
	var perfs = dataObj['perfs'];
	var otherData = dataObj['otherdata'];
	//alert (otherData['website']);
	
	for(i in artists) {
		createNewArtist(artistCount++,artists[i]);
	}
	
	
	
	for(i in perfs) {
		
		var period=Array();
		var aux=parseDBTimeStamp(perfs[i][2]);
		period.push(new Date(aux[0],aux[1]-1,aux[2],aux[3],aux[4]));
		
		aux=parseDBTimeStamp(perfs[i][3]);
		period.push(new Date(aux[0],aux[1]-1,aux[2],aux[3],aux[4]));
	
		var aux2=new Object;
		aux2.value=perfs[i][0];
		aux2.text=perfs[i][1]
		var periodDisplay = parse_periods(Array(period),'D M d',' at ','H:i',0);
		//createPresentation(aux2,period,periodDisplay);
		//createPresentation(estRef,period,periodDisplay,desc_en,desc_fr,descDisplay, pricemin, pricemax, festival) {

		createPresentation(aux2,period,periodDisplay, perfs[i][4], perfs[i][5], perfs[i][4], perfs[i][6],perfs[i][7],perfs[i][8]);
		
	}
	
	/*/
	for(i in otherData) {
		
		try {
			document.getElementById(i).value=otherData[i];
		} catch (err) {};
	}
	*/
}

function parseDBTimeStamp(timeStamp) {
	
	var aux=timeStamp.split(" ");
	var year,month,day;
	var hour,min,sec;
	
	try {
		[year,month,day]=aux[0].split("-");
	} catch(err) {		
		var aux2=Array();
		aux2=aux[0].split("-");
		year=aux2[0];
		month=aux2[1];
		day=aux2[2];		
	};
	
	try {
		[hour,min,sec]=aux[1].split(":");
	} catch(err) {
		var aux2=Array();
		aux2=aux[1].split(":");
		hour=aux2[0];
		min=aux2[1];
		sec=aux2[2];
	};
	return Array(year,month,day,hour,min,sec);
}


// Took from another file... (fp_cal.js)
// Be careful not to overlap functions...
function shortenString(str,maxlength) {
	if(!maxlength || maxlength<-1)
		return str;
	
	if(str.length > maxlength)
		return ((str.substr(0,maxlength-2))+'...');
	else
		return str;
}


// - Just a dump var
function justADumpVar(theEle) {  
	var str='';
	for (var aux in theEle) {
		str+=''+aux+' : '+theEle[aux]+"\n";
	}

	return str;	
}

//----------------------------------------------------
// - Object mods....
Array.prototype.perfIndex = function(period,estId, Desc) {
	for(var i=0;i<this.length;i++) {
		if(period[0].getTime() == this[i][0][0].getTime() && period[1].getTime() == this[i][0][1].getTime()
				&& estId == this[i][1]
				&& Desc == (this[i][2]+this[i][3]))
			return i;
	}
	return -1;
};





// - File's Basement -
//----------------------------------------------

/*
// * * * * * * * Old Code for createPresentation * * * * * * 		
		var row = document.createElement('tr');
		var estCell = document.createElement('td');
		var dateCell = document.createElement('td');
		var remCell = document.createElement('td');
		var link = document.createElement('a');
		
		//estCell
		estCell.appendChild(document.createTextNode(estRef.childNodes[estRef.selectedIndex].text));
		estCell.setAttribute('width','30%');
	
		
		//dateCell
		dateCell.appendChild(document.createTextNode(periodDisplay));
		dateCell.setAttribute('width','50%');
		
		//remCell
		////Link
		link.setAttribute('href','javascript: void(0);');
		link.onclick = function () { window.alert('Remove '+estRef.childNodes[estRef.selectedIndex].text);};
		link.appendChild(document.createTextNode('Remove'));
		link.row=row;
		remCell.appendChild(link);
		
		//Row
		row.countIdx=0;
		row.remLink=link;	//Gives a quick access to the element;
		
		row.appendChild(estCell);
		row.appendChild(dateCell);
		row.appendChild(remCell);
		
		document.getElementById('performanceTableBody').appendChild(row);


// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 

//- Sajax Related Code -
function procCityInfo(arr) {
	
	var selector= document.getElementById('city_sel');
	var children=selector.childNodes
	for(var i=children.length-1; i>=0; i--)
		if(children[i].id!='city_novalue')
			selector.removeChild(children[i]);
	
	for(var cellidx in arr) {
		var opt = document.createElement('option');
		opt.setAttribute('value',arr[cellidx]['city_id']);
		opt.appendChild(document.createTextNode(arr[cellidx]['city_name_en']));
		selector.appendChild(opt);
	}
}

//removing option elements on selects old code...
	for(var i=children.length-1; i>=0; i--)
		if(children[i].id!='search_novalue')
			selector.removeChild(children[i]);






		var info=Array();
		info.artists= artistRefs;
		info.dates=periodRefs;
		info.establishments=establishments;
		info.periodest=periodEsts;
		info.push(Array('artists',artistRefs));
		info.push(Array('dates',periodRefs));
		info.push(Array('establishments',establishments));
		info.push(Array('periodests',periodEsts));
		
		var aux=Array();
		for(var i=0; i<arr.length; i++)
			//info[arr[i]]=document.getElementById(arr[i]).value;
			aux.push(Array(arr[i],document.getElementById(arr[i]).value));
			
		info.push(Array('otherfields',aux));
			
		window.alert('Here!!');



		var str='';
		for(j in artistList.childNodes[i][cella]) {
			str+=j+' : '+artistList.childNodes[i][cellaa][j]+"\n";
		}
		window.alert(str);



*/

