/***************************************************************************************************

THIS JAVASCRIPT IS NOT FIT FOR PRODUCTION - FOR USER TESTING ONLY!

The relevant features to implement in the live version are:

- Show/hide for comments (ndp.iniComments)

- Change URL when page number select box is changed on page detail screen (ndp.iniPages)

- Alert "please enter a search term" when submitting a blank search form (ndp.iniSearch)

- In the date picker, selecting a year enables the months - selecting a month enables the days (ndp.iniDatePicker)

- Show/hide for login and sign up forms (ndp.iniPopUp)

- Rolling over a line of text in the OCR makes the "Help fix this text!" button appear next to it (ndp.iniSync)

- Clicking a line of text syncronises the views (ndp.clickOCR)

- Attaching jQuery UI Slider to scrollbars and scrollwheel behaviour (ndp.iniScrollBars)

- Zooming maintains center of the viewport (ndp.iniZoom)

- Draws the boxes over the image (ndp.drawArticles).  Things to note:
	- An article box is: '<div class="article article23" id="a23"><div class="background"></div></div>'
	- The articles in the column and parts of articles in the viewport share the same numbered class (eg. 'article23')
	- When hovering either of them, it hilights all corresponding parts by attaching a class of 'hover'
	- When clicking an article in the viewport, it adds the tooltip markup: '<div class="menu"><h4>Heading</h4><a href="url">Read this Article</a></div>'
	- The tooltip is positioned above the mouse cursor (so the bottom of the tooltip is just under the cursor) and horizontally centered 

**************************************************************************************************/

ndp = {}; // TO AVOID NAMING CONFLICTS

/*
$(document).ready(function(){
	$('body').addClass('js');
	ndp.iniVars();
	ndp.iniViewer();
	window.onresize = ndp.onResize;
});
*/

ndp.iniVars = function() {
	// DERIVATIVE SIZES
	ndp.zoomSizes = [.05, .15, .333, .50, .666, 1];
	ndp.zoomMod = 3; // MULTIPLIER FOR OUR DERIVATIVES TO BE THE ACTUAL 100%
	ndp.startZoom = $('body').hasClass('article') ? 3 : 1; // DEFAULT ZOOM INDEX
	ndp.zoom = ndp.getZoom(ndp.startZoom);
	ndp.center = {x:0, y:0}; // FOR CENTERING THE ZOOM
	ndp.scrollSteps = 30; // FOR SCROLL WHEEL
	ndp.scrollAmount = 200; // FOR CLICKING A BUTTON ON THE END OF THE SCROLLBARS
	$('body').addClass('js');
}


// experiment to help select best text correction font

var ocrFont = new RegExp('[\\?&]font=([^&#]*)').exec(window.location.href) ; 	// have we gotta font= parameter ?
if (ocrFont) {
	var pmFont = ocrFont[0].substring(6).replace(/%20/g, ' ') ;
/**
	var styleContainer = document.createElement("style") ;	// create a new style element container
	$(styleContainer).text(".power-mode .ocr-input .input {font-family: '" + pmFont + "';}") ; // add the new styles to the container	
	$("head").append(styleContainer); // add the style element to the head of the doc
**/
	document.writeln("<style>\n" + ".power-mode .ocr-input .input {font-family: '" + pmFont + "';}\n" + "</style>") ;
}


// SETS UP THE VIEWER'S BEHAVIOUR
ndp.iniViewer = function() {
	ndp.iniLayout();
	ndp.iniZoom();
	ndp.iniDragging();
	ndp.loadImage();
	ndp.iniButtons();
	ndp.iniSync();
	ndp.showArticle();
	ndp.iniDatePicker();
	ndp.iniSearch();
	ndp.iniPages();
	ndp.iniComments();
}

ndp.ie6 = function() {
	var agt=navigator.userAgent.toLowerCase();
	var is_major = parseInt(navigator.appVersion);
	var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	var is_ie6 = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
	return is_ie6;
}

ndp.iniComments = function() {
	$('#page-detail .notes ul').hide();
	$('#page-detail .notes .show').click(function() {
		$('#page-detail .notes ul').toggle();
		// NN
		var txt = '';
		if ($(this).text().indexOf('Show') == 0) {
			txt = 'Hide Comments';
		} else if ($(this).text().indexOf('Hide') == 0) {
			txt = 'Show Comments';
		}
		$(this).text(txt);
	});
}

ndp.iniPages = function() {
	$('.pages select').change(function(){
		location.href = $('.pages form').attr('action') + '/' + $('.pages select option:selected').text();
	});
}

ndp.iniSearch = function() {
	$('#search .button').click(function(){
		if ($('#search .text').attr('value') == '') {
			alert ('Please enter a search term');
			return false;
		}
	});
}

ndp.iniDatePicker = function() {
	$('#date-year').html('').each(function() {
		$(this).append('<option>Select a year</option>');
		for (i=1803; i<1954; i++) {
			$(this).append('<option>'+i+'</option>');
		}
	}).change(function() {
		$('.months').removeClass('disabled').children('li').click(function(){
			$(this).addClass('selected');
			$('.days').removeClass('disabled');
		});
	});
}

