var Engine = null;

jQuery(document).ready(function($){

	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 = 'font-';
					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'));
					$('#article div.body > :not(div)').addClass('font-' + value);
					return false;
				});
*/
				if($('#article').length && $.cookie('fontsizeAAA') != 'null')
					$('#article .body > :not(div)').addClass('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;
						});

					}
				}
			},

			// latestvideos choice
			latestvideos : {
				time : 5000,
				slide : function(){
					$('.latest-videos ul.paging li.next a').trigger('click');
					Engine.sliders.latestvideos.timeout = setTimeout(Engine.sliders.latestvideos.slide,Engine.sliders.latestvideos.time);
				},
				setupLatestVideo: function(json) {

					// Work out carosel location from channel Guid location
					var videoCaroselElement = $("#octopus-mt-channel-guid").parent();

					// Remove unneeded channel guid
					$("#octopus-mt-channel-guid").remove();

					//Thumbnail height and width settings
					var latestvideosThumbnailWidth 	= 135;
					var latestvideosThumbnailHeight = 75;

					videoCaroselElement.parent().attr("id","octopus-latest-videos");
					var out = [], o = -1;

					//Loop through each video asset, and append each item to an array.
					$(json.Assets).each(function(i){
						var firstChild = (i == 0) ? "class=\"first\" " : "";
						out[++o] = "<li "+firstChild+"><a href=\"#\"><img title=\""+this.Title+" - "+this.Description+"\" src=\"http://ob.octopusmediatechnology.com/thumbnails/independent/defaultthumbnail.ashx?assetguid="+this.AssetGuid+"&width="+latestvideosThumbnailWidth+"&height="+latestvideosThumbnailHeight+"\" alt=\""+this.Title+"\" onclick=\"OctopusMT.OpenFlashWindow('"+this.AssetGuid+"','octopus-latest-videos','"+json.ChannelGuid+"');return false;\" /></a><span>"+this.Title+"</span></li>";
					});

					videoCaroselElement.append(out.join(''));

					// slider engine
					var latestVideoDIV = videoCaroselElement.parent().parent();
					var slidesLI = $('li', videoCaroselElement);

					var latestvideosCurrent 	= 1;
					var latestvideosCount 		= $('li', videoCaroselElement).size();
					var latestvideosWidth 		= latestVideoDIV.outerWidth() / 3;
					var latestvideosContainer 	= latestvideosCount * latestvideosWidth;

					if(latestvideosCount > 3){
						// cloning
						videoCaroselElement.parent().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>');
						slidesLI.clone().appendTo(videoCaroselElement).clone().appendTo(videoCaroselElement);

						// positioning
						var leftPosition = latestvideosWidth * latestvideosCount * -1;
						var fullWidth = latestvideosCount * latestvideosWidth * 3;

						//$('.latest-videos ul.slides').css({ position: "absolute", top: "0", left: leftPosition, width: fullWidth });
						videoCaroselElement.css({ position: "absolute", top: "0", left: leftPosition, width: fullWidth });

						$('ul.paging li.prev a', latestVideoDIV).click(function(){
							//var position = parseInt($('.latest-videos ul.slides').css("left"));
							var position = parseInt(videoCaroselElement.css("left"));
							if (position % latestvideosWidth == 0 && $('.latest-videos ul.slides:animated').size() == 0){
								if(position >= -latestvideosContainer){
									$('.latest-videos ul.slides').css('left',(position - latestvideosContainer));
									position = parseInt($('.latest-videos ul.slides').css("left"));
								}
								$('.latest-videos ul.slides').animate( { left: position+latestvideosWidth }, 350);
							}
							return false;
						});

						// click: next
						$('ul.paging li.next a', latestVideoDIV).click(function(){
							//var position = parseInt($('.latest-videos ul.slides').css("left"));
							var position = parseInt(videoCaroselElement.css("left"));

							if (position % latestvideosWidth == 0 && $('.latest-videos ul.slides:animated').size() == 0){
								if(position <= -latestvideosContainer){
									$('.latest-videos ul.slides').css('left',(position + latestvideosContainer));
									position = parseInt($('.latest-videos ul.slides').css("left"));
								}
								$('.latest-videos ul.slides').animate( { left: (position-latestvideosWidth) }, 350);
							}
							return false;
						});

						// click: pause
						Engine.sliders.latestvideos.timeout = setTimeout(Engine.sliders.latestvideos.slide,Engine.sliders.latestvideos.time);

						$('.latest-videos ul.paging li.pause a').toggle(function(){
							$(this).addClass('active');
							clearTimeout(Engine.sliders.latestvideos.timeout);
							return false;
						},function(){
							$(this).removeClass('active');
							clearTimeout(Engine.sliders.latestvideos.timeout);
							Engine.sliders.latestvideos.timeout = setTimeout(Engine.sliders.latestvideos.slide,Engine.sliders.latestvideos.time);
							return false;
						});
					}

					// hover
					$('.latest-videos ul.slides li a').hover(function(){
						clearTimeout(Engine.sliders.latestvideos.timeout);
						$(this).parent('li').addClass('over');
					},function(){
						Engine.sliders.latestvideos.timeout = setTimeout(Engine.sliders.latestvideos.slide,Engine.sliders.latestvideos.time);
						$(this).parent('li').removeClass('over');
					});
				},
				init : function(){
				        channelGUID = $("#octopus-mt-channel-guid").html();
						$.ajax({url: "http://ob.octopusmediatechnology.com/API/Independent/channels.svc/json/Contents", dataType: "script",type: "GET", cache: true, callback: null, data:{channelGuid:channelGUID,sortOrder:'AddChannel',maxRecords:'10',method:'Engine.sliders.latestvideos.setupLatestVideo'}});
				}
			},

			// editors choice
			editors : {
				time : 10000,
				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()/4;
					var editorsContainer 	= editorsCount * editorsWidth;

					if(editorsCount > 4){
						// 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.searchAdvancedInteraction();
	Engine.other.videosHover();
	Engine.other.iosFix();

	// specific
	Engine.specific.lightboxInit();
	Engine.specific.svToggler();

	// sliders
	Engine.sliders.entertainment.init();
	if ($("#octopus-mt-channel-guid").length)
		Engine.sliders.latestvideos.init();
	Engine.sliders.editors.init();


	$('.refine-search > ul').each(function() { $(this).find('li:gt(4)').hide(); });
	$('.refine-search a.more').show().click(function() { $(this).toggleClass('more-alt').parent().prev('ul').find('li:gt(4)').toggle(); return false; });

	$("#topSearch input[type='text'],#footerSearch input#s03").focus(function() { $(this).addClass("focus"); }).blur(function() { if (!this.value) $(this).removeClass("focus"); });

});

