$=jQuery;

// *************************************************
//	jjFeatured Widget
//	
// 		created by James Jackson for Phandroid.com
//		                             iSource.com
//   
//	... and anywhere else Rob deems necessary!  This
//	all belongs to him.
//
// *************************************************

$(document).ready(function() {

	// These are the initial variables that I set in order to operate the Featured Articles
	// widget, the Newsletter Popup, etc.
	
	slideshowDelay=5;	// Featured Widget animation delay between slides, in seconds.
						// Decimals work (e.g. 4.25)
						
	$(".colorbox").click(function() {

		$(this).colorbox({
			href: $(this).attr("alt"),
			open: true
			
		});
		
	});
	
	$("#shadow").css("height", $(document).height()).hide();		// Creates the dark, low opacity
	$("#jjShadow").css("height", $(document).height()).hide();	// overlay for the Newsletter
																															// popup.
	$(".inlinePopup").each(function(){
		
		thisPopup=$($(this).attr("href"));
		thisPopup.html("<div class='innards'><div class='closeButton'></div>"+thisPopup.html()+"</div>");
		
		$(".closeButton").css({ "marginLeft":(thisPopup.width()-50)+"px","zIndex":500 });
		
		$(this).click(function(){
			
			thisPopup=$($(this).attr("href"));
			thisPopupInnards=thisPopup.children(".innards");
			
			alert(thisPopupInnards.children(".closeButton").css("marginLeft"));
		
			if ($.browser.msie) { $("#jjShadow").css("width",$(window).width()+"px"); }
			$("#jjShadow").fadeIn("slow");
		
			popUpLeft=(($(window).width()/2)-(thisPopup.width()/2));
			popUpTop=(($(window).height()/2)-(thisPopup.height()/2));
		
			thisPopup.css({
			
				left: popUpLeft,
				top: popUpTop
															  
			});
			
			thisPopup.fadeIn("fast");
		
			return false;
										 
		});
	});
	
	$(".jjFeatured").each(function(){	// This only launches if an element with
								   		// class="jjFeatured" is present on the page.
										
		$jjBox=$(this).children(".jjFBox");	// From now on, anyhwere you see $jjBox, it will
											// refer to the container *just* inside .jjFeatured.
		$jjBli= $jjBox.children("ul").children("li");	// jQuery uses less memory and runs
														// more quickly if you assign the elements
		$(this).attr("rel",0);	// Sets the initial		// to variables, and then refer to the
								// tab to Home 			// objects in this way.
		
		$index=0;	// There are a few loops we run, so let's set the starting position at 0.
		
		$jjBli.each(function(){	// For each <li> within .jjBox...
							 
			$jjImgObject=$(this).children("a").children("img").eq(0);	// <a> <img> is put into
			$jjAnchor=$(this).children("a");							// a variable, as is the
																		// <a> itself.
			var $jjIMG = [];	// Shortcut to make $jjIMG an array to hold information about
								// the image, like the SRC, WIDTH, HEIGHT, etc.
								
			$jjIMG["title"]=$jjImgObject.attr("title"); 	// The caption is saved in ["title"]
			$jjIMG["src"]=$jjImgObject.attr("src");			// The image location is in ["src"]
			$jjIMG["width"]=$jjImgObject.attr("width");		// The width is saved in ["width"]
			$jjIMG["height"]=$jjImgObject.attr("height");	// The height is saved in ["height"]
			
			// The following lines are setup in order to keep everything relative.  This way,
			// each <li> can affect elements completely outside of it, but relative to the
			// specific item.  For example, in order ot keep the HTML clean for the box,
			// Two <div>'s are appended around the image, outside of each <li>.
			
			// This is why there are two parent()'s in a row.  It goes up two levels in the DOM.
			
			$(this).parent().parent().prepend("<div id=\"jjIMG"+$index+"\" class=\"jjIMG\"></div>").children(".jjIMG").append("<div class=\"jjIMGblock\"></div>");
			
			// Alright, now we've created these two <div>'s (in order to swap that photo when
			// the "Current Featured Item" is selected.
			
			// Let's grab the most recently created one, and do the following:
			
			//	1. Hide it while it's being rendered, so users don't see it flopping around.
			// 	2. Set the image for *this* item as the image to the left.
			// 	3. Make sure the width and height are accurate.
			// 	4. Force it to remain in the top left corner at all times.
			// 	5. Throw a blue, semi-transparent border over the image to make it similar to
			// 	   the PSD.
			//  
			//  This is done in the respective order below:
			
			$("#jjIMG"+$index).css({
				
				display: "none",
				background: "url('"+$jjIMG["src"]+"') top left no-repeat",
				width: $jjIMG["width"],
				height: $jjIMG["height"],
				position: "absolute"
			}).children(".jjIMGblock").css({
				
				border: "10px solid #3e758b",
				opacity: .5,
				display: "block",
				width: "130px",
				height: "130px"
				
			});
			
			// IE sucks.  If the suer is in IE, then apply a couple of width/height tweaks.
			
			if ($.browser.msie) { $("#jjIMG"+$index).children(".jjIMGblock").css({
				
				width: "150px",
				height: "150px"
				
			}); }
			
			// Thios is a debug line that can be used to verify the HTML contents of each item.
			
			// 		alert($("#jjIMG"+$index).html());

			$(this).append("<a href=\""+$jjAnchor.attr("href")+"\" rel=\"jjIMG"+$index+"\"><span>"+$jjIMG["title"]+"</span></a>");						// Apply headline, and make it a link.  This renders the
									// <a> in the HTML obscelete, now that we have the information
									// we need from it.  Sooo...
			
			$jjAnchor.remove(); 	// Anhilliates the original <a>.  ZAP-BOOM!
			
			$(this).hover(function() { resetTimer();highlightFeatured($(this))}, function() {resetTimer(); }); 	// If you hover over a <li>, it automatically stops the auto-rotate.
					// Once you hover *off* of the <li>, it resumes it.
			
			// All's well that ends well, right?  This item is done.  Onto the next!
			
			$index++;	// $index is increased by one, so we're on to the next <li>!
							 
		}); // Loops, or (if we've cycled through every single <li> under .jjFeatured then go on.
		
		$(".jjFeatured").children(".jjFBox").attr("rel",0);	// We're exploiting the rarely-used
															// rel="" attribute in order to store
															// this <a>'s position in line.  This
															// will come in handly later.
		
		// This selects the top Featured article by default.
		
		highlightFeatured($jjBli.eq(0));
	   
	   // That's it for their creation.  Now, we need to change what happens when you hover over
	   // the entire jjFeatured Box, itself.
	   
	   // Nothing.  Absolutely nothing will happen.  However, when you hover *out* of the box,
	   // it resumes the Auto-Rotation.                   See?  ------------v
	   
	   setTimeout("startSlideshow(slideshowDelay);",5000); // Start the Auto-Rotation.
														// If you don't want it to rotate, put
														// these two characters in front of
														// this line: //
														//
														// Like this:
														//
														//	//setTimeout("startSlideshow...
	   
	}).hover(function(){},function() { resetTimer();setTimeout("startSlideshow(slideshowDelay);",5000); });
	
	// *********************************************************************************
	// jjTrendBox -- Not currently in use, but may be in the future.  ARCHIVED: 10/19/10
	// *********************************************************************************
	
	/*$jjTBindex=0;
	
	$(".jjTrendbox").each(function(){
		
		// Set some local constants.
		
		$jjTBthumbs=$(this).children("ul").children("li").children("a").children("img");
		$jjTBanchors=$(this).children("ul").children("li").children("a");
		
		$(this).append("<div id=\"jjTBimg"+$jjTBindex+"\" class=\"jjTBimg\"></div>");
		
		$thisTBimg=$(this).children("#jjTBimg"+$jjTBindex);
		
		//alert($jjTBthumbs.eq(0).attr("src"));
		
		$thisTBimg.css({
													
			width: $(this).css("width"),
			height: $(this).css("height"),
			background: "url('"+$jjTBthumbs.eq(0).attr("src")+"') center center no-repeat"
													
		});
		
		$thisTBimg.append("<div id=\"jjTBborderBox"+$jjTBindex+"\" class=\"jjBorderBox\"></div>");
		
		$thisTBimg.append("<div class=\"jjNavArrows\"><a href=\"#\" class=\"rightArrow\"></a><a href=\"#\" class=\"leftArrow\"></a></div><div class=\"jjTBbBContent\"><div class=\"jjCont\">"+$jjTBthumbs.eq(0).attr("title")+"</jjCont></div>");
		
		$thisTBimg.children(".jjNavArrows").children(".leftArrow").css("opacity",0.5);
		
		numPhotos=$(this).children("ul").children("li").length;
		$thisTBimg.attr("rel",numPhotos)
		
		navDots="";
		
		for(disPhoto=0;disPhoto<numPhotos;disPhoto++){
			
			navDots+="<img src=\"http://www.isource.com/images/nav_dots_blue_off.png\" width=\"12\" height=\"12\">";	
			
		};
		
		$thisTBimg.children(".jjTBbBContent").append("<div class=\"navDots\">"+navDots+"</div>");
		
		$thisTBimg.children(".jjTBbBContent").children(".navDots").children("img").css("opacity",0.5).eq(0).css("opacity",1).attr("src","http://www.isource.com/images/nav_dots_blue.png");
		
		// Making blue dots clickable.
		
		$currentDot=0;
		
		$thisTBimg.children(".jjTBbBContent").children(".navDots").children("img").each(function(){
			$(this).attr("rel",$currentDot).css("cursor","pointer").click(function(){
				
				$(".jjTrendBox").attr("rel",($(this).attr("rel")));
				runSlides($(this));	
				return false;
								   
			});
			
			$currentDot++;
			
		});
		
		$thisTBimg.children(".jjTBbBContent").fadeIn("slow");
		
		// took out: border: "10px solid #000",
		
		$thisTBimg.children("#jjTBborderBox"+$jjTBindex).css({
													
			width: ($thisTBimg.css("width").substr(0,($thisTBimg.css("width").length)-2)-20),
			height: ($thisTBimg.css("height").substr(0,($thisTBimg.css("height").length)-2)-15),
			opacity: 0
													
		}).parent().hover(function(){
			
			
			$(this).children(".jjTBbBContent").css({ background: 'url("http://www.isource.com/images/black_85.png") top left repeat-x'});
			/*$(this).children(".jjBorderBox").animate({
			
				opacity: .25
							
			});
			
		},function(){
			
			$(this).children(".jjTBbBContent").css({ background: 'url("http://www.isource.com/images/black_85.png") top left repeat-x'});
			/*$(this).children(".jjBorderBox").animate({
			
				opacity: 0
							
			});
			
		});
		
		$(this).attr("rel","0");
		
		//$thisTBimg.children(".jjTBbBContent").children(".jjCont").children(".navDots")
		
		$thisTBimg.children(".jjNavArrows").children(".rightArrow").click(function() {

			$(".jjTrendBox").attr("rel",(parseFloat($(".jjTrendBox").attr("rel"))+1));
			runSlides($(this));	
			return false;
																				   
		});
		
		$thisTBimg.children(".jjNavArrows").children(".leftArrow").click(function() {

			$(".jjTrendBox").attr("rel",(parseFloat($(".jjTrendBox").attr("rel"))-1));
			runSlides($(this));	
			return false;
																				   
		});
								   
	$jjTBindex++; });*/ // End ARCHIVE of Trend Box. 
	
// *************************************************
//	The Newsletter Popup
//   By James Jackson for Phandroid.com - Oct. 2010
//	                      iSource.com
// *************************************************
	
	$("#newsletterPopup").click(function(){ // Yay!  Someone clicked on the Newsletter link!
		
		// IE sucks.  If the user is on IE, then make sure the Shadow fits.		
		if ($.browser.msie) { $("#shadow").css("width",$(window).width()+"px"); }
		
		// Ahhh... back to regular, cross-compatibility.  Make the #shadow element (a big,
		// semi-transparent black box that shades out the rest of the site) fade in slowly.
		
		$("#shadow").fadeIn("slow"); 	// Change to "fast" or enter a millisecond value to affect
									 	// how the shadow animates.	
	
		$("#newsletterContent").fadeIn("fast"); 	// Then, fade in the Newsletter popup.
													// The HTML for this element is located
													// within the HTML page itself.  It's inline,
													// found at <div id="newsletterContent">
		
		// Some quick halving, here, in order to put the Newsletter Popup at the very center of
		// the monitor.  The forumla, by the way, is:
		//
		// 		   1/2 the screen width
		//		-  1/2 the popup width
		//		------
		//		 the left side of the popup
		//
		// Same goes for height!
		newsletterLeft=(($(window).width()/2)-($("#newsletterBG").width()/2));
		newsletterTop=(($(window).height()/2)-($("#newsletterBG").height()/2));
		
		// IE sucks.  MORE IE TWEAKS.  In this case, it's making sure the left/top of the element
		// goes to the right place, as well as the container inside of it.
		
		$("#newsletterContent").css({
			
			left: newsletterLeft,
			top: newsletterTop
															  
		}).find("#newsletterBG").css({
			
			left: newsletterLeft,
			top: newsletterTop
			
		});
		
		// All done with the popup.  This makes it so that the <a> used to make the popup
		// happen doesn't actually go anywhere (not even the top of the page).
		
		return false;
										 
	});
	
	// The user is finished and has clicked on the "Close" button.
	
	$("#newsletterContent #closeButton").click(function(){
	
		// Hide the Newsletter Popup IMMEDIATELY.
	
		$("#newsletterContent").css("display","none");
		
		// Fade out the shadow, slowly.  It makes for a smoother transition.
		
		$("#shadow").fadeOut("slow");
												   
	});
	
	// End of Newsletter Popup code.
	
	// Here are some various bits of Javascript that I've used throughout the layout.  Most of
	// this code is inter-changable between iSource.com and Phandroid.com, but not all of it.
	//
	// In this, the iSource.com version of this script, there are no calls, here, to any Phone
	// pages (obviously), but there are some other nifty snippets that I still like to use.
	
	// This does a quick job taking the right sidbar off of any page, simply by adding
	//		
	//		"noSidebarPlease"
	//
	// to the CLASS of the <div id="temp_Content"> element.

	if($(".noSidebarPlease").length>0) {
		
		$(".noSidebarPlease").parent().css({ backgroundImage: "none",width: "100%" });	// Remove sidebar from bg-img
		
		$("#temp_Footer").addClass("noSidebarFooter");									// Render CSS for footer
																																		// with no sidebar.
		
	}
	
	// Handies scripting.  Not being used as of November 2011.
	
	if($("#handiesWrapper").length>0) {

		/* $("#ratings").stars({ cancelShow: false, starWidth: 28, split: 2,callback: function(ui,type,value){
		
		    currentPhone=$(".handies_header_picture img").attr("title");
		    
		    $.getJSON(
			"http://phandroid.com/phones/stars/"+currentPhone+"/"+value,
			function(data){ 
			    if(data.status == 0){
				document.location = "http://androidforums.com/usercp.php";
			    }else{
			    }
			});
		} });
		
	        currentPhone=$(".handies_header_picture img").attr("title");
		$.getJSON("http://phandroid.com/phones/stars/user/"+currentPhone,
			  function(data){
			      $("#ratings").stars("select",data.stars);
			  });*/
}	

	// This is for the Holiday Gift Guide.
	
	// Initially, this will only launch this code if there is an element present with the id of, "holidayContent".

	if($("#holidayContent").length>0) {
		
		$("#temp_Header").attr("title","'"+$("h1#pageTitle").html()+"'");		
		if($("h1#pageTitle").html()!="Holiday Gift Guide") {
			$("h1#pageTitle").css("display","block");
			$("#pageContent").addClass("individual");
		}
		
	}
		
		// End of Holiday Gift Guide code.
		
		$(".aligncenter").wrap("<center></center>");	// This is to dynamically center items.  It wraps them in center tags.

		$(".handieFooter .relatedLinks ul li").each(function(){
			
			if($(this).find("a").html().length<1) { $(this).css("display","none"); }
			
		});	

		$(".handieFooter .relatedLinks ul li").each(function(){
			
			if($(this).find("a").html().length<1) { $(this).css("display","none"); }
			
		});
		
		if($(".handieFooter .phoneInfo a h3").length>0) {
		
			$("#allNavs").attr("title",$(".handieFooter .phoneInfo a h3").eq(0).html().length);
		
			$(".handieFooter .phoneInfo a h3").each(function() {
			
				if($(this).html().length>17) { $(this).css("font-size","24px"); }
			  
				$("#allNavs").title($("#allNavs").title()+" / "+$(this).html().length);
			
			});
			
			$("#allNavs").attr("title",$(".handieFooter .phoneInfo a h3").eq(0).html().length);
			
		}
		
		if($("#newsletterForm div").length>0) {
		
			var nFtext=$("#newsletterForm div").eq(0);
		
			if(nFtext.html().length>17) {
				//nFtext.css({ fontSize: 10, whiteSpace: "nowrap" });
				nFtext.html("Stay Tuned!");
			}
			
		}
		
		if($("#topTopAd").length>0) { $("#topTopAd").width($(window).width()); }

				// This is the script that automatically creates the navigation for the Holiday Gift Guide index.
		
		var sections = $(".holidayTable tr td h3 strong");	// This stores each section's title into an Array.
		var sectionNav = new Array();												// Each section title will be in this array.
		var sectionLinks = new Array();										// This will give each section an anchor[name=#]
		var sectionNumber = 0;															// Section number, for keeping track of index.
		var sectionWidth = Math.round(490/sections.length);	// Fractional widths, so each button fits.
		
		// Only continue if the page sections exist!
		
		if(sections.length>0) {
			
			// For each section...
			
			sections.each(function(){
				
				thisSection = $(this);			
				sectionNav.push(thisSection.html());
				sectionLinks.push($(".holidayTable").eq(sectionNumber).find(".readMoreLink a").attr("href"));
				
				sectionNumber++;
				
			});
			
			var fullNav = "<div id=\"fullNav\"><ul>";
		
			for(s=0;s<sectionNav.length;s++) {
				
				fullNav+="<li style=\"width: "+(sectionWidth+4)+"px;\"><a href=\""+sectionLinks[s]+"\" style=\"width: "+sectionWidth+"px;\">"+sectionNav[s]+"</a></li>";
				
			}
			
			fullNav+"</ul></div>";
				
			$("#holidayGuideNav").prepend(fullNav);
			
		}

//Motorola droid razr maxx
//012345678901234567890123456789

	if($("#phonesections ul li li span")) {
		$("#phonesections ul li li span").each(function(){
		
			if($(this).html().length>20){
				$(this).css({
					fontSize: "10px"	
				}).attr("title","smaller");
			}
			
		});
	}

	// This is the end of the initial, document.ready().
	
});

