// metawrap fastsearch functions for populating cinema search fields and returning search results
stateChosen = cityChosen = regionChosen = "null";
var locationPreviouslySet = false;
var cinemaRegionOnPageLoad = findInCookie('bpme_cinema_location','region');

function setupSidebar() {

	locationPreviouslySet = true;
	// location hasn't been set yet
	if(cinemaRegionOnPageLoad == 0){
		$('showTimesFormLocation').style.display = $('showTimesOr').style.display = $('showTimesCinemaSearch').style.display = "block";
	} else {
		
		// if favourite cinemas exist, display, otherwise show instructions panel
		if(getListOfCinemas()){
			displayListOfCinemas();
		} else {
			$('chooseFavouriteCinemas').style.display = "block";
		}

		// update text display of user's area
		updateCinemaSearchLocation(findInCookie('bpme_cinema_location','city'),findInCookie('bpme_cinema_location','region') )
		// show text display of user's area and favourite cinemas area
		$('showTimesLocationChosen').style.display = $('showTimesFaveCinemas').style.display = "block";
		$('showTimesMovieSearch').style.borderBottom = "0";
	}
}


var l_fastsearch_action = null;
var index = 1;
var today = new Date();
var weekdays = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");

// before location is set, look up states from DB
function populateStates(whichForm) {
	setupSidebar();
// which form? in the sidebar (1) or above the search results in the movie page (2)
	index = (whichForm==2) ? 2 : 1;
// Create the search action object
	var l_fastsearch = new MetaWrap.XML.Action.Showtimes.states();
	// This will serialise it into XML and post it to the aspx file
//l_fastsearch_action = new MetaWrap.XML.Action(l_fastsearch,strShowtimesPath+"states.aspx");
	l_fastsearch_action = new MetaWrap.XML.Action(l_fastsearch,"/showtimes/states.aspx");
	l_fastsearch_action.run(fastsearch_states_done);
}
// called from populateStates() - once JS finds states, populate states dropdown
function fastsearch_states_done() {
	//fill states dropdown with results
	var l_result = l_fastsearch_action.m_transaction.m_response.m_states.m_results;	
//alert("test: " + l_result); //opera & safari don't make it this far
	for(i=0;i<l_result.length;i++){
		addOption('selState'+index,l_result[i],l_result[i]);
	}
	
	// if value found in cookie, update dropdown and move to next stage
	if(findInCookie('bpme_cinema_location','state') != 0) {
		setDropdown('selState'+index,findInCookie('bpme_cinema_location','state'))
		updateCities(index);
	}
}

// look up cities based on state chosen, called onchange from states dropdown
// or directly from fastsearch_states_done() if state location is stored in cookie
function updateCities(whichForm) {
	index = (whichForm==2) ? 2 : 1;
	//reset next dropdowns and disable
	disableSearches(true);
	$('selRegions'+index).disabled = true;
	$('selCity'+index).disabled = true;
	removeOptions('selRegions'+index);addOption('selRegions'+index,'null','Choose your local area');
	removeOptions('selCity'+index);addOption('selCity'+index,'null','Choose city');

	stateChosen = $('selState'+index).options[$('selState'+index).selectedIndex].value;
	if(stateChosen == "null") return;
	
	// Create the search action object
	var l_fastsearch = new MetaWrap.XML.Action.Showtimes.citiesofstate(stateChosen);
//l_fastsearch_action = new MetaWrap.XML.Action(l_fastsearch,"/showtimes/citiesofstate.aspx");
	l_fastsearch_action = new MetaWrap.XML.Action(l_fastsearch,strShowtimesPath+"citiesofstate.aspx");	
	l_fastsearch_action.run(fastsearch_cities_done);
}
// called from updateCities() - once JS finds cities, populate cities dropdown
function fastsearch_cities_done() {
	// fill cities dropdown with results
	var l_result = l_fastsearch_action.m_transaction.m_response.m_citiesofstate.m_results;	
  	for(i=0;i<l_result.length;i++){
		addOption('selCity'+index,l_result[i],l_result[i]);
	}
 	$('selCity'+index).disabled = false;
	
	// if value found in cookie, update dropdown and move to next stage
	if(findInCookie('bpme_cinema_location','city') != 0) {
		setDropdown('selCity'+index,findInCookie('bpme_cinema_location','city'));
		updateRegions(index);
	}
}