ndp.showArticle = function() {
	if (!$('body').hasClass('article')) return;
	if ($('body').attr('id') != 'home') $('#viewer').append('<p class="buttons" id="return"><a href="javascript:history.go(-1);">View entire page</a></p>');
	ndp.moveImage(ndp.startPos.y, ndp.startPos.x); // CENTRES THE ARTICLE
}

ndp.onResize = function() {
	ndp.iniViewer();
	ndp.sizeThumbs();
}

ndp.iniLayout = function() {
	var h1 = $('#viewer').height();
	var w1 = $('#viewer').width();
	var h2 = $('.scroll-y .down').height();
	var w2 = $('.scroll-x .right').width();
	ndp.viewer = {height:h1, width:w1};
	// SIZES THE SCROLLBARS
	$('.scroll-x').width(w1);
	$('.scroll-x .slider').width($('.scroll-x').width() - w2 * 3);
	$('.scroll-y').height(h1 - h2);
	$('.scroll-y .slider').height($('.scroll-y').height() - h2 * 2);
}

ndp.iniButtons = function(event) {
	$('a.popup').click(function(){
		ndp.openPopup(this);
		return false;
	});
}

//var kfloading = false ;
ndp.openPopup = function(anchorEl) {

//if (kfloading) return ;
//kfloading = true ;

//alert("NDP OP" + anchorEl.id  ) ;
	$('#popup, #mask').remove(); // JUST IN CASE...
	$('body').addClass('popup'); // FOR IE6

	var title = $(anchorEl).attr('title');
	if (title == null || title == '' || (title.charAt(0) == '-') ) {
		title = anchorEl.innerHTML;		
	}
	
	var id = 'popup';
	if ($(anchorEl).hasClass("cloud-link")) {
		id = 'popupTagCloud';
	}
	
	$('body').append('<div id="'+id+'"><h4 class="title">'+title+'</h4><div class="content"></div></div><div id="mask"></div>');
	
	if ($(anchorEl).hasClass("cloud-link")) {
		$('#popupTagCloud .content').load(anchorEl.href,null,function(){
			ndp.iniTagPopUp();
		});	
	} 
//	else if ($(anchorEl).attr("id") == "listsId")  
	else {	
		//var src = anchorEl.href ;
		var src = $(anchorEl).attr("href");
		if ((src == null) || (src == '#') || (src.indexOf("javascript:") == 0)) ndp.iniPopUp(anchorEl);
		else {
//alert("loading " + anchorEl.href+"?12345") ;
			$('#popup .content').load(anchorEl.href,null,function(){ 
//alert("loaded") ;
				ndp.iniPopUp(anchorEl);
//alert("popped up") ;
			});
		}
	}
}

ndp.iniPopUp = function(anchorEl, id) {
	$('#popup .close').click(function() {
		$('#popup, #mask').remove();
		$('body').removeClass('popup');
		return false;
	});
	$("#mask").click(function() {
		$('#popup, #mask').remove();
		$('body').removeClass('popup');
		return false;
	});
	$('#popup .add-note').click(function(e) {
		var txt = $('#popup textarea').val();
		$('#popup, #mask').remove();
		$('body').removeClass('popup');
		return false;
	});
	//ndp.iniButtons();
	if ($('#popup .title').text() == 'Submit') {
		$('#popup').addClass('ocr-popup');
		$('#popup .title').text('Correct text');
		$('#popup input[type="text"]').click(function(){
			$('#popup .buttons .confirm').removeClass('disabled');
			return false;
		});
	} else if ($(anchorEl).text()=='Why may this text have mistakes?') {
		$('#popup').addClass('ocr-help-popup');
		$(".help-accordion").accordion({autoHeight: false, active: 0});
	} 	else if ($(anchorEl).text()=='Why can\'t I correct this text?') {
		$('#popup').addClass('ocr-help-popup');
		$(".help-accordion").accordion({autoHeight: false, active: 2});		
	} else if ($('#popup .title').text() == 'Keyboard Shortcuts') {
		$('#popup .title').html("Text Correction Help");
		$('#popup').addClass('ocr-help-popup');
		$(".help-accordion").accordion({autoHeight: false, active: 3});
	} else if ($('#popup .title').text() == 'Missing Text Help') {
		$('#popup .title').html("Text Correction Help");
		$('#popup').addClass('ocr-help-popup');
		$(".help-accordion").accordion({autoHeight: false, active: 5});
	} else if ($('#popup .title').text() == 'Text Correction Help') {
		$('#popup').addClass('ocr-help-popup');
		$(".help-accordion").accordion({autoHeight: false, active: 1});
	} 
	
	$('#popup .login a').click(function(){
		$(this).siblings('div.hidden').toggle();
		return false;
	});
	
}

ndp.iniTagPopUp = function() {
	$('#popupTagCloud .close').click(function() {
		$('#popupTagCloud, #mask').remove();
		$('body').removeClass('popup');
	});
	$("#mask").click(function() {
		$('#popupTagCloud, #mask').remove();
		$('body').removeClass('popup');
	});
}

