/* 
 * Jquery browser detect plugin to identify browser/os detection.
 * jQuery Browser Plugin - http://jquery.thewikies.com/browser/
*/
(function($){$.browserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;r.version=(c.exec(i)||[x,x,x,x])[3];if(r.name.match(/safari/)&&r.version>400){r.version='2.0';}if(r.name==='presto'){r.version=($.browser.version>9.27)?'futhark':'linear_b';}r.versionNumber=parseFloat(r.version,10)||0;r.versionX=(r.version!==x)?(r.version+'').substr(0,1):x;r.className=r.name+r.versionX;return r;};a=(a.match(/Opera|Navigator|Minefield|KHTML|Chrome/)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.browser=$.extend((!z)?$.browser:{},c(a,/(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/,[],/(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.browser.name,$.browser.className,$.layout.name,$.layout.className].join(' '));}};$.browserTest(navigator.userAgent,true);})(jQuery);

$(document).ready(function(){
	var postNewBlog;
	
	var prvteCont="<i class='prText'>&nbsp;&nbsp;</i>";
	var prvtLegend='<span class="private">Visible only to site adminstrators</span>';

	$('.edit_account li.input.annotation').append(prvtLegend);

	$('.edit_account li.input.private').each(function(){
			var liCont = (this).innerHTML;		
			(this).innerHTML= liCont+prvteCont;
	});
	$('.nav_page ul li.page').each(function(){
		var width=0;
		$(this).find('a').each(function(){
			width+=$(this).outerWidth(true);
			width+=4;
		});
		$(this).css('width',(width)+'px');
	});
	
	var homeliLength = $('#home .articles li.article').length;		
		for(var j=0; j<= homeliLength; j++)
		{
			var homeblogcomment = $('#home .articles li.article:nth-child('+j+') .description');		
			$('#home .articles li.article:nth-child('+j+') .activity').insertBefore(homeblogcomment);
			$('#home .articles li.article:nth-child('+j+') .category').insertBefore(homeblogcomment);
			$('#home .articles li.article:nth-child('+j+') .tools').insertBefore(homeblogcomment);	
			
		}
		$('#home .articles').css('display', 'block');
		$('#home #rss_in-1373578').find('.module .content .body').append('<a class="tourdatesbtn" href="/tour-dates/"></a>');
	var followText = '<div class="follow">' +'<a target=_new href="http://twitter.com/JanelleMonae"></a></div>';
	$('#twitterContainer').parent(".description").parent(".body").siblings(".head").append(followText);
		var liLength = $('#blog .blog_listing .content .articles li.article').length;		
		for(var i=1; i<= liLength; i++)
		{
			var blogcomment = $('#blog .blog_listing .content .articles li.article:nth-child('+i+') .description');		
			$('#blog .blog_listing .content .articles li.article:nth-child('+i+') .activity').insertBefore(blogcomment);			
			$('#blog .blog_listing .content .articles li.article:nth-child('+i+') .category').insertBefore(blogcomment);
			$('#blog .blog_listing .content .articles li.article:nth-child('+i+') .tools').insertBefore(blogcomment);
			
		}
		
		$('#blog .blog_listing .content .articles').css('display', 'block');				
		$('.grid_5 .comments .module .content .body ul li.comment').each(function(){
			var descdiv = $(this).find('.txt .description');
			var toolsdiv = $(this).find('.txt .tools');
			$(this).find('.txt .description').remove();
			$(this).find('.txt .tools').remove();
			$(this).find('.txt').append(toolsdiv);
			$(this).find('.txt').append(descdiv);
		});
		var commentTitle = $('.comments .content .title.comment');
		commentTitle.insertBefore('.comments .content fieldset');
		$('.comments .content').css('display','block');	

		
		var photoThumbnailContent = $('#photo_thumbnail-1373846 .module .content .foot .nav_meta .new');
		var photoTextDiv = "<div id='thumbnailtext'>Contribute your photos, videos and more. We want to hear from you!</div>"
		var photoTitleDiv = "<div id='thumbnailtitle'><span class='title1'>From the Fans:</span><span class='title2'>Photos!</span></div>"
		var linkStr=photoTitleDiv + photoTextDiv + "<div id='newLink'>"+photoThumbnailContent.html()+"</div>"
		$('#photo_thumbnail-1373846 .module .content .body').append(linkStr);
				
		$('#photo_thumbnail-1373846 .module .content .foot .nav_meta .new a').css('display','none');
		
    /* Suppresses display of empty footers on IE */
    $('.module .foot:empty').addClass('empty');
	
	$("html").addClass($.os.name);
	$("body").addClass($.browser.className);
	
		
    /* START Add "Launch Player" links to footer nav of all audio playlist modules */
    var launchLink = $('<li class="launchPlayer"><a href="/music-player/" class="launchPlayerLink">Launch Player</a></li>');
    $(".song_playlist .module .content .nav_meta ul").prepend(launchLink);
    /* END Add "Launch Player" links to footer nav of all audio playlist modules */
    
    /* add popup onClick handler for audio player links */
    $("a.launchPlayerLink").click(function(){
        window.open("/music-player/", "Window2", "width=368,height=270,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no");
        return false;
    });
    
    /* Make store top nav link open in a new window */
    $('.nav_main ul li.custom a[href*=amazon.com]').attr("rel", "external");
    
	/*START - Fix for truncating author name in the discussions page #698 */
			$('.discussion_listing .topics li .author a').each(function(){
				var trunc = (this).innerHTML;	
				if (trunc.length > discussionAuthorLen) {
					trunc = trunc.substring(0, discussionAuthorLen);
					trunc += '<span>' + '...</span>';
					(this).innerHTML = trunc;
				}	
			});
			$('#photo_thumbnail-340501 li.photo .txt .title a').each(function(){
				var trunc = (this).innerHTML;	
				if (trunc.length > 25) {
					trunc = trunc.substring(0, 25);
					trunc += '<span>' + '...</span>';
					(this).innerHTML = trunc;
				}	
			});
			$('#video_thumbnail-340502.video_thumbnail .videos li .txt .title a').each(function(){
				var trunc = (this).innerHTML;	
				if (trunc.length > 45) {
					trunc = trunc.substring(0, 45);
					trunc += '<span>' + '...</span>';
					(this).innerHTML = trunc;
				}	
			});
			$('#photo_thumbnail-340501.photo_thumbnail .module .content .foot .nav_meta ul li.more a').attr('href','/photo/category/member/');
			$('#video_thumbnail-340502.video_thumbnail .module .content .foot .nav_meta ul li.more a').attr('href','/video/category/member/');
	/*END - Fix for truncating author name in the discussions page #698 */

	$('#photo_thumbnail-1373846 .photos  li.photo:first-child').addClass("firstThumbnail");	
	$('#photo_thumbnail-1373846 .photos  li.photo:nth-child(2)').addClass("secondThumbnail");
	$('#blog_listing-294510 .articles  li.article:first-child').addClass("firstBlogTitle");	
    $("a[href^=http://starterfanclub1.wmg.ciscoeos.com]").parent(".custom").addClass("Fanclub");
    var photosul = $('#home #photo_thumbnail-1373846').find('ul.photos');
    var newlinkid = $('#home #photo_thumbnail-1373846').find('#newLink');
    $('#home #photo_thumbnail-1373846').find('ul.photos').remove();
    $('#home #photo_thumbnail-1373846').find('#newLink').remove();
    $('#home #photo_thumbnail-1373846 .body').append(photosul);
    $('#home #photo_thumbnail-1373846 .body').append(newlinkid);
	/* START: Community drop-down for top nav */
    //Define XHTML source for the community subnav inn the variable below	
  	  var communityNavCell = $(".nav_main ul li.nav-community_landing"); //change this selector to target a diffent cell in the top nav
  	  communityNavCell.addClass('dropdown');
 	  communityNavCell.append(communitySubNav);
    /* END: Community drop-down for top nav */
    
    /* START: Custom drop-downs for top nav */
	var $customNavs = $('.nav_main ul li.nav-custom a');
  
	  $customNavs.filter(function(){
	  return (/^Music/i).test($(this).text())
	}).parent()
  	  .addClass('nav-custom')
	  .addClass('nav-music');
	  
	  
	  $customNavs.filter(function(){
	  return (/^Fan Club$/i).test($(this).text())
	}).parent()
	  .addClass('nav-custom')
	  .addClass('dropdown')
	  .addClass('nav-fan')
	  .removeClass('nav-home')
	  .append(FCSubNav);
	  
	 $customNavs.filter(function(){
		  return (/^Store$/i).test($(this).text())
		}).parent()
    	  .addClass('nav-custom')
		  .addClass('dropdown')
		  .addClass('nav-store')
		  .append(storeSubNav);	
	  
	 $customNavs.filter(function(){
		  return (/^Global$/i).test($(this).text())
		 }).parent()
 		  .addClass('nav-custom')
		  .addClass('dropdown')
		  .addClass('nav-global_int')
		  .append(globalSubNav);
		  
	
	/* END: Custom drop-downs for top nav */
	
	/* blog and Home Continue reading button display */
	
	$('.blog_listing .content .articles li .description a').filter(function(){
		  return (/^Read More$/i).test($(this).text())
		}).addClass('continueReading')		  
	 
	 
	 /* Remove the click ability of the jmonae logo on all pages in the site */
	 $("#header h2 a").click (function(){return false;});
	
	
	/* ********** Home Page SS3 *********************** */
	
	/* Removing the upload from the top, and adding at the bottom; */
	var uploadDiv = $("#homepage_ss3 .nav_main ul li.upload");
	$("#homepage_ss3 .nav_main div > ul").append(uploadDiv);
	
	/* Carousel Button */
	/* algo 
	 * Have an event handler for the click of the buttons.
	 * Have global variables like currentActiveCaros
	 * 
	 * 
	 */	
	 var carosActiveCurrent = 0;
	 var carosTotal = $("#carosUnitWrapper .carosUnit").length;

	 if (carosTotal > 1){
	 	$("#rightCarosButton").addClass('active');
	 	$("#carosUnitWrapper .carosUnit:eq("+ carosActiveCurrent +")").toggle(100);
	 }
	 	 
	 $("#rightCarosButton").click(function (event){
	 	 if (carosTotal-carosActiveCurrent != 1){
		 	$("#carosUnitWrapper .carosUnit:eq("+ carosActiveCurrent +")").toggle(100);
			carosActiveCurrent++;
		 	$("#carosUnitWrapper .carosUnit:eq("+ carosActiveCurrent +")").toggle(100);
		 }
		 setCarosButtonsState();
		 
		});
	 $("#leftCarosButton").click(function (event){
	 	 if (carosActiveCurrent > 0 ){
		 	$("#carosUnitWrapper .carosUnit:eq("+ carosActiveCurrent +")").toggle();
			carosActiveCurrent--;
		 	$("#carosUnitWrapper .carosUnit:eq("+ carosActiveCurrent +")").toggle();
		 }
		 setCarosButtonsState();
		});
		function setCarosButtonsState(){
			
			 if (carosActiveCurrent == carosTotal-1 ){
				 	$("#rightCarosButton").removeClass('active');
			 }else {
				 	$("#rightCarosButton").addClass('active');
			 }
			 if (carosActiveCurrent == 0){
				 $("#leftCarosButton").removeClass('active');
			 }else {
		   	 	 $("#leftCarosButton").addClass('active');
			 }
		};
		
		/* ********** Home Page SS3 ends *********************** */	 	  

	
	
	var storeNavCell= $(".nav_main ul li.nav-store"); 
	
    /*Hover event handler for all drop-downs in top nav */
    $(".dropdown").hover(
		function(){$(".flyoutMenu", this).show();}, 
		function(){$(".flyoutMenu", this).hide();}
	);
    
  
	
    if (location.href.indexOf("/forums/") != -1) {
        communityNavCell.addClass("active");
        $("#discussionsNav").addClass("active");
    }
    if (location.href.indexOf("/ringtones/") != -1) {
        storeNavCell.addClass("active");
        $("#ringtonesNav").addClass("active");
    }
		
	 if (location.href.indexOf("/community_landing/") != -1) {
        communityNavCell.addClass("active");
        $("#communityHomeNav").addClass("active");
    }
	if (location.href.indexOf("/member/") != -1){
        communityNavCell.addClass("active");
        $("#memberNav").addClass("active");
    }
	
	 if (location.href.indexOf("/extras/") != -1) {
        communityNavCell.addClass("active");
        $("#extrasNav").addClass("active");
    }
	/*For international pages*/
	var globalNavCell=$(".nav_main ul li.nav-global");
	
	 if (location.href.indexOf("/es/") != -1) {
		globalNavCell.addClass("active");
		$("#esNav").addClass("active");
		}
		if (location.href.indexOf("/jp/") != -1) {
		globalNavCell.addClass("active");
		$("#jpNav").addClass("active");
		} 
		
		if (location.href.indexOf("/gb/") != -1) {
		globalNavCell.addClass("active");
		$("#gbNav").addClass("active");
		} 
		 if (location.href.indexOf("/de/") != -1) {
		globalNavCell.addClass("active");
		$("#deNav").addClass("active");
		}
	
    var photoNavCell = $(".nav_main ul li.photo");
    if (location.href.indexOf("/cellstream/") != -1) {
        photoNavCell.addClass("active");
    }
    
    if (location.href.indexOf("/music/") != -1) {
        $("a[href^=/album/]").parent(".nav-custom").addClass("active");
        
    }
    if (location.href.indexOf("/album/") != -1) {
        $("a[href^=/album/]").parent(".nav-custom").addClass("active");
    }	
    /* ********** Merch module code ********* */
	$('#merchContainer').parent(".description").parent(".body").siblings(".head").addClass("clearfix");				
		$('#merchContainer').parent(".description").parent(".body").siblings(".head").children("h3").css({'border':'none','font-size':'25px'});				
	$('#merchContainer').parent(".description").parent(".body").siblings(".head").css({'position': 'relative','z-index': '100'});
	$('#merchContainer').parent(".description").parent(".body").siblings(".foot").css({'z-index': '98','overflow': 'visible'});
	$('#merchContainer').parent(".description").parent(".body").css({'position': 'relative','clear': 'both','z-index': '99'});

/*  Commented the appending of the merch button again to itself.
	var	visitStorehead = $('#merchContainer').parent(".description").parent(".body").siblings(".head");
	$('#merchContainer .merchHead').appendTo(visitStorehead);

	var	visitStoreFoot = $('#merchContainer').parent(".description").parent(".body").siblings(".foot");
	$('#merchContainer .merchFoot').appendTo(visitStoreFoot);
*/
	$('#merchContainer').parent(".description").parent(".body").siblings(".foot.empty").addClass("emptyfix");
	    
	/* START: Merch module drop-downs */	
	$(".merchHead .visitStore").hover (
			function() { $(".visitStoreFlyout", this).show(); },
			function() { $(".visitStoreFlyout", this).hide(); }
		);
	$(".merchFoot .visitStore").hover (
		function() { $(".visitStoreFlyout", this).show(); },
		function() { $(".visitStoreFlyout", this).hide(); }		
	);
	$(".firstitem .merchBuy").hover (
		function() { $(".merchBuyFlyout", this).show(); },
		function() { $(".merchBuyFlyout", this).hide(); }		
	);
	$(".seconditem .merchBuy").hover (
		function() { $(".merchBuyFlyout", this).show(); },
		function() { $(".merchBuyFlyout", this).hide(); }		
	);
	$(".thirditem .merchBuy").hover (
		function() { $(".merchBuyFlyout", this).show(); },
		function() { $(".merchBuyFlyout", this).hide(); }		
	);
	/* END: Merch module drop-downs */	
	
	if($("#sign_up-294578 li.input input").attr('class')== "focused"){		
		$descriptionDisplay = $("#sign_up-294578 li.input input.focused").parent().contents().filter(".message").children();
		if ($descriptionDisplay.css("display") == "inline" ||$descriptionDisplay.css("display") == "none"  ){
			$descriptionDisplay.css("display","block");
		}
	} 
	
	$("#sign_up-294578 li.input input").click( function() {
		// In this check for the corresponding description div. 		
		 $descriptionDisplay = $(this).next().filter(".message").children();
		if ($descriptionDisplay.css("display") == "inline"){
			$descriptionDisplay.css("display","block");
		}
	});
	
	$("#sign_up-294578 li.select input").click( function() {
		// In this check for the corresponding description div. 
		$descriptionDisplay = $(this).parent().contents().filter(".message").children();
		if ($descriptionDisplay.css("display") == "inline"){
			$descriptionDisplay.css("display","block");
		}
	});

   /* Make rel="external" links open in a new window */
    $("a[rel=external]").attr("target", "_new");
    
    /* Fixing the target for the digg link */
    $(".shareweb .digg a").attr("target", "_new");
    
    /* Append labels to elements in discussion module */
    $(".topics li.list .category li:first-child").prepend("Category: ");
    $(".topics li.list .activity").prepend("Replies: ");
    $(".topics li.list .date").prepend("Last Reply: ");
    
    /* Add "Close" text to close link in social media sharebox on photo and video detail pages */
    $(".sharebox .sb_head .sb_title a.shareclose").prepend("Close");
    
    var noOfImageDscDtl = $("#discussion_entry-294529 .topic .description img").length;
    for (i = 0; i < noOfImageDscDtl; i++) {
        var discussionImageElement = $("#discussion_entry-294529 .topic .description img:eq(" + i + ")");
        var imgHeight = discussionImageElement.height();
        var imgWidth = discussionImageElement.width();
        if (imgHeight > 200 && imgWidth > 200) {
            var calcheight = (imgHeight / imgWidth) * 200;
            discussionImageElement.css("height", calcheight);
            discussionImageElement.css("width", 200);
        }        
    }    
    
    var noOfImageDscDtl = $("#discussion_listing-340654  .topic .description img").length;
    for (i = 0; i < noOfImageDscDtl; i++) {
        var discussionImageElement = $("#discussion_listing-340654 .topic .description img:eq(" + i + ")");
        var imgHeight = discussionImageElement.height();
        var imgWidth = discussionImageElement.width();
        if (imgHeight > 200 && imgWidth > 200) {
            var calcheight = (imgHeight / imgWidth) * 200;
            discussionImageElement.css("height", calcheight);
            discussionImageElement.css("width", 200);
        }
        
    }
	
	// Functionality for add new blogs.
    $(".blog_listing .nav_meta .more a").bind("click", function(e){
		
		$.cookie("blog_body", blogTwitterBlurbText, {
            path: "/"
        });
    });
	    if ($("body").attr("id") == "add_new_blog") {        
        $.cookie("blog_body", blogTwitterBlurbText, {
            path: "/"
        });
    }

	
    //Album detail stuff 
    $buylinks = $('#album_info-383751 .foot .nav_meta ul');
    $buylinks.insertBefore('#album_info-383751 .album .txt div.description');
    $('#album_info-383751.album_info .module .content .foot .nav_meta ul').css("display", "block");
	
	$errmsg = $('.reset_password .module .content .body');
    $errmsg.insertBefore('#errorMsg');
    
    //Modifying the legal text in the log in and sign up pages.
    $("body#sign_up #cmsgData\\[agreeToTerms\\]").next().html(privacyPolicyText + "").show();
    $("body#join #cmsgData\\[agreeToTerms\\]").next().html(privacyPolicyText + "").show(); 	
	
	/*START- code which obfuscates email addresses #2420*/	
		var m_ = "mailto:";
		var a_ = "@";
		var d_ = ".";
		var i = 0;
		var j  = 0;
		var q_ = "?";
		var e_ = "=";
		
		$('span.ciReplace').each(function(){	
			if(cId[i].format == ""){
				$(this).html('<a href="'+m_+cId[i].name+a_+cId[i].domain+d_+cId[i].tld+'">'+ cId[i].name + a_+ cId[i].domain + d_+ cId[i].tld +'</a>');
			}
			else{
				if(cId[i].param == ""){
					$(this).html('<a href="'+m_+cId[i].name+a_+cId[i].domain+d_+cId[i].tld+'">'+ cId[i].format+'</a>');
				}
				else{
					$(this).html('<a href="'+m_+cId[i].name+a_+cId[i].domain+d_+cId[i].tld+q_+'subject'+e_+cId[i].param+'">'+cId[i].format+'</a>');
				}
			}
		i++;				
		});
		
		
		$('span.footReplace').each(function(){
					if(fId[j].format == ""){
				$(this).html('<a href="'+m_+fId[j].name+a_+fId[j].domain+d_+fId[j].tld+'">'+ fId[j].name + a_+ fId[j].domain + d_+ fId[j].tld +'</a>');
			}
			else{
				if(fId[j].param == ""){
					$(this).html('<a href="'+m_+fId[j].name+a_+fId[j].domain+d_+fId[j].tld+'">'+ fId[j].format+'</a>');
				}
				else{
					$(this).html('<a href="'+m_+fId[j].name+a_+fId[j].domain+d_+fId[j].tld+q_+'subject'+e_+fId[j].param+'">'+fId[j].format+'</a>');
				}
			}			
		});	
		
	/*End - code which obfuscates email addresses #2420*/
	
		var $blogFootFix = $('.blog_listing .nav_meta .more a');
	$blogFootFix.filter(function(){
	return (/^Post/i).test($(this).text())
	}).parent()
	.removeClass('more')
	.addClass('new'); 
	
	readBio = $('<div class="nav_meta"><ul><li class="more"><a href="/bio/">Read Bio</a></li></ul></div>');
	$('#member_listing-366839.member_listing .module .content .foot').append(readBio);
       
});