// 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();
	}

	$('ul.article-tools')
		.find('li.share>a').click(function()
		{
			var $shareLinks = $("body>.share-links");
			if (!$shareLinks.length)
				$shareLinks = $(this).parent().find(".share-links").clone(true).appendTo("body");

			var w = 20;
			$shareLinks.css({ visibility: "hidden", display: "block" }).find("ul").each(function() { w += $(this).width() + 20; });

			var pos = $(this).offset(), $column = $("#mainColumn"), columnPos = $column.offset();
			$shareLinks.css({ visibility: "visible", width: w + "px", left: (columnPos.left - 10 + (($column.width() - w) / 2)) + "px", top: (pos.top + 20) + "px" });
			return false;
		}).end()
		//.find('li.print a').click(function(){ window.print(); return false; }).end()
		.not(".article-tools-no-text-size").append('<li class="fonts">Text Size <ul><li><a href="#font-normal" class="a">Normal</a></li><li><a href="#font-large" class="aa">Large</a></li><li><a href="#font-xlarge" class="aaa">Extra Large</a></li></ul></li>').end()
		.find('li.fonts a').click(function(){
			switch ($(this).attr('class')) {
				case 'aaa': var value = 'aaa'; break;
				case 'aa': var value = 'aa'; break;
				default: var value = 'a'; break;
			}
			$.cookie('fontsizeAAA', value, { expires: 90, path: '/'});
			$('#article .body>:not(div)').removeClass('font-a').removeClass('font-aa').removeClass('font-aaa').addClass('font-' + value);
			return false;
		});

	$(".share-links").find("a.close").click(function() { $(this).parents(".share-links").hide(); return false; });
	$(".sports.strip #DIVcontent").toggle(function() { $("#secondaryColumn").css({ paddingTop: "215px" }); }, function() { $("#secondaryColumn").removeAttr("style"); });

	if ($.browser.msie && $.browser.version < 7)
		$('ul.article-tools > li.share').bind('mouseenter mouseleave', function() { $(this).toggleClass('hover'); });

});

document.write('<link rel="stylesheet" type="text/css" media="screen" href="/independent.co.uk/styles/javascript.css" />');
