﻿/*SIFR*/

var thisHost = "";
var myDomain = document.domain;

if (myDomain == "wpp-sr.reports.addison.co.uk") {
	var thisHost = "/assets/wpp-sr.reports.addison.co.uk";
}
else if (myDomain == "exports.reports.addison.co.uk") {
	var thisHost = "/wpp-sr.reports.addison.co.uk";
}
else if (myDomain == "prototype.addison.co.uk") {
	var thisHost = "/wppcr";
}
else {
    var thisHost = "/corporateresponsibilityreports/2009";
}


var wpp = { src: thisHost + '/sifr/sifr.swf' };

sIFR.activate(wpp);

sIFR.replace(wpp, {
	selector: '.what-were-thinking #left_panel h1',
	css: '.sIFR-root { color: #B14C71;width: 100px;background: transparent; letter-spacing: -1; }',
	wmode: 'transparent'
});
sIFR.replace(wpp, {
	selector: '.forward-uk-tesco #left_panel h1, .g2-mexico-diageo #left_panel h1, .ogilvy-mumbai-vodafone-india #left_panel h1, .rkcryr-uk-marks--spencer-plan-a #left_panel h1, .mec-london-the-uk-department-of-health #left_panel h1, .tns-social-uk-nhs---hull-primary-care-trust #left_panel h1, .yr-buenos-aires-unhcr #left_panel h1, .cohn--wolfe-and-zaaz-us-toms-of-maine #left_panel h1, .ogilvyaction-denmark-kraft #left_panel h1',
	css: '.sIFR-root { color: #A4B2D8;width: 100px;background: transparent; letter-spacing: -1; }',
	wmode: 'transparent'
});
sIFR.replace(wpp, {
	selector: '.case-studies #left_panel h1',
	css: '.sIFR-root { color: #E094BE;width: 100px;background: transparent; letter-spacing: -1; }',
	wmode: 'transparent'
});
sIFR.replace(wpp, {
	selector: '#left_panel h1',
	css: '.sIFR-root { color: #000000;width: 100px;background: transparent; letter-spacing: -1; }',
	wmode: 'transparent'
});


/*
Javascript code supporting ajax functionalities.
*/

var NotesCookie = false;
var PrintCartCookie = false;
var LinkCartCookie = false;
var dldInProgress = false;
var basepath = '/';
var notesUrl = "";
var printUrl = "";
var LinksUrl = "";
var mailerUrl = "";
var feedbackUrl = "";
var downloadsUrl = "";
var exitUrl = "";
var options = false;


function establishPgId() {

	return getPageFromLink('#functionality ul li a.second');
}

function isInCart() {
	var value = PrintCartCookie;
	return (value != null && (',' + value + ',').indexOf(',' + establishPgId() + ',') > -1);
}

function setCartPageStatus() {
	if (isInCart()) {
		$('a#printbasket').parents("li:first").find("a:first").hide();
		$('a#printbasket').parents("li:first").find("em:first").hide();
		$('a#printbasket').parents("li:first").find("span:first").hide();
		$('a#printbasket').next().next().addClass("second");
	}
}

function getPageFromLink(link) {
	var pg = $(link).attr('href');
	var rg = new RegExp("pg\\d+");
	var res = rg.exec(pg);
	if (res != null) return res[0];
	else return 0;
}
function displayPopup(customClass) {
	$('body').append('<div id="dialog" class="jqmWindow ' + customClass + ' "><a class="close" style="float:right;" href="#null"><span>Close</span></a><div class="content"></div><div id="splash"><h2>Processing...</h2><img src="' + basepath + 'images/loading.gif" /></div></div>');
	$('#dialog').jqm({ onShow: showEvent, modal: true }).jqmShow();
	$('div.jqmOverlay').click(function() { ClosePopup(); });
	$('.close').click(function() { ClosePopup(); });
}
function showEvent(hash) {
	SetSplashStatus(true);
	hash.w.show();
	$.get(options['url'], options['params'], function(data) {
		loadEvent(data);
	}
	);
}
function loadEvent(data) {
	$('#dialog > div.content').html(data);
	SetSplashStatus(false);
	if (options['CancelAction']) {
		$(options['CancelAction']).click(function() {
			ClosePopup();
			return false;
		});
		$(options['CancelAction']).show();
	}
	if (options['DoAction']) {
		$(options['DoAction']).click(submitEvent);
	}

	if (options['loadCallback']) {
		options['loadCallback']();
	}
}

