jQuery(document).ready(function($){

	var Engine = {
		// navigation scripts
		navigation : {
			// keyboard accessibility for IE6
			keyboardAccessibility : function(){
				if(!($.browser.msie && $.browser.version.substr(0,1) == '6')){
					$('#navigation a').focus(function(){
						$(this).css('text-decoration','underline');
						$(this).parents('ul').eq(0).addClass('over');
						$(this).parent('li').find('ul').eq(0).addClass('over');
					}).blur(function(){
						$(this).css('text-decoration','none');
						$(this).parents('ul').eq(0).removeClass('over');
						$(this).parent('li').find('ul').eq(0).removeClass('over');
					});
				}
			},
			// activate current item on hover
			sectionChange : function(time){
				Engine.navigation.sectionChangeTime = time;
				Engine.navigation.sectionChangeIt = function(){
					Engine.navigation.sectionChangeHovered.parent().find('> li').removeClass('current');
					Engine.navigation.sectionChangeHovered.addClass('current');
				}

				$('#navigation > ul > li:not(.spacer) > a').hover(function(){
					Engine.navigation.sectionChangeHovered = $(this).parent();
					if(time){
						clearTimeout(Engine.navigation.sectionChangeTimeout);
						Engine.navigation.sectionChangeTimeout = setTimeout(Engine.navigation.sectionChangeIt,Engine.navigation.sectionChangeTime);
					} else {
						Engine.navigation.sectionChangeIt();
					}
				},function(){
					if(time) clearTimeout(Engine.navigation.sectionChangeTimeout);
				});
			},
			// hover for IE6
			hoverClass : function(){
				if($.browser.msie && $.browser.version.substr(0,1) == '6'){
					$('#navigation li').hover(function(){
						$(this).addClass('over');
					},function(){
						$(this).removeClass('over');
					});
				}
			}
		},
		// article scripts
		article : {
			// comment chars counter and limit
			commentCounter : function(){
				if($('#postComment fieldset textarea').size() < 1) return false;

				var charLimit 	= 1000;
				var code 		= ', left: <span class="limit">' + (charLimit - $('#postComment fieldset textarea').val().length) + '</span>';

				$('#postComment p.limit-info').append(code);

				$('#postComment fieldset textarea').keyup(function(){
					if($(this).val().length > charLimit){
						$(this).val($(this).val().substr(0,charLimit));
						$('#postComment span.limit').html('0');
					} else {
						$('#postComment span.limit').html((charLimit - $(this).val().length).toString());
					}
				});
			},
			// complainments
			commentsComplainments : function(){
				$('#commentsList div.comment p.author').before('<p class="complain"><span>Complain about this comment</span></p>');
				$('#commentsList div.comment p.complain span').toggle(function(){
					$(this).addClass('active').parents('div.comment').next('form.complainment').addClass('active');
					return false;
				},function(){
					$(this).removeClass('active').parents('div.comment').next('form.complainment').removeClass('active');
					return false;
				});
			},
			// font size change
			fontSize : function(){
				$('div.articleRelated:last').append('<div class="fonts">Change font size: <a href="#a" class="a">A</a> <span>|</span> <a href="#aa" class="aa">A</a> <span>|</span> <a href="#aaa" class="aaa">A</a></div>');

				$('div.articleRelated div.fonts a').click(function(){
					var value;
					switch ($(this).attr('class')) {
						case 'aa':
							value = 'aa';
							break;
						case 'aaa':
							value = 'aaa';
							break;
						default:
							value = 'a';
							break;
					}

					$.cookie('fontsizeAAA', value, { expires: 90, path: '/'});

					$('#article div.body').attr('class','body font-'+$(this).attr('class'));
					return false;
				});

				if($('#article').size() == 1 && $.cookie('fontsizeAAA') != 'null'){
					$('#article div.body').attr('class','body font-'+$.cookie('fontsizeAAA'));
				}
			}
		},
		// other elements
		other : {
			// tabs
			tabbedContainers : function(){
				/* tabs */
				$('div.tabbedContainer').each(function(){
					var cont = $(this);
					cont.find('ul.anchors li:first-child').addClass('tabs-selected');
					cont.find('ul.anchors li a').click(function(){
						cont.find('ul.anchors li').removeClass('tabs-selected');
						$(this).parent('li').addClass('tabs-selected');

						cont.find('>div:visible').hide();
						var re = /([_\-\w]+$)/i;
						$('#' + re.exec($(this).attr('href'))[1]).show();

						return false;
					});
				});
			},
			// searchbox value label
			searchValueLabel : function(container,text){
				if(container.val() === '') container.val(text);
				container.focus(function(){
					if($(this).val() == text){
						$(this).val('');
					}
				}).blur(function(){
					if($(this).val() == ''){
						$(this).val(text);
					}
				});
			},
			// advanced search form interaction
			searchAdvancedInteraction : function(){
				if($('#advs-daterange-5').attr('checked') !== 'checked'){
					$('#advancedSearch fieldset div.radios div.dates select').attr('disabled','disabled');
				}
				$('#advancedSearch span.datechange input').focus(function(){
					if($(this).attr('id') == 'advs-daterange-5'){
						$('#advancedSearch fieldset div.radios div.dates select').attr('disabled','');
					} else {
						$('#advancedSearch fieldset div.radios div.dates select').attr('disabled','disabled');
					}
				});
			},
			// videos hover
			videosHover : function(){
				$('#videoRelated p.video').bind('mouseenter',function(){
					$(this)
						.addClass('video-over')
						.click(function(){
							window.location = $(this).find('a:first').attr('href');
						});

				}).bind('mouseleave',function(){
					$(this)
						.removeClass('video-over')
						.unbind("click");
				});
			},
			// ios images fix
			iosFix : function(){
				$('div.ios p.img img').each(function(){
					var image = $(this);
					var parent = $(this).parent();
					var imageWidth = image.width() || image.get(0).clientWidth;
					var parentWidth = parent.width();
					if (imageWidth / parentWidth < 0.4) parent.addClass('float');
				})
			}
		},
		// town specific
		specific : {
			// lightbox
			lightboxInit : function(){
				$('a[@rel*=lightbox]').lightBox();
			},
			// sound and vision more toggler
			svToggler : function(){
				$('#soundAndVision p.more span').click(function(){
					$(this).parent('p').next('.toggled').toggle();
				});
			}
		},
		// sliders
		sliders : {
			// entertainment
			entertainment : {
				time : 10000,
				slide : function(){
					$('#entertainment ul.paging li.next a').trigger('click');
					Engine.sliders.entertainment.timeout = setTimeout(Engine.sliders.entertainment.slide,Engine.sliders.entertainment.time);
				},
				init : function(){
					var slidesCurrent 	= 1;
					var slidesCount 	= $('#entertainment ul.slides').size();
					var slidesWidth 	= $('#entertainment div.slidesHolder').width();

					if(slidesCount > 1){
						// cloning
						$('#entertainment div.slidesHolder').addClass('slidesHolderCSS').before('<ul class="paging"><li class="prev"><a href="./" title="Previous">&laquo;</a></li><li class="pause"><a href="./" title="Pause">&bull;</a></li><li class="next"><a href="./" title="Next">&raquo;</a></li></ul>');
						$('#entertainment ul.slides:last').clone().prependTo("#entertainment div.slidesHolder");
						$('#entertainment ul.slides').eq(1).clone().appendTo("#entertainment div.slidesHolder");

						// positioning
						$('#entertainment ul.slides').each(function(i){
							var leftPosition = (slidesWidth * i) - slidesWidth;
							$(this).css({ position: "absolute", width: "100%", top: "0", left: leftPosition });
						});

						// click: previous
						$('#entertainment ul.paging li.prev a').click(function(){
							if(parseInt($('#entertainment ul.slides').eq(0).css("left")) % slidesWidth == 0){
								if(slidesCurrent == 0){
									$('#entertainment ul.slides').each(function(){
										var newLeftPosition = parseInt($(this).css("left"),10) - slidesCount * slidesWidth;
										$(this).css('left',newLeftPosition);
									});
									slidesCurrent = slidesCount;
								}

								$('#entertainment ul.slides').each(function(){
									var newLeftPosition = parseInt($(this).css("left"),10) + slidesWidth;
									$(this).animate( { left: + newLeftPosition + 'px' }, 'slow' );
								});
								slidesCurrent--;
							}
							return false;
						});

						// click: next
						$('#entertainment ul.paging li.next a').click(function(){
							if(parseInt($('#entertainment ul.slides').eq(0).css("left")) % slidesWidth == 0){
								if(slidesCurrent == slidesCount+1){
									$('#entertainment ul.slides').each(function(){
										var newLeftPosition = parseInt($(this).css("left"),10) + slidesCount * slidesWidth;
										$(this).css('left',newLeftPosition);
									});
									slidesCurrent = 1;
								}

								$('#entertainment ul.slides').each(function(){
									var newLeftPosition = parseInt($(this).css("left"),10) - slidesWidth;
									$(this).animate( { left: + newLeftPosition + 'px' }, 'slow' );
								});
								slidesCurrent++;
							}
							return false;
						});

						// click: pause
						Engine.sliders.entertainment.timeout = setTimeout(Engine.sliders.entertainment.slide,Engine.sliders.entertainment.time);

						$('#entertainment ul.paging li.pause a').toggle(function(){
							$(this).addClass('active');
							clearTimeout(Engine.sliders.entertainment.timeout);
							return false;
						},function(){
							$(this).removeClass('active');
							clearTimeout(Engine.sliders.entertainment.timeout);
							Engine.sliders.entertainment.timeout = setTimeout(Engine.sliders.entertainment.slide,Engine.sliders.entertainment.time);
							return false;
						});

					}
				}
			},
			// editors choice
			editors : {
				time : 20000,
				slide : function(){
					$('#editorsSlider ul.paging li.next a').trigger('click');
					Engine.sliders.editors.timeout = setTimeout(Engine.sliders.editors.slide,Engine.sliders.editors.time);
				},
				init : function(){
					// equal height
					var editorHeight =  0;
					$('#editorsSlider ul.slides li').each(function(){
						currentHeight = $(this).height();
						if(currentHeight > editorHeight){
							editorHeight = currentHeight;
						}
					});
					$('#editorsSlider ul.slides li').css('height',editorHeight+'px');

					// slider engine
					var editorsCurrent 		= 1;
					var editorsCount 		= $('#editorsSlider ul.slides li').size();
					var editorsWidth 		= $('#editorsSlider').width()/1;
					var editorsContainer 	= editorsCount * editorsWidth;

					if(editorsCount > 1){
						// cloning
						$('#editorsSlider div.slidesWrap').height(editorHeight+16).before('<ul class="paging"><li class="prev"><a href="./">&laquo;</a></li><li class="pause"><a href="./">pause</a></li><li class="next"><a href="./">&raquo;</a></li></ul>');
						$('#editorsSlider ul.slides li').clone().appendTo("#editorsSlider ul.slides").clone().appendTo("#editorsSlider ul.slides");

						// positioning
						var leftPosition = editorsWidth * editorsCount * -1;
						var fullWidth = editorsCount * editorsWidth * 3;
						$('#editorsSlider ul.slides').css({ position: "absolute", top: "0", left: leftPosition, width: fullWidth });

						$('#editorsSlider ul.paging li.prev a').click(function(){
							var position = parseInt($('#editorsSlider ul.slides').css("left"));
							if (position % editorsWidth == 0 && $('#editorsSlider ul.slides:animated').size() == 0){
								if(position >= -editorsContainer){
									$('#editorsSlider ul.slides').css('left',(position - editorsContainer));
									position = parseInt($('#editorsSlider ul.slides').css("left"));
								}
								$('#editorsSlider ul.slides').animate( { left: position+editorsWidth }, 350);
							}
							return false;
						});

						// click: next
						$('#editorsSlider ul.paging li.next a').click(function(){
							var position = parseInt($('#editorsSlider ul.slides').css("left"));
							if (position % editorsWidth == 0 && $('#editorsSlider ul.slides:animated').size() == 0){
								if(position <= -editorsContainer){
									$('#editorsSlider ul.slides').css('left',(position + editorsContainer));
									position = parseInt($('#editorsSlider ul.slides').css("left"));
								}
								$('#editorsSlider ul.slides').animate( { left: (position-editorsWidth) }, 350);
							}
							return false;
						});

						// click: pause
						Engine.sliders.editors.timeout = setTimeout(Engine.sliders.editors.slide,Engine.sliders.editors.time);

						$('#editorsSlider ul.paging li.pause a').toggle(function(){
							$(this).addClass('active');
							clearTimeout(Engine.sliders.editors.timeout);
							return false;
						},function(){
							$(this).removeClass('active');
							clearTimeout(Engine.sliders.editors.timeout);
							Engine.sliders.editors.timeout = setTimeout(Engine.sliders.editors.slide,Engine.sliders.editors.time);
							return false;
						});
					}

					// hover
					$('#editorsSlider ul.slides li a').hover(function(){
						$(this).parent('li').addClass('over');
					},function(){
						$(this).parent('li').removeClass('over');
					});
				}
			}
		}
	}

	// navigation
	Engine.navigation.keyboardAccessibility();
	//Engine.navigation.sectionChange(300);
	Engine.navigation.hoverClass();

	// article
	Engine.article.commentCounter();
	Engine.article.commentsComplainments();
	Engine.article.fontSize();

	// other
	Engine.other.tabbedContainers();
	Engine.other.searchValueLabel($('fieldset.searchBox span.mainInput input'),'Search');
	Engine.other.searchAdvancedInteraction();
	Engine.other.videosHover();
	Engine.other.iosFix();

	// specific
	Engine.specific.lightboxInit();
	Engine.specific.svToggler();

	// sliders
	Engine.sliders.entertainment.init();
	Engine.sliders.editors.init();

});