// look up regions based on city chosen, called onchange from cities dropdown
// or directly from fastsearch_cities_done() if city location is stored in cookie
function updateRegions(whichForm) {
	index = (whichForm==2) ? 2 : 1;
	//reset next dropdown and disable
	disableSearches(true);
	$('selRegions'+index).disabled = true;
	removeOptions('selRegions'+index);	addOption('selRegions'+index,'null','Choose your local area');
//	$('selRegions').innerHTML = '<option value="null">Choose your local area</option>';
	cityChosen = $('selCity'+index).options[$('selCity'+index).selectedIndex].value;
	if(cityChosen == "null") return;
	// Create the search action object
	var l_fastsearch = new MetaWrap.XML.Action.Showtimes.regionsofcity(cityChosen);
//l_fastsearch_action = new MetaWrap.XML.Action(l_fastsearch,"/showtimes/regionsofcity.aspx");
	l_fastsearch_action = new MetaWrap.XML.Action(l_fastsearch,strShowtimesPath+"regionsofcity.aspx");
	l_fastsearch_action.run(fastsearch_regions_done);
}
// called from updateRegions() - once JS finds regions, populate regions dropdown
function fastsearch_regions_done() {
	// fill regions dropdown with results
	var l_result = l_fastsearch_action.m_transaction.m_response.m_regionsofcity.m_results;	
	for(i=0;i<l_result.length;i++){
		addOption('selRegions'+index,l_result[i].m_id,l_result[i].m_name);		
	}
  	$('selRegions'+index).disabled = false;

	// if value found in cookie, update dropdown and move to next stage
	if(findInCookie('bpme_cinema_location','city') == cityChosen && findInCookie('bpme_cinema_location','region') != 0) {
		setDropdown('selRegions'+index,findInCookie('bpme_cinema_location','region'));
		updateResults(index);
	}
}

// sets state, city, region, and regionID in cookie, once region picked from dropdown
// or directly from fastsearch_regions_done() if region location is stored in cookie
function updateResults(index){
	if(locationPreviouslySet && cinemaRegionOnPageLoad != 0) closeLocationChanger();
	
	// eventually replace this with venuessessionsandtitlesofregion script
	//reset results
	disableSearches(true);
	regionChosen   = $('selRegions'+index).options[$('selRegions'+index).selectedIndex].text;
	regionidChosen = $('selRegions'+index).options[$('selRegions'+index).selectedIndex].value;
	if(regionidChosen == "null") return;
	
	cinemaLocationChanged = false;
	// flag if the location has changed at any point - if so, location notification overlay must be fired on submit.
	if(regionChosen != cinemaRegionOnPageLoad) {
		cinemaLocationChanged = true;
	}

	writeCookie("bpme_cinema_location","state",stateChosen)
	writeCookie("bpme_cinema_location","city",cityChosen)
	writeCookie("bpme_cinema_location","region",regionChosen)
	writeCookie("bpme_cinema_location","regionid",regionidChosen)

	// if region chosen is not null, enable search buttons
	disableSearches(false);
}

// update the text indicators of what the chosen location is
function updateCinemaSearchLocation(city,region) {	
	if($('cinemaSearchLocation1')){
		if(city) {
			$('cinemaSearchLocation1').innerHTML = city + ", " + region;
			$('cinemaSearchLocation1').className = "";
		} else {
			$('cinemaSearchLocation1').className = "noAreaChosen";
			$('cinemaSearchLocation1').innerHTML = "No area chosen";
		}
	}		
	if($('locationChosen')) {
		$('locationChosen').innerHTML = findInCookie('bpme_cinema_location','region') +", "+findInCookie('bpme_cinema_location','city') +", "+findInCookie('bpme_cinema_location','state');
	}
}

// called from disableSearches() once location dropdowns are completed, look up movies showing in that region
function updateMovies() {
	// disable movie search submit button
	disableMovieSubmit(true);

	// Create the search action object
	regionidChosen = $('selRegions'+index).options[$('selRegions'+index).selectedIndex].value;
    var l_fastsearch = new MetaWrap.XML.Action.Showtimes.titlesofregion(regionidChosen);
  //l_fastsearch_action = new MetaWrap.XML.Action(l_fastsearch,"/showtimes/titlesofregion.aspx");
		l_fastsearch_action = new MetaWrap.XML.Action(l_fastsearch,strShowtimesPath+"titlesofregion.aspx");		
	l_fastsearch_action.run(fastsearch_titles_done);
}

