allDays = new Array('dayFirst','daySecond','dayThird','dayFourth','dayFifth','daySixth','daySeventh');
//cinemaCookie = "bpme_favecinemas";
cinemaCookie = "bpme_cinemas_fave";

// switch which day's showtimes are shown
function changeDay(newDayLink){
	newDayListItem = newDayLink.parentNode;
	for (i=0; i<7;i++) {
		if (newDayListItem.id == allDays[i]) {
			//alert(newDayListItem + ' : '+ i );
			dayOffset = i;
			newDayListItem.className = "daySelected";
		} else {
			document.getElementById(allDays[i]).className = "";
		}
}
	writeCookie("bpme_cinema_date","dayoffset",dayOffset)
	displayVenues(displayType)
}

// this function handles instances where a search returns no sessions
function noSessionsFound(){
	alert('No sessions found for this day - you could try another day or location and search again');
	for (i=0; i<7;i++){
		if(i == 0){
			document.getElementById(allDays[i]).className = "daySelected";
		} else {
			document.getElementById(allDays[i]).className = "";
		}
	}	
	writeCookie("bpme_cinema_date","dayoffset",0)
	displayVenues(displayType)
}

// collapse/expand films and times showing at different cinemas
function toggleWhatsOn(listings){
	listings.parentNode.className = (listings.parentNode.className == "cinemaExpanded") ? "" : "cinemaExpanded";
}

// toggle favourites icon on/off and update cookie
function toggleFave(thisLink,initialiseStars) {
	// retrieve the cinema's name
	if(!initialiseStars) {
		for(i=0;i<thisLink.parentNode.getElementsByTagName('a').length;i++) {
			if (thisLink.parentNode.getElementsByTagName('a')[i].className == "cinemaName") cinemaName = thisLink.parentNode.getElementsByTagName('a')[i].innerHTML;
		}
	}
	// if it's already a favourite, swap it out and remove from the fave cinemas cookie
	if(thisLink.className == "isFavourite"){
		deleteFaveCinema(cinemaName);		
		//checks to see if this is removing from sidebar - fn in cinemasearch.js
		removeFaveFromSidebar(thisLink);
		thisLink.className = "isntFavourite";
		thisLink.innerHTML = "<div><span>Make this a favourite cinema</span></div>";

	} else {
	// otherwise make it a favourite and add to cookie (unless this is called by updateFaveCinemaStars to set all faves to starred onload)
	//if(!initialiseStars) addFaveCinema(cinemaName); 
		if(!initialiseStars) addFaveCinema(cinemaName,stateName,cityName,regionName,regionChosen)
		thisLink.className = "isFavourite";
		thisLink.innerHTML = "<div><span>Remove from favourites</span></div>";
	}
}

// on page load, show all favourite cinemas as starred.
function updateFaveCinemaStars(){
	resultsArray = new Array()
	for(i=0;i<document.links.length;i++){
		// if cookie exists AND link classname = isntFavourite (ie a cinema link) AND cookiestring contains link text THEN add to results array
		if(getCookie(cinemaCookie) && document.links[i].className == "isntFavourite" && unescape(getCookie(cinemaCookie)).indexOf(document.links[i].parentNode.getElementsByTagName('a')[1].innerHTML) !=-1) {
		 resultsArray[resultsArray.length] = i;
		}
	}
	// toggle all resulting links, nb initialiseStars var is set to 1 so these aren't re-added to cookie in toggleFave()
	for(i=0;i<resultsArray.length;i++){
		toggleFave(document.links[resultsArray[i]],1);
	}
}

function writeCookie(cookieName, cookieParam, cookieValue) {
	if(getCookie(cookieName)) {
		cookieUpdated = false; // set flag
		cookieString = unescape(getCookie(cookieName)).substring(cookieName.length+1); // remove cookie name from front of cookie
		cookieContentPairs = cookieString.split('&'); // pull cookie contents into content/value pairs array

		newCookiePairs = new Array();
		
		//loop through content/value pairs looking for cookieParam, replace cookieValue if necessary
		for(i=0;i<cookieContentPairs.length;i++){
//				console.log(cookieContentPairs[i]);
			if(cookieContentPairs[i].split('=')[0] == cookieParam) {
				newCookiePairs[i] = cookieParam + "=" + cookieValue;
				cookieUpdated = true;
			} else {
				newCookiePairs[i] = cookieContentPairs[i]
			}
		}
		

		newCookieString = "";
		for(i=0;i<cookieContentPairs.length;i++){ // put cookie pairs back together
			newCookieString += newCookiePairs[i] + "&";
			
		}
		if(!cookieUpdated) { // append new cookie pair to the end
			newCookieString += cookieParam + "=" + cookieValue //+ "&";
		}
/*		if(newCookieString.charAt(newCookieString.length-1) == "&") {
			newCookieString = newCookieString.substring(0,newCookieString.length-1);
		}*/
		setCookie(cookieName,newCookieString)
	} else { // no cookies exist, just write new cookie
		setCookie(cookieName,cookieParam+"="+cookieValue)
	}
}