// NEWS TICKER

// Ticker startup
function startTicker() {

	// Define run time values
	theCurrentStory     = -1;
	theCurrentLength    = 0;

	runTheTicker();
}

// Ticker main run loop
function runTheTicker(){
	var myTimeout;

	// Go for the next story data block
	if(theCurrentLength === 0){
		theCurrentStory++;
		theCurrentStory		= theCurrentStory % theItemCount;
		theStorySummary		= theSummaries[theCurrentStory].replace(/&quot;/g,'"');
		theTargetLink		= theSiteLinks[theCurrentStory];
		thePrefix 	     	= "<span>" +theHours[theCurrentStory] + "</span> ";
	}

	// Stuff the current ticker text into the anchor

	var temp = '<li><a href="' + theTargetLink +'">';
	temp += thePrefix;
	temp += theStorySummary.substring(0,theCurrentLength);
	temp += whatWidget();
	temp += '</a></li>';
	$('div.breakingTicker ul').html(temp);

	// Modify the length for the substring and define the timer
	if(theCurrentLength != theStorySummary.length){
		theCurrentLength++;
		myTimeout = theCharacterTimeout;
	} else {
		theCurrentLength = 0;
		myTimeout = theStoryTimeout;
	}

	// Call up the next cycle of the ticker
	setTimeout(runTheTicker, myTimeout);
}

// Widget generator
function whatWidget(){
	if(theCurrentLength == theStorySummary.length){
		return '';
	}

	if((theCurrentLength % 2) == 1){
		return '_';
	} else {
		return '-';
	}
}

jQuery(document).ready(function($){
	if($('div.breakingTicker').size() > 0){
		theCharacterTimeout = 25;
		theStoryTimeout     = 5000;

		theSummaries 		= [];
		theHours 			= [];
		theSiteLinks 		= [];

		$('div.breakingTicker ul').addClass('loaded');

		$('div.breakingTicker ul li a').each(function(){
			theSummaries[theSummaries.length] = $(this).get(0).childNodes[1].nodeValue.replace(/^\s*|\s*$/g,"");
			theHours[theHours.length] = $(this).find('span').html();
			theSiteLinks[theSiteLinks.length] = $(this).attr('href');
		});

		theItemCount = theSummaries.length;

		startTicker();
	}
});