// called from updateMovies() once JS has looked up movies showing - populates movies and date dropdowns
function fastsearch_titles_done() {
	var l_response = l_fastsearch_action.m_transaction.m_response.m_titlesofregion;
	var l_results = l_response.m_results;
	filmTitles = new Array();
	
	// collect film titles into an array
	for(i=0;i<l_results.length;i++) {
		filmTitles[filmTitles.length] = l_results[i].m_name + "_" + l_results[i].m_id;
	}
	// and then sort alphabetically
	filmTitles.sort();
	// then put film titles into dropdown
	for(i=0;i<filmTitles.length;i++){
		addOption('selMovie1',filmTitles[i].split('_')[1],filmTitles[i].split('_')[0]);		
	}
	
	// populate date ONCE.
	if($('selDate1').options.length< 2){
		for(i=1;i<7;i++){
			jsDayIndex = (i + today.getDay() > 6) ? i + today.getDay() - 7: i + today.getDay();
			dayName = (i == 1) ? "Tomorrow" : weekdays[jsDayIndex];
			addOption('selDate1',i,dayName)
		}
	}

}

// function to toggle the searches on or off. If location selects aren't completed, find movie and cinema searches are disabled.
//	if the find movie search dropdown is present, call function to update it (updateMovies())
function disableSearches(disable) {
	if(disable==true) {
		if(index == 1) {
			//showtimes section within the sidebar
			$('cinemaSearchSubmit1').style.background = "url("+strTemplateResourcePath+"images/btn_go_disabled.gif) no-repeat 1px 2px";
			$('cinemaSearchSubmit3').style.background = "url("+strTemplateResourcePath+"images/btn_go_disabled.gif) no-repeat 1px 2px";
			$('cinemaSearchSubmit1').onclick = "return false";
			if($('selMovie1')) {
				$('selMovie1').disabled = $('selDate1').disabled = true;
				removeOptions('selMovie1');	addOption('selMovie1','null','Which movie?');
			}
		}
		if(index == 2) {
			//showtimes section within main column			
			//$('cinemaSearchSubmit2').style.background = "url("+strTemplateResourcePath+"images/btn_go_disabled.gif) no-repeat 1px 2px";
			$('cinemaSearchSubmit2').style.background = "url("+strTemplateResourcePath+"images/spacer.gif) no-repeat 1px 2px";
			$('cinemaSearchSubmit2').onclick = "return false";	
		}
		updateCinemaSearchLocation();
	} else {		
		if(index == 1) {
			//showtimes section within the sidebar
			$('cinemaSearchSubmit1').onclick = "";
			$('cinemaSearchSubmit1').style.background = "url("+strTemplateResourcePath+"images/btn_go.gif) no-repeat left top";
			$('cinemaSearchSubmit3').style.background = "url("+strTemplateResourcePath+"images/btn_go.gif) no-repeat left top";
			if($('selMovie1')) {
			// enable select boxes for movie search (in sidebar) and populate them.
				updateMovies();
				$('selMovie1').disabled = $('selDate1').disabled = false;
			}
		}
		if(index == 2) {
			//showtimes section within main column
			$('cinemaSearchSubmit2').onclick = "submitCinemaSearch2();";
			$('cinemaSearchSubmit2').style.background = "url("+strTemplateResourcePath+"images/btn_go.gif) no-repeat left top";
		}	
		// show user what location they've picked in the showtimesCinemaSearch
		updateCinemaSearchLocation(cityChosen,regionChosen);
	}
}

// called by movie select element onchange - checks to make sure a film is selected before enabling submit button
function movieChosen(){
	if($('selMovie1').selectedIndex > 0) {
		disableMovieSubmit(false);
	} else {
		disableMovieSubmit(true);
	}
}

// toggles enabled status of movie search submit button. called by fn movieChosen()
function disableMovieSubmit(disable) {
	if(disable==true) {
		$('movieSearchSubmit1').style.background = "url("+strTemplateResourcePath+"images/btn_go_disabled.gif) no-repeat 1px 2px"
		$('movieSearchSubmit1').style.cursor = "default";
		$('movieSearchSubmit1').onclick = function() {return false;}
		
	} else {
		$('movieSearchSubmit1').style.background = "url("+strTemplateResourcePath+"images/btn_go.gif) no-repeat left top"
		$('movieSearchSubmit1').style.cursor = "pointer";
		$('movieSearchSubmit1').onclick = function() {submitMovieSearch(); return false;}
	}
}