function setCookie(cookieName, cookieString) {
	years = 365 * 3 // 3 years
	pathString =  ";path=/;"
	expireString = ";expires="+new Date((new Date()).getTime() + years * 86400000).toGMTString();
	if(cookieString.charAt(cookieString.length-1) == "&") {
		cookieString = cookieString.substring(0,cookieString.length-1);
	}
	document.cookie = cookieName + "=" + escape(cookieString) + expireString + pathString;
}

/* temp cookie writer with date preset - temp until rewritten with a duration paramater */
function writeCookie2(cookieName, cookieParam, cookieValue) {
	if(getCookie(cookieName)) {
		cookieUpdated = false; // set flag
		cookieString = unescape(getCookie(cookieName)).substring(cookieName.length+1); // remove cookie name from front of cookie
		cookieContentPairs = cookieString.split('&'); // pull cookie contents into content/value pairs array

		newCookiePairs = new Array();
		
		//loop through content/value pairs looking for cookieParam, replace cookieValue if necessary
		for(i=0;i<cookieContentPairs.length;i++){
			if(cookieContentPairs[i].split('=')[0] == cookieParam) {
				newCookiePairs[i] = cookieParam + "=" + cookieValue;
				cookieUpdated = true;
			} else {
				newCookiePairs[i] = cookieContentPairs[i]
			}
		}

		newCookieString = "";
		for(i=0;i<cookieContentPairs.length;i++){ // put cookie pairs back together
			newCookieString += newCookiePairs[i] + "&";			
		}
		if(!cookieUpdated) { // append new cookie pair to the end
			newCookieString += cookieParam + "=" + cookieValue //+ "&";
		}
		setCookie2(cookieName,newCookieString)
	} else { // no cookies exist, just write new cookie
		setCookie2(cookieName,cookieParam+"="+cookieValue)
	}
}
function setCookie2(cookieName, cookieString) {
	msDuration = 1000 * 60 * 10 //duration is in millisections. 1000 x 60 x 10 = 10 minutes
	pathString =  ";path=/;"
	expireString = ";expires="+new Date((new Date()).getTime() + msDuration).toGMTString();
	if(cookieString.charAt(cookieString.length-1) == "&") {
		cookieString = cookieString.substring(0,cookieString.length-1);
	}
	document.cookie = cookieName + "=" + escape(cookieString) + expireString + pathString;
}

function resetDateCookie() {
	//reset the day offset to default value of 0 (today)	
	writeCookie2("bpme_cinema_date","dayoffset","0");
}
function resetRegionCookie(newState,newCity,newRegion,newRegionid) {
	//reset the region id to that of the just-clicked favourite cinema
	writeCookie("bpme_cinema_location","state",newState)
	writeCookie("bpme_cinema_location","city",newCity)
	writeCookie("bpme_cinema_location","region",newRegion)
	writeCookie("bpme_cinema_location","regionid",newRegionid);
}


/* old function
function addFaveCinema(cinemaName){
	// add cinema unless cookie string exists and cinema name is in the cookie string
	if(!(getCookie(cinemaCookie) && unescape(getCookie(cinemaCookie)).indexOf(cinemaName) != -1)) {
		cinemaString = unescape(getCookie(cinemaCookie)).substring(cinemaCookie.length+1);
		cinemaString += (cinemaString == "") ? cinemaName : "&" + cinemaName;
		setCookie(cinemaCookie, cinemaString);
	}
}
*/
function addFaveCinema(cinemaName,newState,newCity,newRegion,newRegionid){
	//alert(cinemaName+stateChosen+cityChosen+regionChosen+regionidChosen);
	// add cinema unless cookie string exists and cinema name is in the cookie string
	var checkCookie = 0;
	if(getCookie(cinemaCookie)){ 
		for(i=0;i<getListOfCinemas().length;i++){
			if(unescape(getListOfCinemas()[i]).split('~')[0] == cinemaName){
				//cookie already exists
				checkCookie = 1;
			}
		}
	}
	if(checkCookie == 0){
		cinemaString = unescape(getCookie(cinemaCookie)).substring(cinemaCookie.length+1);
		cinemaString += (cinemaString == "") ? cinemaName +"~" + newState +"~" + newCity +"~" + newRegion +"~" + newRegionid : "&" + cinemaName +"~" + newState +"~" + newCity +"~" + newRegion +"~" + newRegionid;
		setCookie(cinemaCookie, cinemaString);
	}
}


