// alert(window.location.hash);
var mistressesNamesFemale = ['Katie', 'Siobhan', 'Trudi', 'Jessica'];
var mistressesNamesMale1 = ['Richard', 'Dominic', 'Hari', 'Simon'];
var mistressesNames = ['Mark', 'Lucas', 'Dan', 'Tom'];

glow.ready(function() {
	/*
	All pages are numbered in groups
	p-grp-theme-000 	= home
	prg-grp-theme-111	= episodes (never used because this is APS (/programmes)
	prg-grp-theme-222	= the mistresses
	prg-grp-theme-333	= the men
	prg-grp-theme-444	= the tangled web
	prg-grp-theme-555	= dilemmas
	prg-grp-theme-666	= style files
	*/
	//if(glow.dom.get('.p-grp-theme-000').length>0)
	//	PageAction.Home(); // only needed for launch
	if(window.location.href.indexOf('mistresses/themistresses')>0&&glow.dom.get('.prg-grp-theme-222').length>0)
		PageAction.TheMistresses();
	else if(window.location.href.indexOf('mistresses/dilemmas')>0&&glow.dom.get('.prg-grp-theme-555').length>0)
		PageAction.Dilemmas();
})

var PageAction = function() {
	return {
		Home: function() {
			if(window.location.hash!=null&&window.location.hash.length>0)
			{
				var href = window.location.hash.replace('#','');
				var title = '';
				var aList = glow.dom.get('#blq-content #prg-wrapper-extra .p-grp .p-mod .promo a');
				for(var i=0; i<aList.length; i++) {
					if(glow.dom.get(aList[i]).attr("href").replace('#','')==href)
					{
						title = glow.dom.get(aList[i]).attr("title");
						PageAction.LoadHomeVideo(title,href);
					}
				}
			}
			
			if(glow.dom.get('body#prg-type-index')!=null&&glow.dom.get('body#prg-type-index').length>0)
			{
				var aList = glow.dom.get('#blq-content #prg-wrapper-extra .p-grp .p-mod .promo a');
				
				for(var i=0; i<aList.length; i++) {
					glow.events.addListener(
						aList[i],
						'click',
						function(e) {
							var href = '';
							var title = '';
							try {
								href = glow.dom.get(e.source).attr("href");
								title = glow.dom.get(e.source).attr("title");
							} 
							catch(error) {}
							
							if(href==null||href=='') {
								href = glow.dom.get(e.source.parentNode).attr("href");
								title = glow.dom.get(e.source.parentNode).attr("title");
							}
							href = href.replace('#','');
							PageAction.LoadHomeVideo(title, href, "http://www.bbc.co.uk/mistresses","");
						}
					);
				}
			}
		},
		LoadHomeVideo: function(title, href) {
			glow.dom.get('#prg-wrapper-featured .prg-featured-lead .p-grp-theme-000 h2').html(title);
			empDivReady("512", "emp1", "black", href, "http://www.bbc.co.uk/mistresses","");
		},
		TheMistresses: function() {
			glow.dom.get('#prg-type-content #prg-wrapper-extra .prg-grp-theme-222 .vision-ratings-rating').css('display','inline');
			
			// CLEAR DEFAULT TEXT
			glow.dom.get('.vision-ratings-add .vision-ratings-prompt').html('');
			glow.dom.get('#prg-type-content #prg-wrapper-extra .prg-grp-theme-222 .vision-ratings-add .vision-ratings-prompt').css('display', 'inline');
			glow.dom.get('#prg-type-content #prg-wrapper-extra .prg-grp-theme-222 .vision-ratings-add div.jsrate').css('display', 'inline');
			
			// VOTING
			var starset = glow.dom.get('#ratingArea-0 .jsrate a');
			
			for(var i=0; i<starset.length; i++) {
				var star = starset[i];
				glow.dom.get(star).attr("class", "votelink votelink"+i);
				glow.dom.get(star).attr("title", mistressesNames[i]);
				glow.dom.get(star).append(glow.dom.create('<span>'+mistressesNames[i]+'</span>'));
			}
			
			/*
			var voteHolderOptions = glow.dom.get('#ratingArea-0 #extendedVoteHolder a');
			for(var i=0; i<voteHolderOptions.length; i++) {
				glow.events.addListener(
					voteHolderOptions[i],
					'click',
					function(e) {
						var href = '';
						var title = '';
						try {
							href = glow.dom.get(e.source).attr("href");
							title = glow.dom.get(e.source).attr("title");
						} 
						catch(error) {}
						
						if(href==null||href=='') {
							href = glow.dom.get(e.source.parentNode).attr("href");
							title = glow.dom.get(e.source.parentNode).attr("title");
						}
						href = href.replace('#','');
						
						return vision.ratings.rater.chooseAction('ratingArea-0',parseInt(href));
					}
				);
			}
			*/
			
			vision.ratings.onSubmit = function(form) {
				setTimeout('PageAction.TheMistressesResults();',500);
			}
		},
		TheMistressesResults: function() {
			// RESULTS - get json data from queryengine
			var resultHolder = glow.dom.get('#visionapps_ratings_customview_results');
			
			// show certain div holders after having to hide them for IE.
			glow.dom.get('#visionapps_ratings_customview_results').css('display','inline');
			glow.dom.get('.vision-ratings-add h3').attr('style','display: inline;');
			
			var request = glow.net.get("/apps/ifl/mistresses/queryengine?&attrib_1=source&oper_1=eq&val_1_1="+vision_ratings_source, {
				onLoad: function(response) {
					var jsonresult = response.json();
					
					var poll_1_count = jsonresult.poll_1_count;
					var poll_2_count = jsonresult.poll_2_count;
					var poll_3_count = jsonresult.poll_3_count;
					var poll_4_count = jsonresult.poll_4_count;
					
					var hasResultsPub = false;
					
					try { 
						if(typeof(poll_1_count)!='undefined')
							hasResultsPub = true;
					} catch(e) { }
					
					var poll_count = parseInt(poll_1_count) + parseInt(poll_2_count) + parseInt(poll_3_count) + parseInt(poll_4_count);
					
					var poll_1_percent = Math.round((poll_1_count/poll_count)*100);
					var poll_2_percent = Math.round((poll_2_count/poll_count)*100);
					var poll_3_percent = Math.round((poll_3_count/poll_count)*100);
					var poll_4_percent = Math.round((poll_4_count/poll_count)*100);
					
					if(!hasResultsPub) {
						poll_1_count = 0;
						poll_2_count = 0;
						poll_3_count = 0;
						poll_4_count = 0;
						poll_1_percent = 0;
						poll_2_percent = 0;
						poll_3_percent = 0;
						poll_4_percent = 0;
					}
					
					var htmlResult = '';
					var p = 0;
					var votePluralSing1 = (poll_1_count==1)?"vote":"votes";
					var votePluralSing2 = (poll_2_count==1)?"vote":"votes";
					var votePluralSing3 = (poll_3_count==1)?"vote":"votes";
					var votePluralSing4 = (poll_4_count==1)?"vote":"votes";

					p = (poll_1_percent*1.8)+1;
					htmlResult += '<div class="visappsratings_barholder visappsratings_barholder0" title="'+mistressesNames[0]+'"><div class="visappsratings_voteResultBarHolder"><div id="visappsratings_bar1" class="visappsratings_bar" style="width: '+p+'px;" title="'+poll_1_count+' '+votePluralSing1+'">'+mistressesNames[0]+'</div></div></div>';
					p = (poll_2_percent*1.8)+1;
					htmlResult += '<div class="visappsratings_barholder visappsratings_barholder1" title="'+mistressesNames[1]+'"><div class="visappsratings_voteResultBarHolder"><div id="visappsratings_bar2" class="visappsratings_bar" style="width: '+p+'px;" title="'+poll_2_count+' '+votePluralSing2+'">'+mistressesNames[1]+'</div></div></div>';
					p = (poll_3_percent*1.8)+1;
					htmlResult += '<div class="visappsratings_barholder visappsratings_barholder2" title="'+mistressesNames[2]+'"><div class="visappsratings_voteResultBarHolder"><div id="visappsratings_bar3" class="visappsratings_bar" style="width: '+p+'px;" title="'+poll_3_count+' '+votePluralSing3+'">'+mistressesNames[2]+'</div></div></div>';
					p = (poll_4_percent*1.8)+1;
					htmlResult += '<div class="visappsratings_barholder visappsratings_barholder3" title="'+mistressesNames[3]+'"><div class="visappsratings_voteResultBarHolder"><div id="visappsratings_bar4" class="visappsratings_bar" style="width: '+p+'px;" title="'+poll_4_count+' '+votePluralSing4+'">'+mistressesNames[3]+'</div></div></div>';
					htmlResult += '';

					/* not supported yet
					var a1 = glow.anim.css("#visappsratings_bar1", 5, { "width": {from: "0px", to: "100px"} }, { tween: glow.tweens.easeBoth() });
					a1.start();
					*/

					
					if(resultHolder!=null)
						resultHolder.html(htmlResult);
				},
				onError: function(response) {
					//alert("Error getting file: " + response.statusText());
				}
			});	
		},
		Dilemmas: function() {
			var js_vision_ratings_source = vision_ratings_source_docurl;
				
			// prep the string
			js_vision_ratings_source = js_vision_ratings_source.replace('/mistresses/','');
			js_vision_ratings_source = js_vision_ratings_source.replace('/','_');
			js_vision_ratings_source = js_vision_ratings_source.replace('.shtml','');
			
			// if this is blank then we're not on the index page and need to build the js source version from js variable 'vision_ratings_source_docurl' like so:
			// based on url - if the url is "/mistresses/dilemmas/dilemma1.shtml"
			// then the js version will be dilemma_dilemma1 (remove '/mistresses', slashes and .shtml)
			var disagreeMsg = 'Definitely not!';
			var neutralMsg = '';
			var agreeMsg = 'Yes I would!';
			
			var previousChoice = CookieFunc.getKeyValueofCookie('dvl',  js_vision_ratings_source);
			if(previousChoice!=null&&previousChoice.length>0) {
				glow.dom.get('.vision-ratings-add').css('display','none');
				var previousChoiceVoteBar = PageAction.DilemmaPreviousChoiceHtml(previousChoice);
				glow.dom.create('<div class="vision-ratings-previous vision-ratings-rank"><h3>Your previous vote</h3>'+previousChoiceVoteBar+'</div>').insertBefore('.vision-ratings-add');
				glow.dom.get('.vision-ratings-previous').after(glow.dom.create('<div class="opinionlegend" id="opinionlegendadd"><div class="disagree">'+disagreeMsg+'</div><div class="neutral">'+neutralMsg+'</div><div class="agree">'+agreeMsg+'</div></div>'));
			} else {				
				vision.ratings.onSubmit = function(form) {
					glow.dom.get('#opinionlegendadd').remove();
					
					var choice = glow.dom.get(form).val()['choice'];
					var previousChoice = CookieFunc.getKeyValueofCookie('dvl',  js_vision_ratings_source);
					if(previousChoice!=null&&previousChoice.length>0)
						alert('You\'ve already chosen an option: '+previousChoice); // this won't ever appear anyway
					else {
						CookieFunc.addKeyValuetoCookie('dvl', js_vision_ratings_source, choice);
					}
				}
				glow.dom.get('.vision-ratings-add').after(glow.dom.create('<div class="opinionlegend" id="opinionlegendadd"><div class="disagree">'+disagreeMsg+'</div><div class="neutral">'+neutralMsg+'</div><div class="agree">'+agreeMsg+'</div></div>'));
			}
			
			glow.dom.get('.vision-ratings-prompt').html('');
			glow.dom.get('.vision-ratings-prompt').css('display', 'inline');
			if(glow.dom.get('.vision-ratings-view p.notfound').length<1)
				glow.dom.get('.vision-ratings-view').after(glow.dom.create('<div class="opinionlegend" id="opinionlegendview"><div class="disagree">'+disagreeMsg+'</div><div class="neutral">'+neutralMsg+'</div><div class="agree">'+agreeMsg+'</div></div>'));
		},
		DilemmaPreviousChoiceHtml: function(previousChoice) {
			var result = '';
			var maxchoice = 5;
			if(previousChoice!=null&&parseInt(previousChoice)>0)
			{
				result += '<ul id="vision-ratings-jsranked-00">';
				
				for(var i=0; i<maxchoice; i++) {
					result += '<li id="0-'+i+'">';
					if(previousChoice<=i) {
						result += '<span class="vision-ratings-star off" title="'+previousChoice+' out of '+maxchoice+'">';
						result += '<span class="offscreen">'+i+'</span>';
					}
					else {
						result += '<span class="vision-ratings-star" title="'+previousChoice+' out of '+maxchoice+'">';
						result += '<span class="offscreen">-</span>';
					}
					result += '</span>';
					result += '</li>';
				}
				result += '</ul>';
			}
			
			return result;
		}
	}
}();