// called by movie search submit button - sends user to the movie page with session times showing
function submitMovieSearch(){

	// set date in cookie (5 minutes duration)
	writeCookie2("bpme_cinema_date","dayoffset",$('selDate1').options[$('selDate1').selectedIndex].value)
	
	// get movie url from selected dropdown option
	movieSearchResultsURL = strTemplateResourcePath + "libraries/article_library/movie_listings/"+getMovieUrl($('selMovie1').options[$('selMovie1').selectedIndex].value,$('selMovie1').options[$('selMovie1').selectedIndex].text) + "?display=showtimes";
	// if cinema location has been changed, display notice overlay
	if(cinemaLocationChanged) {
		showLocationOverlay(movieSearchResultsURL);
		return;
	} else {
	// go to results page
		document.location.href = movieSearchResultsURL;
	}
}

function submitCinemaSearch() {
	resetDateCookie();
	cinemaSearchResultsURL = strTemplateResourcePath + "at_the_cinema/in_cinemas_now/";
	
	// if cinema location has been changed, display notice overlay
	if(cinemaLocationChanged) {
		showLocationOverlay(cinemaSearchResultsURL);
		return false;
	} else {
	// go to results page
		return true;
	}
}

function submitCinemaSearch2() {
	resetDateCookie();
	cinemaSearchResultsURL = "?display=showtimes";
	showLocationOverlay(cinemaSearchResultsURL);
	return false;
}

// add options to DOM
function addOption(selectId,optionValue,optionText) {
	newOption = document.createElement('option');
	textNode = document.createTextNode(optionText);
	attrNode = document.createAttribute('value');
	attrNode.value = optionValue;
	newOption.appendChild(textNode);
	newOption.setAttributeNode(attrNode);
	$(selectId).appendChild(newOption);
}

// remove all option nodes from a select
function removeOptions(selectId){
	$(selectId).innerHTML = '';
}

// if values are found in cookie, update dropdown using cookie values
function setDropdown(dropdownName,dropdownValue){
	dropdown = $(dropdownName);
	for(i=0;i<dropdown.options.length;i++){
		if(dropdown.options[i].text == dropdownValue) dropdown.selectedIndex = i;
	}
}

function setLocationFromPostcode(postcodeValue){
	var l_fastsearch = new MetaWrap.XML.Action.Showtimes.postcode(postcodeValue);
	l_fastsearch_action = new MetaWrap.XML.Action(l_fastsearch,strShowtimesPath+"postcodeinformation.aspx");	
	l_fastsearch_action.run(fastsearch_postcode_done);
}
/*
function fastsearch_postcode_done() {
	// set cookie based on postcode result
	var l_result = l_fastsearch_action.m_transaction.m_response.m_postcodeinformation.m_results;	
	if(l_result.m_state!= "") 		writeCookie("bpme_cinema_location","state",l_result.m_state)
	if(l_result.m_city!= "") 			writeCookie("bpme_cinema_location","city",l_result.m_city)
	if(l_result.m_region!= "")		writeCookie("bpme_cinema_location","region",l_result.m_region)

//alert(l_result.m_state +" "+l_result.m_city +" "+l_result.m_region)

}*/

function submitChangeLocation(){
	if(findInCookie('bpme_cinema_location','region')!=0);
	document.location.reload();
}

// open change location panel in the sidebar if location is already set - moves button to the right and hides submit button
function locationChangeToggle() {
	if($('locationChosenChange').innerHTML == "Change this location") {
		// change button to 'close this' for closing location panel
		$('locationChosenChange').style.background = "url("+strTemplateResourcePath+"images/btn_tab.gif) no-repeat right bottom";
		$('locationChosenChange').style.padding = "4px 10px 0 0"
		$('locationChosenChange').style.textAlign = "right"
		$('locationChosenChange').innerHTML = "Close this";
		$('cinemaSearchSubmit3').hide();
		
		// show location form
		$('showTimesFormLocation').style.display = "block";
		$('showTimesFormLocation').style.borderWidth = "1px 0";
	} else {
		closeLocationChanger();
	}
}

// close the location changer panel in the sidebar
function closeLocationChanger() {
	// change button to 'change location link'
	$('locationChosenChange').style.background = "none"
	$('locationChosenChange').style.padding = "0"
	$('locationChosenChange').style.textAlign = "left"
	$('locationChosenChange').innerHTML = "Change this location";
	$('cinemaSearchSubmit3').style.display = "block";
	
	// hide location form;
	$('showTimesFormLocation').hide();
	$('showTimesFormLocation').style.borderWidth = "0";
}