/*
ndp.iniSync = function() {
//	$('body#page-detail.article #column .ocr').prepend('<div class="buttons" id="sync1"><a class="popup" href="_inc/common/captcha.html">Help fix this text!</a></div>');
// NN	$('body#page-detail.article #column .ocr').prepend('<div class="buttons" id="sync1"><a class="popup1" href="javascript:void(0)" onclick="javascript:dc1(\'lc1\');">Help fix this text!</a></div>');

// NN	$('body#page-detail.article #column span').hover(function(){
	$('body#page-detail.article #column .ocr span.displayFix').hover(function(){
//		var idAttr = $(this).attr('id');
//if (idAttr != null && idAttr != '') {
		var offset = $(this).offset();
		var user = $.cookie('newspaperUser');
		var captcha = $.cookie('newspaperCaptcha');
		var txt = ((user == null || user == '') && (captcha == null || captcha == '')) ?
			  '<div class="buttons" id="sync"><a class="popup" href="/ndp/del/captchaForm">Help fix this text!</a></div>' :
			  '<div class="buttons" id="sync"><a class="popup1" id="' + $(this).attr('id') + '" href="javascript:void(0)" onclick="javascript:dc1($(this).attr(\'id\'));">Help fix this text!</a></div>';

//		$(this).append('<div class="buttons" id="sync"><a class="popup" href="/_inc/common/captcha.html">Help fix this text!</a></div>');
//		$(this).append('<div class="buttons" id="sync"><a class="popup1" id="' + $(this).attr('id') + '" href="javascript:void(0)" onclick="javascript:dc1($(this).attr(\'id\'));">Help fix this text!</a></div>');
		$(this).append(txt);
		$('#sync1').hide();
		ndp.iniButtons();
//}

	}, function() {
		$('#sync1').show();
		$('#sync').remove();
	});
	ndp.iniButtons();
}
*/

ndp.iniSync = function() {
	$('body#page-detail.article #column .ocr span.displayFix').hover(function(){
		if ($(this).hasClass("saving") || $(".ocr-input input").length>0) {
			return;
		}
		$(this).addClass("hovered");
		var offset = $(this).offset();
		var user = $.cookie('newspaperUser');
		var captcha = $.cookie('newspaperCaptcha');
		var txt = ((user == null || user == '') && (captcha == null || captcha == '')) ?
			  ('<div class="buttons" id="sync"><a class="popup" href="/ndp/del/captchaForm?target=ocr&t=' + new Date().getTime() + '">Fix this text</a></div>') :
			  '<div class="buttons" id="sync"><a class="popup1" href="javascript:void(0)" onclick="javascript:enterPowerEdit(\''+ $(this).attr('id') +'\');">Fix this text</a></div>';				  
//			  '<div class="buttons" id="sync"><a class="popup1" id="' + $(this).attr('id') + '" href="javascript:void(0)" onclick="javascript:dc1(event);">Help fix this text!</a></div>';
//			  '<div class="buttons" id="sync"><a class="popup1" id="' + $(this).attr('id') + '" href="javascript:void(0)" onclick="javascript:dc1($(this).attr(\'id\'));">Help fix this text!</a></div>';
		$(this).append(txt);
		ndp.iniButtons();
	}, function() {
		$(this).removeClass("hovered");
		$('.ocr p span .buttons').remove();
	});
	ndp.iniButtons();
}

ndp.clickOCR = function(wh, ww, y, x) {
	ndp.panImage(x - 100, y - wh);
}

ndp.iniScrollBars = function() {
	$('.scroll-x .slider').slider({
		handle: '.thumb',
		max: 100,
		start: function(e, ui) { }, // NEEDS TO BE DEFINED
		slide: function(e, ui) {
			$('#viewer .wrapper').css('left', ((-ui.value/100) * (ndp.graphic.width * ndp.zoom - ndp.viewer.width)));
			//document.title = ($('#viewer .wrapper').offset().left-$('#viewer').offset().left) + ', ' + ($('#viewer .wrapper').offset().top-$('#viewer').offset().top);
		},
		stop: function(e, ui) { } // NEEDS TO BE DEFINED
	}).slider('moveTo', 1); // BUG FIX
	$('.scroll-y .slider').slider({
		handle: '.thumb',
		max: 100,
		start: function(e, ui) { }, // NEEDS TO BE DEFINED
		slide: function(e, ui) {
			$('#viewer .wrapper').css('top', ((-ui.value/100) * (ndp.graphic.height * ndp.zoom - ndp.viewer.height)));
		},
		stop: function(e, ui) { } // NEEDS TO BE DEFINED
	});
	// END BUTTONS
	$('.scroll-y .up').click(function() {
		$('.scroll-y .slider').slider('moveTo', '-='+ndp.scrollAmount);
	});
	$('.scroll-y .down').click(function() {
		$('.scroll-y .slider').slider('moveTo', '+='+ndp.scrollAmount);
	});
	$('.scroll-x .right').click(function() {
		$('.scroll-x .slider').slider('moveTo', '+='+ndp.scrollAmount);
	});
	$('.scroll-x .left').click(function() {
		$('.scroll-x .slider').slider('moveTo', '-='+ndp.scrollAmount);
	});
	// SCROLL WHEEL
	window.addEventListener('DOMMouseScroll', ndp.scrollWheel, false);
	// TO MAKE SURE YOU'RE USING THE SCROLL WHEEL ON THIS WINDOW
	$('#viewer').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	ndp.sizeThumbs();
}