function eoscInit(){	
	//Modifying the legal text in the log in and sign up pages.
	$("body#sign_up #cmsgData\\[agreeToTerms\\]").next().html(privacyPolicyText + "").show();
	$("body#join #cmsgData\\[agreeToTerms\\]").next().html(privacyPolicyText + "").show(); 		
	
	/*reset password screen*/	
	$('.reset_password .module .content .body').insertBefore('#errorMsg');
	
	var commentTitle = $('.comments .content .title.comment');
	commentTitle.insertBefore('.comments .content fieldset');
	$('.comments .content').css('display','block');
	$('.grid_5 .comments .module .content .body ul li.comment').each(function(){
		var descdiv = $(this).find('.txt .description');
		var toolsdiv = $(this).find('.txt .tools');
		$(this).find('.txt .description').remove();
		$(this).find('.txt .tools').remove();
		$(this).find('.txt').append(toolsdiv);
		$(this).find('.txt').append(descdiv);
	});
	$('.nav_page ul li.page').each(function(){
		var width=0;
		$(this).find('a').each(function(){
			width+=$(this).outerWidth(true);
			width+=4;
		});
		$(this).css('width',(width)+'px');
	});
	
}

   $.urlParam = function(name){
        var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
        if (results == null) {
            return 0;
        }
        else {
            return results[1];
        }
    }	
	
	
	function carouselShare() {
		var shareContent = $('#home .articles li .tools ul li .sharebox').html();
		$('#carSharePopUp').innerHTML = shareContent;
	}