var CookieFunc = function() {
	/*
	Slightly restructured from http://www.quirksmode.org/js/cookies.html
	createCookie('ppkcookie','testcookie') - name,value
	*/
	return {
		createCookie: function(name, value) {
			// sets the expiry to the next monday at 5pm
			var date = new Date();
			var currentDay = parseInt(date.getDay()); // 0 = Sunday
			var currentTime = date.getTime(); // not date.getTime()
			var dayOffset = (7-currentDay)+1; // +1 to make it monday
			date.setTime(currentTime+(dayOffset*24*60*60*1000));
			var monthname = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
			var currentMonth = monthname[parseInt(date.getMonth())];
			var date2 = new Date(currentMonth+' '+date.getDate()+', '+date.getFullYear()+' 17:00:00');
			//alert(date2.toGMTString());
			
			var expires = "; expires="+date2.toGMTString();
			document.cookie = name+"="+value+expires+"; path=/";
		},
		readCookie: function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		},
		// assumes that the cookie is built up like a url - key1=value1&key2=value2 etc.
		// getKeyValueofCookie('dvl','key1') would return string 'value1';
		// returns '' if key doesn't exist
		getKeyValueofCookie: function(cookiename, key) {
			var result = '';
			
			var cookiedata = CookieFunc.readCookie(cookiename);
			if(cookiedata!=null&&cookiedata.length>0)
			{	
				if(cookiedata.indexOf('&')>-1)
				{
					var cookieArray = new Array();
					cookieArray = cookiedata.split('&');
					for(var i=0; i<cookieArray.length; i++) {
						var cookieEntry = cookieArray[i];
						var cookieEntryArray = new Array();
						cookieEntryArray = cookieEntry.split('=');
						
						if(cookieEntryArray.length>0)
						{
							if(cookieEntryArray[0]==key)
							{
								if(cookieEntryArray[1]!=null&&cookieEntryArray[1].length>0)
									result = cookieEntryArray[1];
							}
						}
					}
				}
				else if(cookiedata.indexOf('=')>-1)
				{
					var cookieEntryArray = new Array();
					cookieEntryArray = cookiedata.split('=');
					
					if(cookieEntryArray.length>0)
					{
						if(cookieEntryArray[0]==key)
						{
							if(cookieEntryArray[1]!=null&&cookieEntryArray[1].length>0)
								result = cookieEntryArray[1];
						}
					}
				}
			}
			
			return result;
		},
		addKeyValuetoCookie: function(cookiename, key, value) {
			CookieFunc.addKeyValuetoCookie(cookiename, key, value, false);
		},
		// first of all checks to see if the key already exists, if it does then ammends the value of that key (if forceOverwrite is true), if it doesn't then creates the key value pair inside the cookie
		// syntax addKeyValuetoCookie('dvl', 'key1', 'value1')
		addKeyValuetoCookie: function(cookiename, key, value, forceOverwrite) {
			var previousChoice = CookieFunc.getKeyValueofCookie(cookiename, key);
			if(forceOverwrite||(previousChoice==null||previousChoice.length<1)) // only add key value combo if the key hasn't already been added
			{
				var originalcookie = CookieFunc.readCookie(cookiename); // read cookie details
				var cookiecookie = '';
				
				var valyou = key+'='+value+'&';
				// valyou might typically look like - dilemmas_dilemma1=4&dilemmas_dilemma2=1
				
				if(originalcookie!=null&&originalcookie.length>0)
				{
					if(originalcookie.indexOf('&')>-1)
					{
						var cookieArray = new Array();
						var currentIdExistInLoop = false;
						cookieArray = originalcookie.split('&');
						for(var i=0; i<cookieArray.length; i++) {
							var cookieEntry = cookieArray[i];
							if(cookieEntry!=null&&cookieEntry.length>0) {
								var cookieEntryArray = new Array();
								cookieEntryArray = cookieEntry.split('=');
								
								if(cookieEntryArray[0]==key) {
									if(forceOverwrite)
										cookiecookie+=cookieEntryArray[0]+'='+value+'&';
									else
										cookiecookie+=cookieEntryArray[0]+'='+cookieEntryArray[1]+'&';
										
									currentIdExistInLoop = true;
								}
								else
									cookiecookie+=cookieEntryArray[0]+'='+cookieEntryArray[1]+'&';
							}
						}
						if(!currentIdExistInLoop)
							cookiecookie+=key+'='+value+'&';
					}
					else // else compare to see if this id = value of cookie
					{
						if(originalcookie.indexOf('=')>-1) {
							var cookieEntryArray = new Array();
							cookieEntryArray = cookieEntry.split('=');
							
							if(cookieArray[0]!=key)
								cookiecookie+=key+'='+value+'&';
						}
					}
				
					if(originalcookie!=cookiecookie) // Finally, if there are any changes then update with the new data
					{
						CookieFunc.eraseCookie(cookiename);
						CookieFunc.createCookie(cookiename,cookiecookie,28); // read back updated cookie details
					}
				}
				else
					CookieFunc.createCookie(cookiename,valyou,28);
			}
		},
		eraseCookie: function(name) {
			var date = new Date();
			date.setTime(date.getTime()+(-1*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
			document.cookie = name+"="+expires+"; path=/";
		}
	}
}();