ndp.panImage = function (x, y) {
	// PASS IT COORDINATES ON THE ORIGINAL IMAGE TO SHOW (eg. SYNC)
	var top = Math.round(-y * ndp.zoom / ndp.zoomMod);
	var left = Math.round(-x * ndp.zoom / ndp.zoomMod);
	ndp.moveImage(top, left);
}

// MOVES .wrapper
ndp.moveImage = function (top, left) {
	$('#viewer .wrapper').animate({
		top:top,
		left:left
	},false ,false ,function(){
		ndp.findCenter();
		ndp.sizeThumbs();
	});
}

ndp.scrollWheel = function(e) {
	if (!$('#viewer').hasClass('hover')) return; // IF YOU AREN'T HOVERING OVER THE WINDOW
	var moveTo = '+=' + 100/ndp.scrollSteps;
	if (e.detail < 0) moveTo = '-=' + 100/ndp.scrollSteps;
	$('.scroll-y .slider').slider('moveTo', moveTo);
}

ndp.sizeThumbs = function() {
	if (ndp.ie6()) return; // BUG
	var thumbW = (ndp.viewer.width / (ndp.graphic.width * ndp.zoom)) * $('.scroll-x .slider').width();
	var thumbH = (ndp.viewer.height / (ndp.graphic.height * ndp.zoom)) * $('.scroll-y .slider').height();
	var trackW = $('.scroll-x .slider').width();
	var trackH = $('.scroll-y .slider').height();
	// DISABLE THE SCROLLBAR IN THESE CASES?
	if (thumbW > trackW) thumbW = trackW - 10;
	if (thumbH > trackH) thumbH = trackH - 10;
	$('.scroll-x .thumb').width(thumbW);
	$('.scroll-y .thumb').height(thumbH);

	// POSITIONS THE THUMBS
	var x = $('#viewer .wrapper').offset().left - $('#viewer').offset().left;
	var y = $('#viewer .wrapper').offset().top - $('#viewer').offset().top;
	var left = -(trackW - thumbW) * (x / (ndp.graphic.width * ndp.zoom - ndp.viewer.width));
	var top = -(trackH - thumbH) * (y / (ndp.graphic.height * ndp.zoom - ndp.viewer.height));
	if (left > trackW - thumbW) left = trackW - thumbW;
	if (top > trackH - thumbH) top = trackH - thumbH;
	if (left < 0) left = 0;
	if (top < 0) top = 0;
	$('.scroll-x .thumb').css('left', left);
	$('.scroll-y .thumb').css('top', top);
}

// FIGURES OUT THE DIFFERENCE BETWEEN OUR ZOOM AND ACTUAL 100%
ndp.getZoom = function(n) {
	return Math.round(ndp.zoomSizes[n] * ndp.zoomMod * 100) / 100;
}

ndp.iniDragging = function() {
	// MAKES THE IMAGE DRAGGABLE
	$('#viewer .wrapper').draggable({
		start: function(e, ui) {
			$(this).addClass('active');
			ndp.cancelClick = true;
		},
		drag: function(e, ui) {
			ndp.sizeThumbs();
		},
		stop: function(e, ui) {
			$(this).removeClass('active');
			ndp.findCenter();
		}
	});
}

ndp.iniZoom = function() {
	$('.controls .callout').hide();
	$('.controls .slider').slider({
		handle: '.thumb',
		min: 0,
		max: 5,
		steps: 5,
		startValue: ndp.startZoom,
		//min: 300, max: 0,
		start: function(e, ui) {
			$('.controls .callout').fadeIn('fast');
		},
		slide: function(e, ui) {
			$('.controls .callout').html((ndp.getZoom(ui.value) * 100) + '%')
				.css('left', $('.controls .thumb').css('left'));
			/*
			ndp.zoom = ui.value/100;
			ndp.zoomImage();
			*/
		},
		stop: function(e, ui) {
			$('.controls .callout').fadeOut();
			// SCALES THE IMAGE
			ndp.zoom = ndp.getZoom(ui.value);
			ndp.zoomImage();
		}
	});
	$('.controls .plus').click(function() {
		$('.controls .slider').slider('moveTo', '+=1');
	});
	$('.controls .minus').click(function() {
		var moveTo = '-=1';
		if ($('.controls .slider').slider('value') == 1) moveTo = '0';
		$('.controls .slider').slider('moveTo', moveTo);
	});
}