// ****************************************************************************
// 	More legacy, TrendBox code.  This will be needed someday -- do not delete!
// ****************************************************************************

/*

function runSlides(elementObject){
		
			$this=elementObject;
		
			$currentSlide=$(".jjTrendBox").attr("rel");
			$totalSlides=($(".jjTrendBox .jjTBimg").attr("rel")-1);
			
			$arrows=$(".jjTrendBox .jjTBimg .jjNavArrows");
			
			if($currentSlide>$totalSlides) { $currentSlide=0; }
			if($currentSlide<0) { $currentSlide=$totalSlides; }

			// Reset Arrows 
			//
			// ** NOTE: Arrow fading functionality removed, this code is archived.
			
			/*if($currentSlide==$totalSlides) {
				
				$arrows.children(".rightArrow").css("opacity",0.5);
				$arrows.children(".leftArrow").css("opacity",1);
				
			} else {
				
				$arrows.children(".rightArrow").css("opacity",1);
				$arrows.children(".leftArrow").css("opacity",1);
				
			}
			
			if($currentSlide==0) {
			
				$arrows.children(".rightArrow").css("opacity",1);
				$arrows.children(".leftArrow").css("opacity",0.5);
				
			}*//*

			$thisTBimg.css("background","url('"+$jjTBthumbs.eq($currentSlide).attr("src")+"') top left no-repeat");
			$thisTBimg.children(".jjTBbBContent").children(".jjCont").html($jjTBthumbs.eq($currentSlide).attr("title"));
			$(".jjTrendBox").attr("rel",$currentSlide);
			
			//alert($(".jjTrendBox .jjTBimg").html());
			
			$(".jjTrendBox .jjTBimg").children(".jjTBbBContent").children(".navDots").children("img").animate({ opacity: 0.5 }).attr("src","/images/nav_dots_blue_off.png").eq($currentSlide).animate({ opacity: 1 }).attr("src","/images/nav_dots_blue.png");
																				   
		}*/
		