function submitEvent(data) {
	SetSplashStatus(true);
	var fields = $('#dialog > div.content').find(":input");
	var inputs = getAjaxFormFields(fields);
	$.get(options['url'], inputs, function(data) {
		if (options['submitCallback'] != null)
			options['submitCallback']();
		else
			loadEvent(data);
	});
	return false;
}
function ClosePopup() {
	$('#dialog').jqmHide();
	$('#dialog').remove();
}

function getAjaxFormFields(fields) {
	var inputs = new Object();
	inputs['ajax'] = 1;
	for (i = 0; i < fields.length; i++) {
		if (fields[i].name != '') {
			if ((fields[i].type == 'radio' || fields[i].type == 'checkbox')) {
				if (fields[i].checked) inputs[fields[i].name] = fields[i].value;
			}
			else
				inputs[fields[i].name] = fields[i].value;
		}
	}
	return inputs;
}

function SetSplashStatus(visible) {
	if (visible) {
		$('#splash').show();
		$('#dialog > div.content').hide();
	}
	else {
		$('#splash').hide();
		$('#dialog > div.content').show();
	}
}

/*Homepage flash functions*/



$(document).ready(function() {
	$("#search").click(function() { $(this).attr({ value: '' }); });


	/*Code for report tools begins*/
	basepath = $('#heading a').attr('href').replace('index.html', '');


	//define urls
	printUrl = basepath + 'scripts/print.aspx';
	mailerUrl = basepath + 'scripts/email.aspx';


	exitUrl = basepath + 'scripts/exit.aspx';
	feedbackUrl = basepath + 'scripts/feedback.aspx';
	shareUrl = basepath + 'scripts/share.aspx';
	noteUrl = basepath + 'scripts/notepad.aspx';

	$('#print_all').click(function() {
		$('input.' + $(this).attr('class')).attr('checked', $(this).attr('checked'));
	});
	$('#delete_all').click(function() {
		$('input.' + $(this).attr('class')).attr('checked', $(this).attr('checked'));
	});
	$('#email_all').click(function() {
		$('input.' + $(this).attr('class')).attr('checked', $(this).attr('checked'));
	});

	//don't think this is used - the print button is an input, not an anchor - Ireo
	$('a.printButton').click(function() {
		window.print();
	});
	var rdn = Math.floor(Math.random() * 2000);
	
	//PrintCartCookie = $.ajax({ type: 'GET', url: printUrl, async: false, data: { ajax: 1, ajxcmd: 'getcookie', tst: rdn }, dataType: 'text' }).responseText;

	//this allows the print page to open in a new window 
	//- a page called printview.html which draws its content from the sitemap accordingto page no.s passed in as parameters - eg printview.html?print=pg12345-pg12346
	//to go back to the default practice (opening the print page inthe same window) just comment out this function
	$('input.btnPrint').click(function() {
		
					//get the list of pages to be printed (ie check boxes checked), in the format '-21572-21574' etc
					//we identify them by the checkboxes in the print page - they have class 'sa01'
					
					var pagesToPrint = "";
					$("input.sa01").each(function() {
																	  
							var child = $(this);
							if (child.attr('checked') != "") pagesToPrint += "-"+child.attr("value").substring(2); 	//the substring(2) bit gets rid of a 'pg' prefix
								
					});
					
										
					//if there are no pages selected, do nothing
					if (pagesToPrint == "") return false;
						
					//get rid of the first hyphen - so we have something like 'pg12345-pg12346'.
					//So, on the server page, we can split this string into an array
					pagesToPrint = pagesToPrint.substring(1);
					
					//so the link is like this: scripts/printview.html?print=pg12345-pg12346
					var printViewUrl = basepath + 'scripts/printview.html';
					
					var link = printViewUrl + "?print=" + pagesToPrint;
					
					window.open(link);

					return false;
				
	});


	//---------keypress events for AAA compliance

	//on the note form, Enter submits and Esc clears the form
	//the form is loaded via AJAX, so we need to use .live
	$('#ctl00_phContent_Notepad_txNote').live('keypress', function(event) {

	    if (event.keyCode == '13') {
	        $('#ctl00_phContent_Notepad_btnAdd').click();
	        return false;
	    }

	    if (event.keyCode == '27') {
	        $('#ctl00_phContent_Notepad_btnCancelNote').click();
	        return false;
	    }

	});

	//now the same for the email form - and also comments, which has the same button ids
	$('#ctl00_phContent_fromName, #ctl00_phContent_toName, #ctl00_phContent_toEmail, #ctl00_phContent_message, #ctl00_phContent_frmCode, #ctl00_phContent_comments, #ctl00_phContent_frmCode').live('keypress', function(event) {

	    if (event.keyCode == '13') {

	        $('#ctl00_phContent_btnSend').click();
	        return false;
	    }

	    if (event.keyCode == '27') {

	        $('#CancelSend').click();
	        return false;
	    }

	});

	//and also for teh Email Notes form controls / buttons
	$('#ctl00_phContent_Notepad_sname, #ctl00_phContent_Notepad_semail, #ctl00_phContent_Notepad_frmCode').live('keypress', function(event) {

	    if (event.keyCode == '13') {

	        $('#ctl00_phContent_Notepad_btnSend').click();
	        return false;
	    }

	    if (event.keyCode == '27') {

	        $('#ctl00_phContent_Notepad_btnCancel').click();
	        return false;
	    }

	});


	$('#functionality li a.email').click(function() {
		var rdn = Math.floor(Math.random() * 2000);
		//options = {url: mailerUrl,params: {pg:getPageFromLink('#functionality li a.email'),ajax:1},CancelAction: '.CancelSend',DoAction: '.ActionSend'};
		options = { url: mailerUrl, params: { ajax: 1, tst: rdn, pg: getPageFromLink('#functionality li a.email') }, CancelAction: '.CancelSend', DoAction: '.ActionSend' };
		displayPopup('email');
		return false;
	});
	var ClosePopupAction = function() {
		ClosePopup();
	}
	$('#functionality li a.noteAdd').click(function() {
		var rdn = Math.floor(Math.random() * 2000);
		//options = {url: mailerUrl,params: {pg:getPageFromLink('#functionality li a.email'),ajax:1},CancelAction: '.CancelSend',DoAction: '.ActionSend'};
		options = { url: noteUrl, params: { ajax: 1, tst: rdn, add: getPageFromLink('#functionality li a.email') }, CancelAction: '.CancelNote', DoAction: '.SaveNote', submitCallback: ClosePopupAction };
		displayPopup('notes');
		return false;
	});

	$('#functionality li a.share').click(function() {
		options = { url: shareUrl, params: { ajax: 1, pg: getPageFromLink('#functionality li a.share'), window: 'share' }, CancelAction: '.CancelSend', DoAction: '.ActionSend' };
		displayPopup('shareModal');
		return false;
	});

	$('li.feedback a').click(function() {
		var rdn = Math.floor(Math.random() * 2000);
		options = { url: feedbackUrl, params: { ajax: 1, tst: rdn }, CancelAction: '.CancelSend', DoAction: '.ActionSend' };
		displayPopup('feedbackModal');
		return false;
	});


	$('a.external').click(function() {
		var surl = (this.href.indexOf('url=') > 0) ? this.href.substring(this.href.indexOf('url=') + 4) : this.href;
		options = { url: exitUrl, params: { url: surl }, CancelAction: '.CancelExit' };
		displayPopup();
		return false;
	});


	// Cookie js finds if persistent cookies are enabled
	setCartPageStatus();
	/*Code for report tools ends*/



	//ADDISON DEFAULT ACCORDION
	if ($('#accordion').length != 0) {
		$('#accordion h2').next("div").each(function() {
			if ($('body').css('minWidth') == undefined) {
				$(this).attr("rel", $(this).height() + 30);
			} else {
				$(this).attr("rel", $(this).height());
			};
		});
		// Open first one
		//$('#accordion h3:first').addClass("ui-state-active").next('div');
		$('#accordion h2')//.not('#accordion h3:first')
		.each(function() {
			$(this).next("div").css("height", "0");
			$(this).next("div").addClass("closedAccordion");
		});
		$('#accordion h2').live("click", function() {
			accordion($(this), "#accordion h2", "", $('#accordion h2').index(this));
			activeAccSubSection = false;
			return false;
		});
	};
	// END ADDISON DEFAULT ACCORDION

	// variable for accordion section
	activeAccSubSection = false;
	// variable for accordiion subsection and anchor
	activeAccSubSectionAnchor = false;



	$('a.full').click(function() {
		window.open(this.href);
		return false;
	});

	// if back button rememberance go to that point in page
	if (location.hash) {

		// remove the # (the hash can container either a number or text)
		var activeAcc = (location.hash).replace('#', '');
		// test to find subsection anchor
		activeAccSubSectionTest = activeAcc.indexOf('=');
		activeAccSubSection = false;
		// if test is true
		if (activeAccSubSectionTest != '-1') {

			// split the varibale example 2(accordion sub section) and animal(anchor within subsection)
			activeAccSubSection = activeAcc.split('=', [2]);
			// place sub section accordion varibale within activeAcc
			activeAcc = activeAccSubSection[0];
		} else {

			// else test if activeAcc is either a number or text
			if (/^\d*$/.test(activeAcc)) {
				// if a number turn into a interger

				activeAcc = parseInt(activeAcc);
			} else {
				// else activeAcc is a text anchor
				activeAccSubSectionAnchor = activeAcc;
			}
		}
		activeAcc = parseInt(activeAcc);
		if (activeAccSubSectionAnchor) {
			// them scroll to anchor
			$(window).scrollTo($('#' + activeAccSubSectionAnchor), 800);
		} else {

			accordion($('#accordion h2').eq(activeAcc), "#accordion h2", "true", activeAcc);
		}
	}



	// Accordion function with options - pass in the object (Header) thats been clicked		
	function accordion(element, header, type, index) {
		$('#accordion h2').each(function() {
			if ($(this).hasClass('open')) {
				$(this).removeClass("open");
			}
		});
		var height = element.next("div").attr('rel');
		if (element.hasClass("ui-state-active")) {

			element.next("div").animate({
				height: "0"
			}, 500).addClass("closedAccordion").prev(header).removeClass("ui-state-active").removeClass('open');
		} else {
			element.next("div").animate({
				height: height
			}, 500, function() {
				if (type != 'false') {
					if (!activeAccSubSection) {
						$(window).scrollTo($(header).eq(index), 800);
					} else {
						$(window).scrollTo($('#' + activeAccSubSection[1]), 800);
					}
				}
			}).removeClass("closedAccordion").prev(header).addClass("ui-state-active").addClass('open');
		};
	};

	// End Accordion function with options - pass in the object (Header) thats been clicked


	$('#contentArea a').click(function() {
		theLink = false;
		theLink = $(this).attr('href');
		theLinkTest = theLink.indexOf('#');
		if (theLinkTest != '-1') {
			var splitHash = $(this).attr('href').split('#');
			// remove #
			var activeAcc = splitHash[1];
			// test to find subsection anchor
			activeAccSubSectionTest = activeAcc.indexOf('=');
			activeAccSubSection = false;
			// if test is true
			if (activeAccSubSectionTest != '-1') {
				// split the varibale example 2(accordion sub section) and animal(anchor within subsection)
				activeAccSubSection = activeAcc.split('=', [2]);
				// place sub section accordion varibale within activeAcc
				activeAcc = activeAccSubSection[0];
			}
			// test if activeAcc is either a number or text
			if (/^\d*$/.test(activeAcc)) {
				activeAcc = parseInt(activeAcc);
				$(window).scrollTo($('body'), 800, function() {
					// if a sub section with a anchor exist then scroll that anchor after accordion has opened correct section
					isclosed = $('#accordion h2').eq(activeAcc).next().hasClass('closedAccordion');
					if (activeAccSubSection) {
						if (isclosed) {
							accordion($('#accordion h2').eq(activeAcc), "#accordion h2", "true", activeAccSubSection[1]);
						} else {
							$(window).scrollTo($('#' + activeAccSubSection[1]), 800);
						}
					} else {
						// if no anchor within a sub section exist then scroll to open accordion
						if (isclosed) {
							accordion($('#accordion h2').eq(activeAcc), "#accordion h2", "true", activeAcc);
						} else {
							$(window).scrollTo($('#accordion h2').eq(activeAcc), 800);
						}
					}
				});
			} else {
				// if #hash change was for a anchor within already open accordion then just go the right anchor without any accodion effect 
				$(window).scrollTo($('#' + activeAcc), 800);
			}
		}
	});





	$('.charts img').mouseover(function() {
		var src = $(this).attr('src').replace('-sml', '');
		var x = $(this).offset().left;
		var y = $(this).offset().top;
		var width = $(this).width() / 4;
		var height = $(this).height() / 4;
		var x = x - width;
		var y = y - height;
		$('#container').prepend('<img class="chart-hover" src="' + src + '" />').children().css({ 'top': y, 'left': x });
		mouseOutCharts();
	});
	function mouseOutCharts() {
		$('.chart-hover').mouseout(function() {
			$(this).remove();
		});
	}





	$('.artist img').mouseover(function() {
		var src = $(this).attr('src').replace('-sml', '');
		var x = $(this).offset().left;
		var y = $(this).offset().top;
		var width = $(this).width() / 1.5;
		var height = $(this).height() / 1.5;
		var x = x - width;
		var y = y - height;
		$('.chart-hover').remove();
		$('#container').prepend('<img class="chart-hover" src="' + src + '" />').children().css({ 'top': y, 'left': x });
		mouseOutCharts();
	});


	function mouseOutCharts() {
		$('.chart-hover').mouseout(function() {
			$(this).remove();
		});
	}



	//ADD A BULLET TO LIST ITEMS THAT FALL OVER A DROPCAP
	$('.fauxBulletBlue').prepend('<span class="fauxBulletBlueBullet"></span>');
	$('.fauxBulletBlue').parent().css('margin-top', '0');




	//backtotops
	var mainHeight = $("#left_panel").height();
	if ((mainHeight >= 700) || ($('#accordion').length != 0)) {
		$('#left_panel').append('<p class="backtotop"><a href="#header">Back to top</a></p>');
	};


	//table row hover
	$("table tbody tr")
.mouseover(function() {
	$(this).addClass("rowhover");
}).mouseout(function() {
	$(this).removeClass("rowhover");
});



	//share popup
	$('#shareIt').hide();
	$('a#shareItLink').click(function() {
		$('#shareIt').show();
		return false;
	});
	$('#shareIt a.close').click(function() {
		$('#shareIt').hide();
		return false;
	});


	// case study scroll
	$('.case-studies-panel .right-col div').not(':first').hide();
	divLength = 0;
	thisPos=0;
	$('.case-studies-panel .right-col div').each(function(){
		divLength = divLength+1;
	});
	if(divLength>1){
		thisPos=0;
		t=setTimeout(animateCaseStudies,7000);
	}
	function animateCaseStudies(){
		$('#carouselNav li a').removeClass("currentItem");
		$('#carouselNav li a').eq(thisPos).addClass("currentItem");
		$('.case-studies-panel .right-col div:visible').fadeOut("slow",function(){
			$('.case-studies-panel .right-col div').eq(thisPos).fadeIn("slow");
		});
		thisPos=thisPos+1;
		if (thisPos==divLength){
			thisPos=0;
		};
		t=setTimeout(animateCaseStudies,7000);
	}

	// image scroll

	$('.switch div').not(':first').hide();
	divLength1 = 0;
	thisPos1=0;
	$('.switch div').each(function(){
		divLength1 = divLength1+1;
	});
	if(divLength1>1){
		thisPos1=0;
		t=setTimeout(animateSwitch,7000);
	}
	function animateSwitch(){
		$('#carouselNav li a').removeClass("currentItem");
		$('#carouselNav li a').eq(thisPos1).addClass("currentItem");
		$('.switch div:visible').fadeOut("slow",function(){
			$('.switch div').eq(thisPos1).fadeIn("slow");
		});
		thisPos1=thisPos1+1;
		if (thisPos1==divLength1){
			thisPos1=0;
		};
		t=setTimeout(animateSwitch,7000);
	}





	/*!video popups */


	$("#videoFile, #videoFile2").fancybox({
	    'padding'           : 0
	});


	$(".digitalvid").fancybox({
	    'padding'           : 0,
		'width'				: 560,
		'height'			: 315
	});

	$(".anadvid").fancybox({
	    'padding'           : 0,
		'width'				: 560,
		'height'			: 409
	});

	$(".uniceffvid").fancybox({
	    'padding'           : 0,
		'width'				: 560,
		'height'			: 448
	});

	$(".wildvid, .standvid, .wastevid, .bookvid, .ogilvyvid, .powervid").fancybox({
	    'padding'           : 0,
		'width'				: 560,
		'height'			: 420
	});

	$(".marksvid").fancybox({
	    'padding'           : 0,
		'width'				: 560,
		'height'			: 308
	});



/* text replacement */


	$('a[title*="RKCR/Y and R UK: Marks and Spencer Plan A"]').html('<span class="second">RKCR/Y&amp;R UK: Marks &amp; Spencer Plan A</span>');
	$('a[title*="Our companies and associates"]').html('<span class="second">Our companies &amp; associates</span>');
	$('a[title*="Cohn and Wolfe and ZAAZ US: Toms of Maine"]').html('<span class="second">Cohn and Wolfe &amp; ZAAZ US: Tom&#39;s of Maine</span>');
	$('a[title*="Y and R Buenos Aires: UNHCR"]').html('<span class="second">Y &amp; R Buenos Aires: UNHCR</span>');

	$('a[title*="Y and R Mumbai: Dakshta"]').html('<span class="second">Y&amp;R Mumbai: Dakshta</span>');
	$('a[title*="Y and R Johannesburg: UNICEF"]').html('<span class="second">Y&amp;R Johannesburg: UNICEF</span>');
	$('a[title*="Sudler and Hennessey Milan: San Patrignano"]').html('<span class="second">Sudler &amp; Hennessey Milan: San Patrignano</span>');
	$('a[title*="H and K Poland: The Womens Congress"]').html('<span class="second">H&amp;K Poland: The Women&#39;s Congress</span>');
	$('a[title*="O and M Frankfurt: ANAD"]').html('<span class="second">O&amp;M Frankfurt: ANAD</span>');
	
	$('h2.noteH1').replaceWith('<h1 class="popupTableWidth noteH1">Your notes</h1>');

});



	
	