// LOADS AN IMAGE IN TO THE VIEWER
ndp.loadImage = function() {
	$('#viewer .image img').animate({opacity:0},1);
	ndp.checkInt = window.setInterval('ndp.iniImage()', 250);
}

ndp.iniImage = function() {
	var img = $('#viewer .image img');
	var w = $(img).width();
	var h = $(img).height();
	if (h < 500) return;
	if (ndp.checkInt) window.clearInterval(ndp.checkInt);
	$('#viewer .image img').animate({opacity:1},1);
	ndp.graphic = {width:w, height:h};
	ndp.findCenter();
	ndp.drawArticles();
	ndp.zoomImage();
	ndp.iniScrollBars();
}

// CENTERS A COORDINATE OF THE IMAGE IN THE VIEWER
ndp.centerImage = function(o) {
	var top = Math.round(ndp.viewer.height / 2 - o.y * ndp.zoom);
	var left = Math.round(ndp.viewer.width / 2 - o.x * ndp.zoom);
	$('#viewer .wrapper').css('top', top).css('left', left);
}

ndp.findCenter = function() {
	var pos1 = $('#viewer .wrapper').offset();
	var pos2 = $('#viewer').offset(); // offset() PROVIDES AN ABSOLUTE OFFSET SO WE NEED TO ADD THE #viewer
	var top = Math.round((-pos1.top + pos2.top + ndp.viewer.height/2) / ndp.zoom);
	var left = Math.round((-pos1.left + pos2.left + ndp.viewer.width/2) / ndp.zoom);
	ndp.center = {x:left, y:top};
}

ndp.zoomImage = function() {
	var w = ndp.graphic.width * ndp.zoom;
	var h = ndp.graphic.height * ndp.zoom;
	$('#viewer .image img, #viewer .wrapper').width(w).height(h); // SCALES THE IMAGE AND ITS WRAPPER
	ndp.centerImage(ndp.center);
	ndp.drawArticles();
	ndp.sizeThumbs();
}

ndp.drawArticles = function() {
	if (!ndp.articles) return; // NO ARTICLES
	$('#viewer .article').remove();
	if ($('body').hasClass('article')) {
		return ndp.blackOut(); // FOR ARTICLE VIEW
	}
	for (i = 0; i < ndp.articles.length; i++) {
		var areas = ndp.articles[i].areas;
		for (j = 0; j < areas.length; j++) {
			var a = areas[j];
			var article = $('#viewer .wrapper').append('<div class="article" id="a'+i+'"><div class="background"></div></div>');
			var z = ndp.zoom / 3.04; //ndp.zoomMod;
			$('#a'+i).css('left', (a.x)*z)
				.css('top', (a.y)*z)
				.addClass('article'+i)
				.children('.background')
					.width(a.width*z)
					.height(a.height*z);
		}
	}

	// HOVER FOR ARTICLE IN COLUMN
	$('#column .articles li').hover(function(){
		var i = $(this).attr('class');
		i = i.split(' ').slice(-1);
	 		$('.'+i).addClass('hover');
	}, function() {
		var i = $(this).attr('class');
		i = i.split(' ').slice(-1);
			$('.'+i).removeClass('hover');
	});

	// HOVER FOR ARTICLE IN VIEWER
	$('#viewer .article').hover(function(){
		var i = $(this).attr('id');
		i = i.substr(1);
			$('.article'+i).addClass('hover');
		//document.title = i;
	}, function() {
		$('#viewer .menu').remove();
		var i = $(this).attr('id');
		i = i.substr(1);
			$('.article'+i).removeClass('hover');
	}).click(function(e) {
		if (!$(this).hasClass('article')) return;
		if (ndp.cancelClick) return ndp.cancelClick = false;
		var i = $(this).attr('id');
		i = i.substr(1);
		var link = $('#column .articles .article'+i+' a:first-child');
		var url = $(link).attr('href');
		var heading = $(link).text();
		$(this).append('<div class="menu"><h4>'+heading+'</h4><a href="'+url+'">Read this Article</a></div>');
		var top = e.pageY - $(this).offset().top;
		var left = e.pageX - $(this).offset().left;
		var h = $('#viewer .menu').height();
		$('#viewer .menu').css('top', top-h-10).css('left', left-81);
		$('#viewer .menu a').click(function() {
			$('#viewer .menu').remove(); // REMOVES POPUP ONCLICK
		});
	});
}

ndp.blackOut = function() {
	for (i = 0; i < ndp.articles.length; i++) {
		var a = ndp.articles[i];
		var article = $('#viewer .wrapper').append('<div class="article" id="a'+i+'"></div>');
		var z = ndp.zoom / 3.04; //ndp.zoomMod;
		$('#a'+i).css('left', (a.x)*z)
			.css('top', (a.y)*z)
			.width(a.width*z)
			.height(a.height*z)
			.addClass('article'+i);
	}
}