function highlightFeatured(elementObject) {
	
	// The function call for this passes on the current element in the DOM, which is great
	// for locating adjacent elements.  We're gonna toss it into $this, which is very similar
	// to jQuery's $(this).  Efficiency!
	$this=elementObject;
	
	// Remove the little white carrot that sticks over the left side.	
	if($("#arrowLeft").length) { $("#arrowLeft").css("display","none"); }

	// Remove all images, just in case.
	for(ii=0;ii<5;ii++) { $("#jjIMG"+ii).css("display","none"); }
		
	// Add the arrow to the appropriate Featured article tab.
	$this.parent().parent().children("#arrowLeft").css("display","block");
				
	// Uncomment this to see a debug alert that verifies the current element's parent().
	// alert($(this).parent().html());
				
	// Now, let's make sure that arrow is in the right spot.  This positions it on the corrent
	// vertical plane, as well as to just the left of the tab's visibility.
	
	//alert($this.position().left);
	
	$("#arrowLeft").css({
		/** /// brakes featured articles on phandroid, ~V			
		left: ($this.position().left+142),
		top: $this.position().top+2
		/**/							
	});
	
	// Here, we're resetting all the tabs so that there aren't any stragglers.
	
	$this.parent().children("li").children("a").each(function(){
		
		$(this).removeClass("tab_highlighted");				
						
	});	
				
	// NOW.  Let's finally make the current tab highlighted!
	
	// Notice the $this, which makes this whole thing soooo much easier to select... JUST ONCE.
	$this.children("a").addClass("tab_highlighted");
	
	// ... that makes this whole script run faster and take less memory.  EFFICIENCY!
	
	$thisREL=$this.children("a").attr("rel");
	$thisNum=$thisREL.substr(5,6);	// Check it: each of these anchor elements carries its
								 	// position within its REL tag.  We'll use this to grab
									// the correct Featured article thumbnail.  EFFICIENCY!
									
			//  v This, here, is that number.
	$("#jjIMG"+$thisNum).fadeIn("fast"); // Let's reveal that new photo!
	$(".jjFeatured").children(".jjFBox").attr("rel",$thisREL);
	
}