// display overlay advising users the change of default location, called on search submit from movie search or cinema search.
function showLocationOverlay(postNoticeAction) {
	$('loc_state').innerHTML = stateChosen;
	$('loc_city').innerHTML = cityChosen;
	$('loc_region').innerHTML = regionChosen;
	// set continue button's href to either cinema search results or find a movie search results page
	$('overlayLocationContinue').href = postNoticeAction;
	$('overlayLocationContinue').onclick = function() {hideBox()}
	showBox('overlayLocation','boxLocation')
}

// displays list of fave cinemas in sidebar
function displayListOfCinemas() {
	var sidebarCinemaList = "";

	// generate <li>s with links
	for(i=0;i<getListOfCinemas().length;i++){
		strCinemaName     = unescape(getListOfCinemas()[i]).split('~')[0];
		strCinemaState    = unescape(getListOfCinemas()[i]).split('~')[1];
		strCinemaCity     = unescape(getListOfCinemas()[i]).split('~')[2];
		strCinemaRegion   = unescape(getListOfCinemas()[i]).split('~')[3];
		strCinemaRegionid = unescape(getListOfCinemas()[i]).split('~')[4];

		sidebarCinemaList += '<li>';
		sidebarCinemaList += '<a class="isFavourite" onclick="toggleFave(this);return false;" href="#"><div><span>Remove from favourites</span></div></a>';

		//add a check here, to see if each cinema within the loop has any movies/sessions listed today. if yes then carry on. if not list them, but greyed out. 
		/*
		var thisCinema = escape(getListOfCinemas()[i]);
		checkForSessions(thisCinema);
		alert("checkSessionsThisVenue " + checkSessionsThisVenue);
		if(checkSessionsThisVenue == 1) {
			//sessions exist. reset day offset to 0 (today). reset region to the region of this cinema.	
			sidebarCinemaList += '<a href="' + strTemplateResourcePath + 'at_the_cinema/in_cinemas_now/?theatre='+escape(getListOfCinemas()[i])+'" class="cinemaName" title="Find out more about this cinema" onclick="resetDateCookie();">'+getListOfCinemas()[i]+'</a>';
		} else {
			var msgStr = 'no movies found, please check again later';	
			sidebarCinemaList += '<a href="" class="cinemaName" title="Find out more about this cinema" onclick="alert(msgStr);">'+getListOfCinemas()[i]+'</a>';
		}
		*/
		//sidebarCinemaList += '<a href="' + strTemplateResourcePath + 'at_the_cinema/in_cinemas_now/?theatre='+escape(getListOfCinemas()[i])+'" class="cinemaName" title="Find out more about this cinema" onclick="resetDateCookie();">'+getListOfCinemas()[i]+'</a>';
		sidebarCinemaList += '<a href="' + strTemplateResourcePath + 'at_the_cinema/in_cinemas_now/?theatre='+unescape(strCinemaName)+'" class="cinemaName" title="Find out more about this cinema"';
		sidebarCinemaList += ' onclick="resetRegionCookie(\''+strCinemaState+'\',\''+strCinemaCity+'\',\''+strCinemaRegion+'\',\''+strCinemaRegionid+'\');resetDateCookie()">'+unescape(strCinemaName)+'</a>';
		sidebarCinemaList += '</li>';
	}

	//if cinema list doesn't already exists, create <ul> node in DOM
	if(!$('sidebarFaveCinemas')) {
		cinemaListNode = document.createElement('ul');
		cinemaListNodeId = document.createAttribute('id');
		cinemaListNodeId.value = "sidebarFaveCinemas";
		cinemaListNode.setAttributeNode(cinemaListNodeId);
		$('showTimesFaveCinemas').appendChild(cinemaListNode);
	} 
	// fill <ul> node with <li>s
	$('sidebarFaveCinemas').innerHTML = sidebarCinemaList;

}

/* called from toggleFave() in cinema.js - checks to see if fave star icon clicked
	is in the sidebar; if so, remove the cinema <li>; if there are no fave cinemas,
	replace with fave cinemas instruction para */
function removeFaveFromSidebar(removeLink) {
	if(removeLink.parentNode.parentNode.id == 'sidebarFaveCinemas') {
		if(!getListOfCinemas()) {
			$('sidebarFaveCinemas').hide();
			$('chooseFavouriteCinemas').style.display = "block";
		} else {
			removeLink.parentNode.parentNode.removeChild(removeLink.parentNode);
		}
	}
}