ndp.enterOCRFullScreen = function(){
	$('div.button #exit').show();
	$('div.button #enter').hide();
	$('body').addClass('ocrFullScreen');
	$('#contentall').css("top", "0px") ;
	$('div#viewer').css("height",$('div#viewer').height() + 104   );	
	//$(".ocr-text").css("overflow-y","auto");
	//$(".ocr-text").css("overflow-x","hidden");
	$('.ocr-text').css('clear','both');
	$('.ocr-text').css('padding-bottom','2em');		
	ndp.resizeOCRSection();
	$(window).bind('resize', ndp.resizeOCRSection);
	ndp.redrawViewport() ; //kkf9mar10
}
var ocrResizeTimeout;

ndp.resizeOCRSection = function() {
	if (ocrResizeTimeout) clearTimeout(ocrResizeTimeout);
	ocrResizeTimeout = setTimeout("ndp.resizeOCRSection2()",100)
}

ndp.resizeOCRSection2 = function() {		
	//if (jQuery.browser.msie) {
		$("#column").css("height",$(window).height()-$(".power-mode-toolbar").height()+"px");
	//	return;
	//}
	//$(".ocr-text").css("height",$(window).height() - 80 - $(".ocr .definition").height() + "px");
}

ndp.exitOCRFullScreen = function() {
	$('div.button #exit').hide();
	$('div.button #enter').show();
	$('body').removeClass('ocrFullScreen');
	$('#contentall').css("top", "") ;
	$('div#viewer').css("height",$('div#viewer').height() - 104   + "px");
	//if (jQuery.browser.msie) {
		$("#column").css("height","");
	//}
	$(".ocr-text").css("height","auto");
	$(".ocr-text").css("clear","none");
	$(window).unbind("resize", ndp.resizeOCRSection);
	ndp.redrawViewport() ; //kkf9mar10
}

ndp.iniEditModeButton = function() {
	if ($(".ocr-text .displayFix").length==0) { //don't display button if no lines to edit		
		return;
	}	
	var txt = '<a class="power-mode-button" onclick="if (ndp.authenticated()) {this.href=\'javascript:void(0);\'; enterPowerEdit();} else {ndp.openPopup(this); return false;};" href="/ndp/del/captchaForm?target=ocr&t=' + new Date().getTime() + '">Fix this Text</a>';
	$(".ocr .definition .buttons").append(txt);
}

ndp.authenticated = function() {
	var user = $.cookie('newspaperUser');
	var captcha = $.cookie('newspaperCaptcha');
	return ((user != null && user != '') || (captcha != null && captcha != ''));
}

ndp.enterEditTags = function() {
	ndp.openPopup($('#tagId')[0]);
}

ndp.enterEditAnnotations = function() {
	ndp.openPopup($('#annotationId')[0]);
}

ndp.initialisePages = function(lastPage) {
	if(lastPage < 8){ // Show all pages
		for(i = 1; i <= lastPage; i++){
			$('#page' + i).show();
		}
		$('#placeHolder').show();
	} else {
		var onID = parseInt($('span ul#tagPages li.on').attr("id").substring(4));
		
		// Show appropriate arrows
		if (onID > 4 ){
			$('#leftArrow').show();
		} else {
			$('#placeHolder').show();
		}
		if (onID < (lastPage - 3)){
			$('#rightArrow').show();
		}
		
		//show first and last links
		$('#page1').show();
		$('#page' + lastPage).show();
		
		//show five pages that are in view
		// If within 3 of first page, show first 6 and lastEllipsis
		if(onID < 4){ 
			for(i = 2; i <= 6; i++){
				$('#page' + i).show();
			}
			$('#lastEllipsis').show();
		} else if(onID > lastPage - 3){ // If within 3 of last page, show last 6 and firstEllipsis
			for(i = lastPage - 1; i >= lastPage - 5; i--){
				$('#page' + i).show();
			}
			$('li#firstEllipsis').show();
		} else {
			for(i = (onID - 2); i <= (onID + 2); i++){
				$('#page' + i).show();
			}
			if(onID != 4){ // Show elipsis before first in current 5
				$('li#firstEllipsis').show();
			}
			if(onID != lastPage - 3){  // Show elipsis after last in current 5
				$('li#lastEllipsis').show();
			}
		}
	}	
}


ndp.pageLeft = function() {
	// Find out where the first page link is
	var lastVisiblePage = parseInt($('ul#tagPages li.page:visible:not(:last):last').attr("id").substring(4));
	var firstVisiblePage = parseInt($('ul#tagPages li.page:visible:not(:first):first').attr("id").substring(4));
	var lastPage = parseInt($('ul#tagPages li.page:visible:last').attr("id").substring(4));
	if((lastVisiblePage - firstVisiblePage) > 3){
		lastVisiblePage = firstVisiblePage + 4;
	}
		
	// show right hand ellipsis
	$('#lastEllipsis').show();
	if(lastVisiblePage == (lastPage - 1)){ // Was showing last 5, so now show right hand arrow again
		$('#rightArrow').show();
		$('#placeHolder').hide();
	}
	
	// Hide left hand and left arrow ellipsis if now showing first 5 in range
	if((firstVisiblePage - 2) == 1){ 
		$('#firstEllipsis').hide('slow');
		$('#leftArrow').hide();
		$('#placeHolder').show();
	}
	
	//Hide last page in old range
	$('li#page' + lastVisiblePage).hide('slow');
	
	//Show first page in new range
	$('li#page' + (firstVisiblePage - 1)).show('slow');

		
}