// This is the line that starts the slideshow, whenever necessary.  It is setup with a play/pause
// format, rather than a play/stop.  So, when the timer is killed, it pauses and when it's 
// recreated, it continues.

function startSlideshow(slideDelay) {

	// Take the Slideshow Delay variable from the very top of this document and converts it to
	// milliseconds.
	
	slideDelayCurrent=slideDelay*1000;

	// Remember where we exploited that rel="" attribute waaaay above?  This is why.  This
	// allows the Slideshow to run independently, and relatively, meaning LESS CODE!

	// Grab the slidenumber of the current slide, so we can increment based on it...

	$currentSlide=($(".jjFeatured").children(".jjFBox").attr("rel").substr(5,6));
	
	// Convert that REL to a number that Javascript can use, and increase it by one (moving to
	// the next slide).
	
	$currentSlide=parseFloat($currentSlide)+1;

	// Sweet, now we're ready to... oh, wait a second.  You haven't increased beyond the total
	// number of slides, have you?  If so, make sure you reset back to the first one (0).

	if($currentSlide==5) { $currentSlide=0; }
	
	// Alright.  We now have the next slide in the order selected, let's highlight it:
	
	highlightFeatured($(".jjFeatured").children(".jjFBox").children("ul").children("li").eq($currentSlide));
	
	// (to see what happens here, jump back up to the function highlightFeatured() section, above.
	
	// Whew.  Alright.  Now that *that* is done, let's do it again after the slideDelay
	// has passed.

	$slideshowRoutine=setTimeout("startSlideshow("+slideDelay+");",slideDelayCurrent);
	
}

function resetTimer() {
	
	// This is, basically, the PAUSE button.  This takes the variable set just above, here,
	// and tells it not to move on automatically.
	
	clearTimeout($slideshowRoutine);

}

