/** 
 * @projectDescription	Auto trader media javascript, using jQuery.
 * @author Matt Hobbs matt.hobbs@harvestdigital.com
 * @version 0.1
 */

/**
 * Set jQuery into noConflict mode (MODx uses MooTools)
 */
var $j = jQuery.noConflict();

/** 
* Allow jQuery to fire the page 'onload'
* @id jQueryLoader
*/
$j(document).ready(function(){
	//Add a class to the body tag if JS is on.
	$j('body').addClass('hasJS');
	/**
	* All pages
	*/
	//The research popup
		var researchLinks = function(){
			var signInHTML = '<div id="signInBox"><div><h1><span>Document Repository<span></h1><a href="#" id="close">Close</a><form name="login" method="post" action="http://research.autotrader.co.uk:8081/login.php"><input type="hidden" value="language" name="en" /><input type="hidden" value="login" name="action"/><input type="hidden" value="" name="cookieverify"/><input type="hidden" value="" name="redirect"/><p class="descriptiveText">Enter your details below to login.</p><label for="username">Username</label><input type="text" name="username" id="username"/><label for="password">Password</label><input type="password" name="password" id="password"/><div class="form_actions"><input type="submit" value="login"/></div></form></div></div>';
			$j('a#signIn').click(function(){
				$j('body').append(signInHTML);
				$j('#close').click(function(){
					$j('body').find('#signInBox').fadeOut('slow',function(){
						$j(this).remove();
					});
					return false;
				});
				return false;
			});
		}();

	/**
	 * Homepage Javascript
	 */
	if($j('body').is('#homepage')){
		//Grab the 3 tabs of content for later use
		var publicEyeContent = $j('#publicEyeContent').html();
		var audienceContent = $j('#ourAudienceContent').html();
		var winStuffContent = $j('#winStuffContent').html();
		
		//Hide the unused boxes
		$j('#winStuff').hide();
		$j('#ourAudience').hide();
		
		//Remove the 2 corners from the original box 
		$j('#inThePublicEye b.tl').remove();
		$j('#inThePublicEye b.tr').remove();
		
		//Add the top nav tabs to (inThePublicEye)
		var tabsHTML = '<ul id="dynamicTabs">';
		tabsHTML += '<li id="inThePublicEyeTab"><a href="/" title="In the public eye" class="selected">In the public eye</a></li>';
		tabsHTML += '<li id="ourAudienceTab"><a href="/" title="Our audience">Our audience</a></li>';
		tabsHTML += '<li id="winStuffTab"><a href="/" title="Win stuff!">Win stuff!</a></li>';
		tabsHTML +=	'</ul>';
		$j('#inThePublicEye').prepend(tabsHTML);
		
		//Homepage ticker function
		var newsTicker = function(){
			var tickerDiv = $j('div.ticker');
			$j('p.ticker').hide();
			$j.get("/feed", function(data){
				var newsHTML = "<ul class='theNews'>";
				$j(data).find('item').each(function(){
					var anchorTitle = $j(this).find('title').text();
					var anchorLink = $j(this).find('link').text();
					var link = "<li><a href='"+anchorLink+"' title='"+anchorTitle+"'>"+anchorTitle+"</a></li>";
					newsHTML += link;
				});
				newsHTML += "</ul>";
				$j('div.ticker').append(newsHTML);
				var options = {
				    newsList: ".theNews",
				    startDelay: 100,
				    placeHolder1: " _"
				};
				$j().newsTicker(options);
			});
		};
		
		//Run the News Ticker
		newsTicker();
		
		//Homepage tabs click function
		$j('#dynamicTabs a').click(function(){
			//ID of the clicked li tab
			var clickedID = $j(this).parent().attr('id');
			
			//The function that fadesOut, swaps then fades in new content
			var tabContentSwap = function(selectedContent){
				//Fade out the old content
				$j('#publicEyeContent').fadeOut(function(){
					//Now swap, and fade in new content
					$j('#publicEyeContent').html(selectedContent).fadeIn(function(){
						$j(this).animate({opacity: 1.0}, 500, function(){
							
						});
					});
				});
				//Remove selected from all anchors
				$j('#dynamicTabs a').removeClass('selected');
				//Add selected to the clicked anchor
				$j('li#'+clickedID+'').find('a').addClass('selected');
			};
			//Depending on what was clicked, swap this content
			switch(clickedID){
				case 'inThePublicEyeTab':
					tabContentSwap(publicEyeContent);
					break;
				case 'ourAudienceTab':
					tabContentSwap(audienceContent);
					break;
				case 'winStuffTab':
					//tabContentSwap(winStuffContent);
					return false;
					break;
			}
		return false;
		});
		$j("#ourAudienceTab a").trigger("click");
	}
	
	/**
	 * Fairly generic expand / contract script. Varies depending on the body ID
	 * due to some changes in the template. Look for the 'switch' looking at
	 * bodyID.
	 */
	if ($j('body').is('#onSister') || $j('body').is('#onAdFormats') || $j('body').is('#ofSister')) {
		//ID of the page we are on.
		var bodyID = $j('body').attr('id');
		
		//Hide the content we don't need on page load
		$j('.toggleContent').hide();
		//Set the background image to a plus
		$j('.toggleLink').css({"background": "url('/assets/templates/atMediaAssets/images/adPlus.gif') no-repeat center left"});
	
		//Add the expand and collapse buttons if JS is available				
		var expandCollapseHTML = '<ul id="expandAndCollapse">';
		expandCollapseHTML += '<li><a title="expand all" id="expandAll" href="/">expand all</a></li>';
		expandCollapseHTML += '<li class="last"><a title="collapse all" id="collapseAll" href="/">collapse all</a></li>';
		expandCollapseHTML += '</ul>';
		
		//Insert the expand/collapse links after the PDF download link. 
		$j('.contentBox:eq(0)').before(expandCollapseHTML);
		
		//Click on page link, check to see if it is already expanded
		$j('.toggleLink').click(function(){
			var $this = $j(this).parent();
			var isExpanded = $this.hasClass("expanded");
			switch(isExpanded){
				case true: 
					collapseThisTrue($this);
					break;
				default:
					expandThisTrue($this);
					break;
			}
			return false;
		});
		
		/**
		 * Create a generic function that will expand whatever is passed to it
		 * @id expandThis
		 * @param {Object} jQel Expects the ad format link to be passed to it.
		 */
		var expandThisTrue = function(jQel){
			//Add the class expanded to the content box
			jQel.addClass('expanded');
			
			//Hide the image
			jQel.find('.contentImg').hide();
			
			//The CSS for the anchor
			var cssOn = {
	        	"background": "url('/assets/templates/atMediaAssets/images/adMinus.gif') no-repeat center left"
      		};
			//Find the link inside the contentBox, apply the CSS
			jQel.find('.toggleLink').css(cssOn);
			
			//Find the toggleContent, and show it
			jQel.find('.toggleContent').slideDown('slow',function(){
				$j(this).find('.contentImg').fadeIn();
			});
		};
		
		/**
		 * Create a generic function that will collapse whatever is passed to it
		 * @id collapseThis
		 * @param {Object} jQel Expects the ad format link to be passed to it.
		 */
		var collapseThisTrue = function(jQel){
			jQel.removeClass('expanded');
			var cssOff = {
        		"background": "url(/assets/templates/atMediaAssets/images/adPlus.gif) no-repeat center left"
  			};
			//Apply the cssOff
			jQel.find('.toggleLink').css(cssOff);
			//Slide up the sibling
			
			jQel.find('.contentImg').fadeOut(function(){
				$j(this).parent().slideUp('slow');
			});
		};
		
		/**
		 * Both the expand and collapse function. 
		 */
		$j('#expandAndCollapse a').click(function(){
			var clickedID = $j(this).attr('id');
			switch(clickedID){
				case 'expandAll':
					$j('.contentBox').each(function(){
						var isExpanded = $j(this).hasClass("expanded");
						switch(isExpanded){
							case false:
								//Expand the selected content box
								expandThisTrue($j(this));
								break;
						}
					});
					return false;
				case 'collapseAll':
					$j('.contentBox').each(function(){
						var isExpanded = $j(this).hasClass("expanded");
						switch(isExpanded){
							case true:
								//Collapse the selected content box
								collapseThisTrue($j(this));
								break;
						}
					});
					return false;
			}
		});
		
		//Depending on the body id, select what nav link to use
		var domToggle;
		switch(bodyID){
			case 'onSister':
				domToggle = 'sideNav16 a';
				break;
			case 'onAdFormats':
				domToggle = 'sideNav10 a';
				break;
			case 'ofSections':
				domToggle = 'sideNav19 a';
				break;
			case 'ofSister':
				domToggle = 'sideNav25 a';
				break;
		}
		
		/**
		 * Generate the subNav from the DOM, add it underneath the links
		 */
		$j('#'+domToggle).toggle(function(){
			var cssOn = {
	        	"background": "url(/assets/templates/atMediaAssets/images/secNavMinus.gif)  0 4px no-repeat",
      			"text-decoration": "underline"
			};
			$j(this).css(cssOn);

			/**
			 * FORK: onSister looks at the image alt attribute, onAdFormats looks at the link text.
			 */
			var navHTML;
			//For template wf004
			if(bodyID === "onSister" || bodyID === "ofSections" || bodyID === "ofSister"){
				navHTML = "<ul class='subNav'>";
				$j('.toggleLink').each(function(){
					navHTML += '<li><a href="/" title="' + $j(this).find('img').attr('alt')+ '">' + $j(this).find('img').attr('alt') + '</a></li>';
				});
				navHTML += '</ul>';
			//For template wf003
			} else if(bodyID === "onAdFormats"){
				navHTML = "<ul class='subNav'>";
				$j('.toggleLink').each(function(){
					navHTML += '<li><a href="/" title="' + $j(this).text()+ '">' + $j(this).text() + '</a></li>';
				});
				navHTML += '</ul>';
			}
			
			//Only allow 1 set of subNav's to be added.
			if($j(this).siblings('ul.subNav').length === 0){
				$j(this).after(navHTML);
			} else {
				$j('ul.subNav').slideDown('slow');
				return false;
			}
			$j('ul.subNav').hide().slideDown('slow');
			
			/**
			 * FORK: Do something when you click on the subnav. onSister looks for alt
			 * text, onAdFormats looks at anchor text.
			 */
			//For template wf004
			if (bodyID === "onSister" || bodyID === "ofSections" || bodyID === "ofSister") {
				$j('ul.subNav li a').click(function(){
					var ourText = $j(this).text();
					var found = $j(".toggleLink img[alt="+ourText+"]");
					
					var contentContainer = found.parent().parent();
					var isExpanded = contentContainer.hasClass("expanded");
					if (isExpanded) {
						//Collapse selected anchor
						collapseThisTrue(contentContainer);
					}
					else {
						//Expand selected anchor
						expandThisTrue(contentContainer);
					}
					return false;
				});
			//For template wf003
			} else if(bodyID === "onAdFormats"){
				$j('ul.subNav li a').click(function(){
					var found = $j(".toggleLink:contains('" + $j(this).text() + "')");
					var isExpanded = found.parent().hasClass("expanded");
					if (isExpanded) {
						//Collapse selected anchor
						collapseThisTrue(found.parent());
					}
					else {
						//Expand selected anchor
						expandThisTrue(found.parent());
					}
					return false;
				});
			}
		},
		function(){
			//The toggle function, leaves the subNav attached to the DOM
			var cssOn = {
	        	"background": "url(/assets/templates/atMediaAssets/images/secNavPlus.gif)  0 4px no-repeat",
      			"text-decoration": "none"
			};
			$j(this).css(cssOn);
			$j('ul.subNav').slideUp('slow');
		});
		
		/**
		 * FORK: Simulate a user click on page entry.
		 */
		switch(bodyID){
			case 'onAdFormats':
				$j('#sideNav10 a').trigger('click');
				break;
			case 'onSister':
				$j('#sideNav16 a').trigger('click');
				break;
			case 'ofSections':
				$j('#sideNav19 a').trigger('click');
				break;
			case 'ofSister':
				$j('#sideNav25 a').trigger('click');
				break;
		}
	}
});