ndp.pageRight = function() {
	
	// Find out where the first page link is
	var lastVisiblePage = parseInt($('ul#tagPages li.page:visible:not(:last):last').attr("id").substring(4));
	var firstVisiblePage = parseInt($('ul#tagPages li.page:visible:not(:first):first').attr("id").substring(4));
	var lastPage = parseInt($('ul#tagPages li.page:visible:last').attr("id").substring(4));
	if((lastVisiblePage - firstVisiblePage) > 3){
		firstVisiblePage = lastVisiblePage - 4;
	}
		
	// show left hand ellipsis
	$('#firstEllipsis').show();
	if(firstVisiblePage == 2){ // Was showing first 5, so now show left hand arrow again
		$('#leftArrow').show();
		$('#placeHolder').hide();
		
	}
	
	// Hide right hand ellipsis and right arrow if now showing last 5 in range
	if((lastVisiblePage + 2) == lastPage){ 
		$('#lastEllipsis').hide('slow');
		$('#rightArrow').hide();
		
	}
	
	//Hide first page in old range
	$('li#page' + firstVisiblePage).hide('slow');
	
	//Show last page in new range
	$('li#page' + (lastVisiblePage + 1)).show('slow');
	
}	

// KW 20 Oct 10 - for page and article more options interaction
function showOptions() {
		// Check if option menu is open
		if ($('.options').hasClass('hidden')) {
			$('.options').removeClass('hidden'); // show sub menu
			}
		else {
			$('.options').addClass('hidden'); // hide sub menu
			}

}