function deleteFaveCinema(cinemaName) {
//function deleteFaveCinema(cinemaName,newState,newCity,newRegion,newRegionid){
	// if cinema cookie exists and cinema name is found in the cookie string
	//if(getCookie(cinemaCookie) && unescape(getCookie(cinemaCookie)).indexOf(cinemaName) != -1) {
	if(getCookie(cinemaCookie)) {
		cinemaStringMinusDeletedCinema = ""
		//loop through cinema list, create new cookiestring with all cinemas except one to be deleted
		for(i=0;i<getListOfCinemas().length;i++){
			if(unescape(getListOfCinemas()[i]).split('~')[0] != cinemaName){
				cinemaStringMinusDeletedCinema += getListOfCinemas()[i] +"&";
			}				
				//if(getListOfCinemas()[i])					
				//cinemaStringMinusDeletedCinema += (getListOfCinemas()[i] != cinemaName && getListOfCinemas()[i]!="") ? getListOfCinemas()[i] +"&": "";
			//}
			setCookie(cinemaCookie,cinemaStringMinusDeletedCinema)
		}
	}
}

function getListOfCinemas() {
/*returns array of cinemas 
	first checks that document.cookie has the cinema cookie, and it's not just bpme_cinemas_fave= (18 chars)*/
	//return (document.cookie.indexOf(cinemaCookie) != -1 && unescape(getCookie(cinemaCookie)).length > 18) ? unescape(getCookie(cinemaCookie)).split('=')[1].split('&') : false;
	return (document.cookie.indexOf(cinemaCookie) != -1 && unescape(getCookie(cinemaCookie)).length > 18) ? unescape(getCookie(cinemaCookie)).split('=')[1].split('&') : false;
}

// fn returns cookie string from document.cookie
function getCookie(cookieName) {
	if(document.cookie.length > 0 && document.cookie.indexOf(cookieName)!=-1) { //if there are cookies in browser
	// work out where [cookieName] details are in this site's cookies	
//		cookieStringToEnd = document.cookie.substring(document.cookie.indexOf(cookieName+"="));
		cookieStringToEnd = document.cookie.substring(document.cookie.indexOf(cookieName));
		endOfThisCookie = (cookieStringToEnd.indexOf(';') > -1) ? cookieStringToEnd.indexOf(';') : cookieStringToEnd.length;
		return cookieStringToEnd.substring(0,endOfThisCookie);
	} else {
		return false;
	}
}
	  
// retrieves [parameter]'s value from [cookieName]
function findInCookie(cookieName,parameter) {
	resultsArray = new Array();
	cookieString = unescape(getCookie(cookieName)).substring(cookieName.length+1); // remove cookie name from front of cookie
	cookieContentPairs = cookieString.split('&');

	for(i=0;i<cookieContentPairs.length;i++) {
		if (cookieContentPairs[i].split('=')[0] == parameter) {
			resultsArray[resultsArray.length] = cookieContentPairs[i].split('=')[1];
		}
	}
	
	return (resultsArray.length>0) ? resultsArray[0] : 0;
}

function toggleShowtimes(toggleLink) {
	$('displayVenues').style.display = ($('displayVenues').style.display =='block') ? 'none' : 'block';
	toggleLink.innerHTML = ($('displayVenues').style.display =='block') ? "Click here to hide &raquo;" : "Click here to view &raquo;";
}

function changeLocation(changeLink) {
	if(changeLink.className == "CLopen") {
		changeLink.className = "";
		changeLink.innerHTML = "Change this location";
		$('changeLocation').style.display = "none";
	} else {
		changeLink.className = "CLopen";
		if($('selState2').options.length < 2) populateStates(2);
		changeLink.innerHTML = "Close this";
		$('changeLocation').style.display = "block";
}
}

//window.onload = updateFaveCinemaStars;	//moved to cinemavenues.js