ndp.iniAdvancedSearchPublicationDatesValidation = function() {
	
	$('#publication').children().change(function() {
 		// remove any existing message on change
        $('#dateErrorMsg').remove();
		
		// remove any set classes on change
		$('#fromyyyy').removeClass();
		$('#frommm').removeClass();
		$('#fromdd').removeClass();
		$('#toyyyy').removeClass();
		$('#tomm').removeClass();
		$('#todd').removeClass();

        var fromyyyy;
        var toyyyy;
        var frommm;
        var tomm;
        var fromdd;
        var todd;
        var message = "";
        var messageSet = new Boolean();
        messageSet = false;

		// get values for years, months and days or set as 0000, 00 and 00 respectively
        fromyyyy = (!$('[name=fromyyyy]').val()) ? "0000" : $('[name=fromyyyy]').val();
        toyyyy = (!$('[name=toyyyy]').val()) ? "0000" : $('[name=toyyyy]').val();
        frommm = (!$('[name=frommm]').val()) ? "00" : $('[name=frommm]').val();
        tomm = (!$('[name=tomm]').val()) ? "00" : $('[name=tomm]').val();
        fromdd = (!$('[name=fromdd]').val()) ? "00" : $('[name=fromdd]').val();
        todd = (!$('[name=todd]').val()) ? "00" : $('[name=todd]').val();

        // concatenate values for years, months and days to enable easy comparison
        var fromDate = fromyyyy + frommm + fromdd;
        var toDate = toyyyy + tomm + todd;
		
		/*
		 * Type 1 warnings provide assistance to the user while constructing a date 
		 * Type 2 warnings compare the dates entered and warn if the To date is earlier than the From date
		 */
        if (fromDate == '00000000' || toDate == '00000000') {
            // date validation where only one of the from or to dates is being used and there are incorrect values
			
			// Type 1 warnings
            if (fromyyyy != '0000' && fromdd != '00' && frommm == '00') {
                message = message + "Please enter a <em>From</em> month";
                $('#frommm').focus().addClass("dateControlError");
                messageSet = true;
            } else {
                if (fromyyyy == '0000' && fromDate != '00000000') {
                    message = message + "Please enter a <em>From</em> year";
                    $('#fromyyyy').focus().addClass("dateControlError");
                    messageSet = true;
                }
            }
            if (toyyyy != '0000' && todd != '00' && tomm == '00') {
                message = message + "Please enter a <em>To</em> month";
                $('#tomm').focus().addClass("dateControlError");
                messageSet = true;
            } else {
                if (toyyyy == '0000' && toDate != '00000000') {
                    message = message + "Please enter a <em>To</em> year";
                    $('#toyyyy').focus().addClass("dateControlError");
                    messageSet = true;
                }
            }
        }
        else {
            // date validation where both from and to dates are being used and there are incorrect values

			// Type 1 warnings
            if (!messageSet) {
                if (fromyyyy == '0000') {
                    message = message + "Please enter a <em>From</em> year";
                    $('#fromyyyy').focus().addClass("dateControlError");
                    messageSet = true;
                } else {
                    if (frommm == '00' && fromdd != '00') {
                        message = message + "Please enter a <em>From</em> month";
                        $('#frommm').focus().addClass("dateControlError");
                        messageSet = true;
                    }
                }
            }
			
			// Type 1 warnings
            if (!messageSet) {
                if (toyyyy == '0000') {
                    message = message + "Please enter a <em>To</em> year";
                    $('#toyyyy').focus().addClass("dateControlError");
                    messageSet = true;
                } else {
                    if (tomm == '00' && todd != '00') {
                        message = message + "Please enter a <em>To</em> month";
                        $('#tomm').focus().addClass("dateControlError");
                        messageSet = true;
                    }
                }
            }
			
			// Type 2 warnings
            if (!messageSet) {
                if (fromDate - toDate > 8870 && !messageSet) {
                    /*
                     * 8870 is the minimum difference between two dates out by a year
                     * eg 19710101 - 19701231 = 8870 (diff between 1 Jan 1971 and 31 Dec 1970)
                     *
                     */
                    message = message + "The <em>From</em> year (" + parseInt(fromyyyy) + ") must be the same as or earlier than the <em>To</em> year (" + parseInt(toyyyy) + ")";
                    // message = message + "The first year (" + parseInt(fromyyyy) + ") must be the same as or earlier than the second year (" + parseInt(toyyyy) + ")";
					$('#fromyyyy').addClass("dateControlError");
					$('#toyyyy').addClass("dateControlError");
                    messageSet = true;
                } else {
                    if (fromDate - toDate >= 70 && frommm != '00' && tomm != '00' && !messageSet) {
                        /*
                         * 70 is the minimum difference between two dates out by a month
                         * eg 18050501 - 18050431 = 70 (diff between 31 April 1805 and 1 May 1805)
                         *
                         * 1130 is the maximum difference between two dates out by a month
                         * eg 18911231 - 18910101 = 1130 (diff between 1 Jan 1891 - 31 December 1891)
                         */

                        var fromMonthText = "";
                        var toMonthText = "";

                        switch (parseInt(frommm)) {
                            case 1:
                                fromMonthText = "January";
                                break;
                            case 2:
                                fromMonthText = "February";
                                break;
                            case 3:
                                fromMonthText = "March";
                                break;
                            case 4:
                                fromMonthText = "April";
                                break;
                            case 5:
                                fromMonthText = "May";
                                break;
                            case 6:
                                fromMonthText = "June";
                                break;
                            case 7:
                                fromMonthText = "July";
                                break;
                            case 8:
                                fromMonthText = "August";
                                break;
                            case 9:
                                fromMonthText = "September";
                                break;
                            case 10:
                                fromMonthText = "October";
                                break;
                            case 11:
                                fromMonthText = "November";
                                break;
                            case 12:
                                fromMonthText = "December";
                                break;
                        }

                        switch (parseInt(tomm)) {
                            case 1:
                                toMonthText = "January";
                                break;
                            case 2:
                                toMonthText = "February";
                                break;
                            case 3:
                                toMonthText = "March";
                                break;
                            case 4:
                                toMonthText = "April";
                                break;
                            case 5:
                                toMonthText = "May";
                                break;
                            case 6:
                                toMonthText = "June";
                                break;
                            case 7:
                                toMonthText = "July";
                                break;
                            case 8:
                                toMonthText = "August";
                                break;
                            case 9:
                                toMonthText = "September";
                                break;
                            case 10:
                                toMonthText = "October";
                                break;
                            case 11:
                                toMonthText = "November";
                                break;
                            case 12:
                                toMonthText = "December";
                                break;
                        }

                        message = message + "The <em>From</em> month (" + fromMonthText + ") must be the same as or earlier than the <em>To</em> month(" + toMonthText + ") ";    
                        // message = message + "The first month (" + fromMonthText + ") must be the same as or earlier than the second month (" + toMonthText + ")";
						$('#frommm').addClass("dateControlError");
						$('#tomm').addClass("dateControlError");
                        messageSet = true;
                    } else {
                        if (parseInt(fromDate) - parseInt(toDate) >= 1 && fromdd != '00' && todd != '00' && !messageSet) {
                            /*
                             * 1 is the minimum difference between two dates out by a day (obviously)
                             * eg 18210501 - 18210502 = 1 (diff between 1 May 1821 and 2 May 1821)
                             *
                             * 70 is the maximum see difference between two dates out by days
                             * eg 18210501 - 18050431 = 70 (diff between 1 May 1821 and 31 Apr 1821)
                             *
                             */
                            message = message + "The <em>From</em> day (" + parseInt(fromdd) + ") must be the same as or earlier than the <em>To</em> day (" + parseInt(todd) + ")";
                            // message = message + "The first day (" + parseInt(fromdd) + ") must be the same as or earlier than the second day (" + parseInt(todd) + ")";
							$('#fromdd').addClass("dateControlError");
							$('#todd').addClass("dateControlError");
                            messageSet = true;
                        }
                    }
                }
            }
        }

        if (messageSet) {
        	$('#publication').append("<span id = 'dateErrorMsg'> " + message + " </span > ");
        }
    });
	
}

