// Program: insite_cookie_manager.jsa
// Purpose: This program should be used to extract user information from either the default '<SITENAME>_user_auth' cookie, 
//   or the more detailed 'insite_account_info' cookie.  
//   NOTE: The 'insite_account_info' cookie is not used by Insite by default, and must be added to the list of custom cookies. See wiki for details.
// Expected Use:
//   When a user instantiates this object several variables will be set and available to the user these are, also users can call the methods outlined here if they need to for some reason.  NOTE: All variables after 'userLoggedIn' are only set if the user is acually logged into Insite.
//     userLoggedIn = 1 if logged in, 0 if not
//     userID       = Users Insite ID
//     userName     = Users Insite username
//     firstName    = Users first name as Insite sees it
//     lastName     = Users last name as Insite sees it
//     email        = Users Email as registered with Insite
// Author:  Ara Yapejian - 3/31/2008

function Insite_Cookie_Manager() {
	// The name of the default Insite Cookie as well as the more detailed 'insite_account_info' cookie
	this.insiteDefaultCookie = 'user_auth';
	this.insiteAccountInfoCookie = 'insite_account_info';
	
	// Purpose: This function will return 1 if the user is logged into insite, and 0 if not.
	this.isUserLoggedIn = function() {
		if( document.cookie.length > 0 ) {
			var cookieValue = document.cookie.match( '(^|;)*' + this.insiteDefaultCookie + '=([^;]*)(;|$)' );
			if( cookieValue && !document.cookie.match( '(^|;)*' + this.insiteDefaultCookie + '=\.threshold([^;]*)(;|$)' ) )
				return( "1" );
			else 
				return( "0" );
		}
	}
	
	// Purpose: This function will return the Insite users 'username' from the default, and always available (When logged in) 'user_auth' cookie.
	this.getInsiteUserName = function() {
		if( document.cookie.length > 0 ) {
			var cookieValue = document.cookie.match( '(^|;)*' + this.insiteDefaultCookie + '=([^;]*)(;|$)' );
			if( cookieValue && !document.cookie.match( '(^|;)*' + this.insiteDefaultCookie + '=\.threshold([^;]*)(;|$)' ) ){
				var end = cookieValue[2].indexOf( "%7C" );
				var userName = cookieValue[2].substr(0, end);
				return( userName );
			} else
				return( "0" );
		} else
			return( "0" );
	}
	
	// Purpose: This function will return the users insite ID from the 'insite_account_info' cookie
	this.getInsiteID = function() {
		if( document.cookie.length > 0 ) {
				var cookieValue = document.cookie.match( '(^|;)*' + this.insiteAccountInfoCookie + '=([^;]*)(;|$)' );
			        if( cookieValue && !document.cookie.match( '(^|;)*' + this.insiteDefaultCookie + '=\.threshold([^;]*)(;|$)' ) ){
					// Get the index of the first and last character in the cookie argument we need
					var start = cookieValue[2].indexOf( "id%3D" );
					var end   = cookieValue[2].indexOf( "%7C", start );
					// Extract that one piece of the cookie based on the start, end values.  The calculate a new 'start' for the '=' to get the 
					//   actual value of the piece we are interested ... increment by 3 based on teh '%3D' Hex code for '='
					// The little 'end == -1' part is needed if the value found is the last value in the cookie ... if it is then the
					//   'end' index (where we look for the next occurence of a pipe ("%7C") wont exist and brakes stuff.
					if( end == -1 )
						var extractedCookieValue = cookieValue[2].substr( start );
					else
						var extractedCookieValue = cookieValue[2].substring( start,end );
					start = extractedCookieValue.indexOf( "%3D" );
					start = start + 3;
					var ID = extractedCookieValue.substr(start);
					return( ID );
				} else
					return( "0" );
			} else
				return( "0" );
	}
	
	// Purpose: This function will return the users first name from the 'insite_account_info' cookie
	this.getInsiteFirstName = function() {
		if( document.cookie.length > 0 ) {
			var cookieValue = document.cookie.match( '(^|;)*' + this.insiteAccountInfoCookie + '=([^;]*)(;|$)' );
			if( cookieValue && !document.cookie.match( '(^|;)*' + this.insiteDefaultCookie + '=\.threshold([^;]*)(;|$)' ) ){
				// Get the index of the first and last character in the cookie argument we need
				var start = cookieValue[2].indexOf( "first_name%3D" );
				var end   = cookieValue[2].indexOf( "%7C", start );
				// Extract that one piece of the cookie based on the start, end values.  The calculate a new 'start' for the '=' to get the 
				//   actual value of the piece we are interested ... increment by 3 based on teh '%3D' Hex code for '='
				// The little 'end == -1' part is needed if the value found is the last value in the cookie ... if it is then the
				//   'end' index (where we look for the next occurence of a pipe ("%7C") wont exist and brakes stuff.
				if( end == -1 )
					var extractedCookieValue = cookieValue[2].substr( start );
				else
					var extractedCookieValue = cookieValue[2].substring( start,end );
				start = extractedCookieValue.indexOf( "%3D" );
				start = start + 3;
				var firstName = extractedCookieValue.substr(start);
	
				return( firstName );
			} else
				return( "0" );
		} else
			return( "0" );
	}
	
	// Purpose: This function will return the users last name from the 'insite_account_info' cookie
	this.getInsiteLastName = function() {
	if( document.cookie.length > 0 ) {
			var cookieValue = document.cookie.match( '(^|;)*' + this.insiteAccountInfoCookie + '=([^;]*)(;|$)' );
			if( cookieValue && !document.cookie.match( '(^|;)*' + this.insiteDefaultCookie + '=\.threshold([^;]*)(;|$)' ) ){
				// Get the index of the first and last character in the cookie argument we need
				var start = cookieValue[2].indexOf( "last_name%3D" );
				var end   = cookieValue[2].indexOf( "%7C", start );
				// Extract that one piece of the cookie based on the start, end values.  The calculate a new 'start' for the '=' to get the 
				//   actual value of the piece we are interested ... increment by 3 based on teh '%3D' Hex code for '='
				// The little 'end == -1' part is needed if the value found is the last value in the cookie ... if it is then the 
				//   'end' index (where we look for the next occurence of a pipe ("%7C") wont exist and brakes stuff.
				if( end == -1 )
					var extractedCookieValue = cookieValue[2].substr( start );
				else                    
					var extractedCookieValue = cookieValue[2].substring( start,end );
				start = extractedCookieValue.indexOf( "%3D" );
				start = start + 3;
				var lastName = extractedCookieValue.substr(start);
	
				return( lastName );
			} else
				return( "0" );
		} else
			return( "0" );
	}
	
	// Purpose: This function will return the users email from the 'insite_account_info' cookie
	this.getInsiteEmail = function() {
		if( document.cookie.length > 0 ) {
			var cookieValue = document.cookie.match( '(^|;)*' + this.insiteAccountInfoCookie + '=([^;]*)(;|$)' );
			if( cookieValue && !document.cookie.match( '(^|;)*' + this.insiteDefaultCookie + '=\.threshold([^;]*)(;|$)' ) ){
				// Get the index of the first and last character in the cookie argument we need
				var start = cookieValue[2].indexOf( "email%3D" );
				var end   = cookieValue[2].indexOf( "%7C", start );
				// Extract that one piece of the cookie based on the start, end values.  The calculate a new 'start' for the '=' to get the 
				//   actual value of the piece we are interested ... increment by 3 based on teh '%3D' Hex code for '='
				// The little 'end == -1' part is needed if the value found is the last value in the cookie ... if it is then the 
				//   'end' index (where we look for the next occurence of a pipe ("%7C") wont exist and brakes stuff.
				if( end == -1 ) 
					var extractedCookieValue = cookieValue[2].substr( start );
				else 
					var extractedCookieValue = cookieValue[2].substring( start,end );
				start = extractedCookieValue.indexOf( "%3D" );
				start = start + 3;
				var email = extractedCookieValue.substr(start);
	
				return( email );
			} else
				return( "0" );
		} else
			return( "0" );
	}
	

// ***********************************
// THE MAIN CONSTRUCTOR FOR THE CLASS
// ***********************************
	this.userLoggedIn = this.isUserLoggedIn();
	// If the user is logged in get all info
	if( this.userLoggedIn != 0 ) {
		this.userID       = this.getInsiteID();
		this.userName     = this.getInsiteUserName();
		this.firstName    = this.getInsiteFirstName();
		this.lastName     = this.getInsiteLastName();
		this.email        = this.getInsiteEmail();
	} else {
		this.userID       = "";
		this.userName     = "";
		this.firstName    = "";
		this.lastName     = "";
		this.email        = "";
        }
	
} // END OF PROGRAM


// ##################
// PURPOSE: This function fetches our insite cookie and returns the insite userName or "-1" if not logged in
function getInsiteUserName( myInsiteCookieName ) {
        if( document.cookie.length > 0 ) {
                var cookieValue = document.cookie.match( '(^|;)*' + myInsiteCookieName + '=([^;]*)(;|$)' );
	        if( cookieValue && !document.cookie.match( '(^|;)*' + this.insiteDefaultCookie + '=\.threshold([^;]*)(;|$)' ) ){
                        var end = cookieValue[2].indexOf( "%7C" );
                        var userName = cookieValue[2].substr(0, end);
                        if( userName == '' ){
                                return( "-1" );
                        }
                        return( userName );
                } else
                        return( "-1" );
        } else
                return( "-1" );
}
// ##################
//SHOW HIDE CSS

//if (typeof account_user_name != 'undefined' && typeof insitecookie != 'undefined') {
	var account_user_name = getInsiteUserName( insitecookie );
	if ( -1  == account_user_name) {
		document.write("<style>#member{display:none;}</style>");
		account_user_name = 'Guest';
	} else {
		document.write("<style>#nonmember{display:none;}</style>");
	}
//}

var rurl_qs = '';
var loc = ''+document.location;
if (loc.match('/reg-bin/') )
{
    rurl_qs = ";goto=/";
}
else
{
    rurl_qs = ";goto="+loc
}



// temporary switch stand in for Pluck
var siteLife_master_switch_on = true;
var sitelife_is_on = true;

if (!siteLife_master_switch_on || !sitelife_is_on) {
	var gSiteLife = {
		AddEventHandler: function () {},
		FireEvent: function () {},
		ScriptId: function() {},
		OnError: function() {},
		OnDebug: function() {},
		GetParameter: function() {},
		GetElement: function() {},
		GetTags: function() {},
		EscapeValue: function() {},
		__ArrayValidation: function() {},
		__CheckErrorHandler: function() {},
		SetCookie: function SetCookie() {},
		__GetArgument: function() {},
		__StripAnchorFromUrl: function() {},
		__SafeAppendUrlValue: function() {},
		__AppendUrlValues: function () {},
		ReloadPage: function() {},
		__Send: function() {},
		Logout: function() {},
		AddLoadEvent: function() {},
		AdInsertHelper: function() {},
		InsertAds: function() {},
		TitleTag: function() {},
		WriteDiv: function() {},
		InnerHtmlWrite: function() {},
		SortTimeStampDescending: "TimeStampDescending",
		SortTimeStampAscending: "TimeStampAscending",
		SortRecommendationsDescending: "RecommendationsDescending",
		SortRecommendationsAscending: "RecommendationsAscending",
		SortRatingDescending: "RatingDescending",
		SortRatingAscending: "RatingAscending",
		SortAlphabeticalAscending: "AlphabeticalAscending",
		SortAlphabeticalDescending: "AlphabeticalDescending",
		KeyTypeExternalResource: "ExternalResource",
		PersonaHeaderRequest: function() {},
		PersonaHeader: function() {},
		Persona: function() {},
		LoadPersonaPage: function() {},
		PersonaHome: function() {},
		PopulateGroupsDiv: function() {},
		WatchItem: function() {},
		PersonaRemoveWatchItem: function() {},
		PersonaAddFriend: function() {},
		PersonaRemoveFriend: function() {},
		PersonaRemovePendingFriend: function() {},
		PersonaAddPendingFriend: function() {},
		PersonaMessages: function() {},
		PersonaComments: function() {},
		PersonaBlog: function() {},
		PersonaProfile: function() {},
		PersonaWatchListPaginate: function() {},
		PersonaFriendsPaginate: function() {},
		PersonaFriendsExpand: function() {},
		PersonaFriendsCollapse: function() {},
		PersonaPendingFriendsPaginate: function() {},
		PersonaMessagesPreviewPaginate: function() {},
		PersonaMessageRemove: function() {},
		PersonaSend: function() {},
		PersonaPaginate: function() {},
		PersonaPhotoSend: function() {},
		PersonaMostRecent: function() {},
		PersonaCommunityGroupsPaginate: function() {},
		PersonaCreateGallery: function() {},
		PersonaEditGallery: function() {},
		PersonaUploadToUserGallery: function() {},
		PersonaPhotos: function() {},
		PersonaAllPhotos: function() {},
		PersonaGalleryPhoto: function() {},
		PersonaMyRecentPhotos: function() {},
		PersonaGallery: function() {},
		UserGalleryList: function() {},
		PersonaGallerySubmissions: function() {},
		PersonaGalleryPhoto: function() {},
		PersonaRecentGalleryPhoto: function() {},
		LoadPersonaGalleryPage: function() {},
		LoadPersonaPhotoPage: function() {},
		LoadPersonaRecentPhotoPage: function() {},
		ShowFacebookHelpDialog: function() {},
		CopyRssUrlToClipboard: function() {},
		SolicitPhoto: function() {},
		PhotoUpload: function() {},
		PublicGallery: function() {},
		GalleryPhoto: function() {},
		PublicGalleries: function() {},
		PhotoRecommend: function() {},
		Comments: function() {},
		CommentsInput: function() {},
		CommentsOutput: function() {},
		CommentsRefresh: function() {},
		CommentsInternal: function() {},
		GetComments: function() {},
		Blog: function() {},
		LoadBlogPage: function() {},
		BlogViewEdit: function() {},
		BlogPostCreate: function() {},
		BlogPendingComments: function() {},
		BlogSettings: function() {},
		BlogEditPost: function() {},
		BlogRemovePost: function() {},
		BlogViewPost: function() {},
		BlogViewMonth: function() {},
		AddBlogWatchItem: function() {},
		RemoveBlogWatchItem: function() {},
		BlogViewTag: function() {},
		BlogRefreshViewEditList: function() {},
		BlogSend: function() {},
		Recommend: function() {},
		BlogSelectPendingComments: function() {},
		Forums: function() {},
		ForumCategories: function() {},
		Forum: function() {},
		ForumDiscussion: function() {},
		ForumCreateDiscussion: function() {},
		ForumMain: function() {},
		ForumCreatePost: function() {},
		ForumEditPost: function() {},
		ForumEditProfile: function() {},
		ToggleExpand: function() {},
		ForumSearch: function() {},
		ForumSearchKeyPress: function() {},
		ForumSearchPaginate: function() {},
		ForumSpecificForumSearchKeyPress: function() {},
		ForumSpecificForumSearch: function() {},
		ForumSearchSpecificForumPaginate: function() {},
		LoadForumPage: function() {},
		ForumSend: function() {},
		ForumDiscussionEdit: function() {},
		ForumDiscussionToggleIsSticky: function() {},
		ForumDiscussionToggleIsClosed: function() {},
		ForumDiscussionDelete: function() {},
		MoveDiscussion: function() {},
		ForumEdit: function() {},
		ForumToggleIsClosed: function() {},
		ForumDelete: function() {},
		ForumPostDelete: function() {},
		ForumBlockUser: function() {},
		ForumMyDiscussionsPaginate: function() {},
		ForumImage: function() {},
		BaseAdParam: function () {},
		ForumJoinGroup: function() {},
		ForumLeaveGroup: function() {},
		ForumGroupMemberList: function() {},
		ForumInviteUser: function() {},
		ForumGroupConfirm: function() {},
		ForumSendInviteToUser: function() {},
		ForumAddEnemy: function() {},
		ForumRemoveEnemy: function() {},
		ForumChangeSort: function() {},
		Recommend: function() {},
		PostRecommendation: function() {},
		RateItem: function () {},
		Rating: function() {},
		RatingClickStar: function () {},
		RatingFillStar: function() {},
		Review: function() {},
		ReviewClickStar: function () {},
		GetReviews: function() {},
		SummaryArticlesMostCommented: function() {},
		SummaryArticlesMostRecommended: function() {},
		SummaryPhotosRecentPhotosByTag: function() {},
		SummaryPhotosRecentUserPhotos: function() {},
		SummaryPhotosRecentPhotos: function() {},
		SummaryPhotosMostRecommendedPhotos: function() {},
		SummaryPhotosMostRecommendedUserPhotos: function() {},
		SummaryPhotosMostRecommendedGalleries: function() {},
		SummaryForumsRecentDiscussions: function() {},
		SummaryBlogsRecent: function() {},
		SummaryBlogsRecentPostsByTag: function() {},
		SummaryBlogsRecentPosts: function() {},
		SummaryBlogsMostRecommendedPosts: function() {},
		SummaryPersonaProfileRecent: function() {},
		SummaryPanel: function() {},
		SummarySend: function() {}
	}
	var RequestBatch = function() {};
	RequestBatch.prototype = {
		initialize: function() {},
		AddToRequest: function(requestThis) { },
		BeginRequest: function(serverUrl, callback) {}
	};
	function Section () {}
	function Category () {}
	function Activity () {}
	function ContentType () {}
	function UserTier () {}
	function DiscoverContentAction () {}
	function UserKey () {}
	function ArticleKey () {}
	function UpdateArticleAction () {}
	function CommentPage () {}
}
var switchThumbnails='';function convert2MobilePath(link){originalHREF=$(link).attr('href');if(originalHREF.indexOf('/v-')==-1){newHREF=originalHREF.replace(/(.+)\/(\d+[\/\.])/,"$1/v-mobile/$2");}else{newHREF=originalHREF.replace(/\/v-[^\/]+/,"/v-mobile");}
$(link).attr('href',newHREF);}
function convertPopularLinks(){$("#mostPopular ul li a").each(function(){convert2MobilePath(this);});}
myGadgetCom.finishGui=function(){jQuery('#ComDiscOutput_dynamicContent a').each(function(){convert2MobilePath(this);});}
myGadgetRec.finishGui=function(){jQuery('#RecDiscOutput_dynamicContent a').each(function(){convert2MobilePath(this);});}
function initAccordion()
{currentURL=window.location.href;if(currentURL.match("mobile_channels")){$("li.channel").show();$("ul#mostPopularFeeds").hide();}else{tmpChannelList=readCookie("mobileChannelList").split('|');var lastChannelListID=''
if(tmpChannelList){for(i in tmpChannelList){$("#c"+tmpChannelList[i]).css("display","block");lastChannelListID="#c"+tmpChannelList[i];}}}
positionCount=0;lastLiBlock=0;$("div#homePageChannels ul li.channel").each(function(){positionCount++;if($(this).css('display').match('block'))
lastLiBlock=positionCount;});lastLiBlock--;$('div#homePageChannels ul li.channel:eq('+lastLiBlock+')').css('-webkit-border-bottom-right-radius','10px');$('div#homePageChannels ul li.channel:eq('+lastLiBlock+')').css('-webkit-border-bottom-left-radius','10px');$('div#homePageChannels ul li.channel:eq('+lastLiBlock+') li.story:last-child').css('-webkit-border-bottom-left-radius','10px');$('.channel h2').click(function(){var checkElement=$(this).next();if($(checkElement).attr('id').match('ComDiscTemplate')||$(checkElement).attr('id').match('RecDiscTemplate')){checkElement=$(checkElement).next();}
console.log('DEBUG: '+$(checkElement).attr('id'));$('.channel h2').removeClass('arrowDown');$('.channel h2').addClass('arrowLeft');if((checkElement.is('ul'))&&(checkElement.is(':visible'))){checkElement.hide();return false;}
if((checkElement.is('ul'))&&(!checkElement.is(':visible'))){testInitialExpansion=$(this).attr('class');if(testInitialExpansion.match('neverExpanded')){tmpSectionID=$(this).attr('id').split('h2');liSectionID="li#c"+tmpSectionID[1];sectionID="mi"+tmpSectionID[1];atomURL='/'+tmpSectionID[1]+'/index.atom';$(liSectionID+" .moreStories").hide();$(liSectionID+" h2").append("<span class='h2LoadingText'> <span class='ajaxLoadTop'</span></span>");$(liSectionID+" h2 span.ajaxLoadTop").css("background-image",'url(/static/images/mi/smartphone/ajaxLoad.gif)');fetchStories(0,5,atomURL,sectionID);$(this).removeClass('neverExpanded');}
$('.channel ul:visible').hide();$(this).removeClass('arrowLeft');$(this).addClass('arrowDown');checkElement.show();return false;}});}
addEventListener("load",function(){setTimeout(hideURLbar,0);},false);function hideURLbar(){window.scrollTo(0,1);}
function fetchStories(start,end,url,cssID){var loopCount=0;var elementCount=0;var outputStories="";$.ajax({type:"GET",url:url,async:true,success:function(xml){$('entry',xml).each(function(i){loopCount++;if((loopCount>start)&&(elementCount<end)){var headline=$(this).find("title").text();var url=$(this).find("link[ type='text\/html' ]").attr('href');var dateUpdated=$(this).find("updated").text();var datePublished=$(this).find("published ").text();var image=$(this).find("img.mobileThumb").attr('src');var imageAlt=$(this).find("img").attr('alt');var	summary=$(this).find("p.body").html();if(summary){tmpSummary=summary.split('<![CDATA[');summary=tmpSummary[1].split(']]>');summary=summary[0];}else{summary='';}
var spliturl=url.split("/");url=spliturl[0]+"/"+spliturl[1]+"/"+spliturl[2]+"/"+spliturl[3]+"/"+spliturl[4]+"/"+spliturl[5]+"/v-mobile/"+spliturl[6]+"/"+spliturl[7];if(!image)
image='/static/styles/smartphone/themes/mi_theme/images/image-bkgd.png';image=encodeURI(image);outputStories+="\
								<li class='story newStory'>\
								    <span class='moreStoryHighlight'></span>\
								    <div class='image' style='background-image: url("+image+");'>\
								        <span class='overlay'></span>\
								    </div>\
								    <div class='summary'>\
								        <p class='headline'>\
				        				    <a href='"+url+"' >\
												"+headline+"\
											</a>\
										</p>\
										<p class='secondary'>\
											<a href='"+url+"' >\
												"+summary+"\
											</a>\
										</p>\
									</div>\
								</li>";elementCount++;}else if(elementCount>end){return(false);}});$(liSectionID+" .moreStories").show();if((elementCount==0)||(elementCount<end)){$("#"+cssID+" li.moreStories").css("display","none");headingCssSelector=cssID.split("mi");$("#h2"+headingCssSelector[1]).append("(No more stories)");$("#h2"+headingCssSelector[1]).addClass("noMoreStories");}
if(elementCount!=0)
$("#"+cssID+" li.story p.secondary").css("display","none");$("#"+cssID+" li").removeClass('newStory');$("#"+cssID+" li.moreStories").before(outputStories);$("ul#"+cssID+" li.moreStories span.ajaxLoad").css("background-image",'none');$("span.h2LoadingText").remove();},error:function(xhr,desc,exceptionobj){$("ul#"+cssID+" li.moreStories span.ajaxLoad").css("background-image",'none');$("span.h2LoadingText").remove();alert("Error fetching news feed");}});}
function fetchStoriesJSON(start,end,url,cssID){var loopCount=0;var elementCount=0;var outputStories="";console.debug("DEBUG: Fetching JSON Feed");$.getJSON("/static/scripts/smartphone/tmp/feed.json?test=1&jsoncallback=jsonCallbackTest",function(json){alert("TEST");$.each(json.items,function(){console.debug("DATA: "+json.items[1].title);console.debug("DEBUG: Currently Fetching JSON Feed");});});console.debug("DEBUG: DONE Fetching JSON Feed");}
function preFetchStories(url,ulCssID,end){var startStory=$("ul#"+ulCssID+" li").size();$("ul#"+ulCssID+" li.moreStories span.ajaxLoad").css("background-image",'url(/static/images/mi/smartphone/ajaxLoad.gif)');setTimeout(function(){fetchStories(startStory,end,url,ulCssID);},300);}
function isAppleDevice(){userAgent=navigator.userAgent;userAgent=userAgent.toLowerCase();if(userAgent.match('iphone')||userAgent.match('ipod'))
return(true);else
return(false);}
function orientationChange(){var currentOrientation=window.orientation;var orient=currentOrientation==0?"portrait":"landscape";document.body.setAttribute("orient",orient);hideURLbar();}
var isSearchDisplayed=0;function searchDisplay(){if(isSearchDisplayed==0){if(isLoginDisplayed==1){$("#insiteLogin").hide();hideURLbar();isLoginDisplayed=0;}
$("#simpleSearch").show();isSearchDisplayed=1;}else{$("#simpleSearch").hide();hideURLbar();isSearchDisplayed=0;}}
var isLoginDisplayed=0;function loginDisplay(){if(isLoginDisplayed==0){if(isSearchDisplayed==1){$("#simpleSearch").hide();hideURLbar();isSearchDisplayed=0;}
$("#insiteLogin").show();isLoginDisplayed=1;}else{$("#insiteLogin").hide();hideURLbar();isLoginDisplayed=0;}}
var isMainMenuDisplayed=0;function mainMenuDisplay(){if(isMainMenuDisplayed==0){if(isSearchDisplayed==1){$("#simpleSearch").hide();hideURLbar();isSearchDisplayed=0;}
wrapperHeight=$("#wrap").css('height');wrapperHeight=wrapperHeight.split('px');wrapperHeight[0]-=20;wrapperHeight=wrapperHeight[0]+"px";$(".menuOpacity").css('height',wrapperHeight);$("#mainMenu").show();isMainMenuDisplayed=1;}else{$("#mainMenu").hide();hideURLbar();isMainMenuDisplayed=0;}}
function processLogin(){$.post("/reg-bin/int.cgi",{mode:$("#insiteHiddenMode").val(),version:$("#insiteHiddenVersion").val(),rurl:$("#insiteHiddenRurl").val(),error_url:$("#insiteHiddenErrorUrl").val(),user_name:$("#insiteTextUsername").val(),password:$("#insitePasswordPassword").val(),remember:$("#insiteCheckboxRemember").val()},function(msg){if(msg.match("insiteLoginError")){alert("Incorrect Username or Password. Please retry.");$("#insitePasswordPassword").val('');$("#insiteTextUsername").focus();}else{alert("Thank you for logging in, the page will now refresh.");window.location=window.location.href;}});}
function storyTextBig(){var initialFontSize=$("#storyBody p").css('font-size');tmpInitialFontSize=initialFontSize.split("px");if(tmpInitialFontSize[0]<20){initialFontSize=++tmpInitialFontSize[0]+"px";$("#storyBody p").css('font-size',initialFontSize);$("#storyTextSmall").css("color","white");createCookie("mobileStoryTextSize",initialFontSize,365);}else{$("#storyTextBig").css("color","grey");$("#storyTextSmall").css("color","white");}}
function storyTextSmall(){var initialFontSize=$("#storyBody p").css('font-size');tmpInitialFontSize=initialFontSize.split("px");if(tmpInitialFontSize[0]>10){initialFontSize=--tmpInitialFontSize[0]+"px";$("#storyBody p").css('font-size',initialFontSize);$("#storyTextBig").css("color","white");createCookie("mobileStoryTextSize",initialFontSize,365);}else{$("#storyTextSmall").css("color","grey");$("#storyTextBig").css("color","white");}}
var isCommentsDisplayed=0;function toggleComments(){if(isCommentsDisplayed==0){$("#storyBody").hide();$("#storyTools").hide();if(!isUserLoggedIn()){$("#SiteLife_Login").html('\
				Please <a href="#" onClick="mainMenuDisplay(); loginDisplay(); return( false );"> login </a>\
				to leave comments.  If you are not registered, please register on our full site\
				<a href="/reg-bin/int.cgi?mode=register&goto='+window.location.href+'"> here </a>\
			');}else{$("#SiteLife_Login").html('');}
$(".comWrapper").show();isCommentsDisplayed=1;}else{$("#storyBody").show();$("#storyTools").show();$(".comWrapper").hide();isCommentsDisplayed=0;}}
function settingsToggleInitialization(){if(readCookie('mobileVideoPreview')){$("#mobileVideoPreview").removeClass("iToggleOff");$("#mobileVideoPreview").addClass("iToggleOn");}
getSettingsCookie=readCookie("mobileChannelList");if(getSettingsCookie){activeChannels=getSettingsCookie.split('|');for(i in activeChannels){$("#"+activeChannels[i]).removeClass("iToggleOff");$("#"+activeChannels[i]).addClass("iToggleOn");}}}
function settingsToggle(state,id){channelList=readCookie("mobileChannelList");if(state=="true"){if(channelList){channelList+="|"+id;createCookie("mobileChannelList",channelList,365);}else{createCookie("mobileChannelList",id,365);}
}else{if(channelList){splitChannelList=channelList.split(id+"|");if(splitChannelList[1]==undefined){splitChannelList=channelList.split("|"+id);}
if(splitChannelList[1]!=undefined){modifiedChannelList=splitChannelList[0]+splitChannelList[1];createCookie("mobileChannelList",modifiedChannelList,365);}else{alert("Must leave atleast one channel active");$("#"+id).removeClass("iToggleOff").addClass("iToggleOn");}
}else{}}
channelList=readCookie("mobileChannelList");}
function channelListCookieInitialization(){testChannelList=readCookie("mobileChannelList");channelList='';if(testChannelList){}else{for(i in miDefaultHomePageSectionList){channelList=channelList+miDefaultHomePageSectionList[i]+"|";}
channelList=channelList.replace(/\|$/,'');createCookie("mobileChannelList",channelList,365);}}
function createCookie(name,value,days){if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires="; expires="+date.toGMTString();}
else var expires="";document.cookie=name+"="+value+expires+"; domain="+cookieDomain+"; path=/";}
function readCookie(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' ')c=c.substring(1,c.length);if(c.indexOf(nameEQ)==0)return c.substring(nameEQ.length,c.length);}
return null;}
function eraseCookie(name){createCookie(name,"",-1);}
function isUserLoggedIn(){insiteCookie=readCookie(insiteUserAuthCookieName);if(insiteCookie){insiteCookie=insiteCookie.split('%7');return(insiteCookie[0]);}else{return(false);}}
function hideVideos(){$(".videoChannel").hide();positionCount=0;lastLiBlock=0;$("ul#mostPopularFeeds li").each(function(){positionCount++;if($(this).css('display').match('block'))
lastLiBlock=positionCount;});lastLiBlock=lastLiBlock-1;$('ul#mostPopularFeeds li.channel:eq('+lastLiBlock+')').css('-webkit-border-bottom-right-radius','10px');$('ul#mostPopularFeeds li.channel:eq('+lastLiBlock+')').css('-webkit-border-bottom-left-radius','10px');}
function processLogout(){eraseCookie(insiteUserAuthCookieName);eraseCookie('vmix_core_user_info');eraseCookie('AT');$("li.menuLogin a").text("Login");$("li.menuLogin").removeClass("menuLogout");$("li.menuLogin").addClass("menuLogon");$("li.menuLogin a").attr('onClick','loginDisplay(); return( false )');alert('You have been successfully logged out');mainMenuDisplay();}
$(document).ready(function(){windowHREF=window.location.href;if(isUserLoggedIn()){$("li.menuLogin a").text("Log Out");$("li.menuLogin").removeClass("menuLogon");$("li.menuLogin").addClass("menuLogout");$("li.menuLogin a").attr('onClick','processLogout(); return( false )');}else{}
$("div.iToggle").click(function(){buttonState=$(this).attr('class');sectionID=$(this).attr('id');if(buttonState.match("iToggleOn")){buttonState='false';$(this).removeClass("iToggleOn").addClass("iToggleOff");}else{buttonState='true';$(this).removeClass("iToggleOff").addClass("iToggleOn");}
if((sectionID=='mobileVideoPreview')&&(buttonState=='true'))
createCookie('mobileVideoPreview','1',365);else if((sectionID=='mobileVideoPreview')&&(buttonState=='false'))
eraseCookie('mobileVideoPreview');else
settingsToggle(buttonState,sectionID);});$("#simpleSearchText").focus(function(){$(this).attr('value','');});if(isAppleDevice()){$("li.videoChannel ul li").click(function(){currentVideoCssID=$(this).attr('id');currentVideoID=currentVideoCssID.split('-');currentVideoID=currentVideoID[1];if(readCookie('mobileVideoPreview')){window.clearInterval(switchThumbnails);$("ul#miVideo div.image").show();$("ul#miVideo div.summary").show();$("#"+currentVideoCssID+" div.image").hide();$("#"+currentVideoCssID+" div.summary").hide();isVisible=$("#"+currentVideoCssID+" .thumbnailPreview").css('display');if(isVisible=='none'){}else{window.location=$("#"+currentVideoCssID+" a.videoPlayURL-MP4").attr('href');}
$("div.thumbnailPreview").hide();thumbnailUrlList=[];loopCount=0;$("#"+currentVideoCssID+" div.thumbnailPreview input").each(function(){thumbnailUrlList[loopCount]=$(this).val();loopCount++;});$("#"+currentVideoCssID+" div.thumbnailPreview div.vmixThumbnailPreview img.thumbnailCurrent").attr('src',thumbnailUrlList[0]);$("#"+currentVideoCssID+" div.thumbnailPreview div.vmixThumbnailPreview img.thumbnailOnDeck").attr('src',thumbnailUrlList[1]);$("#"+currentVideoCssID+" div.thumbnailPreview div.vmixThumbnailPreview img.thumbnailThird").attr('src',thumbnailUrlList[2]);$("#"+currentVideoCssID+" .thumbnailPreview").show();imageSwitch=3;switchThumbnails=window.setInterval(function(){$("#"+currentVideoCssID+" div.thumbnailPreview div.vmixThumbnailPreview img.thumbnailThird")
.addClass("awaitingThumbnailClass")
.removeClass("thumbnailThird");$("#"+currentVideoCssID+" div.thumbnailPreview div.vmixThumbnailPreview img.thumbnailCurrent")
.addClass('thumbnailThird')
.removeClass('thumbnailCurrent');$("#"+currentVideoCssID+" div.thumbnailPreview div.vmixThumbnailPreview img.thumbnailOnDeck")
.addClass('thumbnailCurrent')
.removeClass('thumbnailOnDeck');$("#"+currentVideoCssID+" div.thumbnailPreview div.vmixThumbnailPreview img.awaitingThumbnailClass")
.addClass('thumbnailOnDeck')
.removeClass('awaitingThumbnailClass');$("#"+currentVideoCssID+" div.thumbnailPreview div.vmixThumbnailPreview img.thumbnailThird").attr('src',thumbnailUrlList[imageSwitch]);imageSwitch++;},1700);}else{window.location=$("#"+currentVideoCssID+" a.videoPlayURL-MP4").attr('href');}});}else{}
if(windowHREF.match('galleries')||windowHREF.match('gallery')){}
if(windowHREF.match(/\d{4}(\/\d{2}){2}/)){$("#story_comments_count a").click(function(){toggleComments();return(false);});tmpStoryCookie=readCookie('mobileStoryTextSize');if(tmpStoryCookie){$("#storyBody p").css('font-size',tmpStoryCookie);}
if(windowHREF.match('Comments_Container')){toggleComments();}}
});var isThemeSwitched=0;function switchTheme(themeName){if(isThemeSwitched==0){$("body").addClass(themeName);isThemeSwitched=1;mainMenuDisplay();}else{$("body").removeClass(themeName);isThemeSwitched=0;mainMenuDisplay();}}
var mouseDownX;var mouseUpX;function experimentalFlick(){document.addEventListener('touchstart',touchHandler,false);document.addEventListener('touchmove',touchHandler,false);document.addEventListener('touchend',touchHandler,false);document.addEventListener('touchcancel',touchHandler,false);function touchHandler(e){var touch=e.touches[0];e.preventDefault();if(e.type=="touchstart"){$("#galleryImageCurrentCaption").html("TOUCH START: "+touch.pageX);mouseDownX=touch.pageX;}
else if(e.type=="touchmove"){e.preventDefault();if((mouseDownX-touch.pageX)<-50){$("#galleryImageCurrentCaption").html("SWIPE RIGHT: "+(mouseDownX-touch.pageX));}else if((mouseDownX-touch.pageX)>50){$("#galleryImageCurrentCaption").html("SWIPE LEFT: "+(mouseDownX-touch.pageX));}
}
else if(e.type=="touchend"||e.type=="touchcancel"){$("#galleryImageCurrentCaption").html("TOUCH CANCEL: "+touch.pageX);mouseUpX=touch.pageX;$("img#currentImage").addClass("slideMeRight");}}
}
function trackChannelExpansion(){$('.channel h2').click(function(){currentID=$(this).attr('id');if(currentID=="h2MostRecommended"){pageTracker._trackEvent("Mobile","Channel Expansion","Most Recommended");}else if(currentID=="h2MostCommented"){pageTracker._trackEvent("Mobile","Channel Expansion","Most Commented");}else if(currentID=="h2MostPopular"){pageTracker._trackEvent("Mobile","Channel Expansion","Most Popular");}else if(currentID=="h2Video"){pageTracker._trackEvent("Mobile","Channel Expansion","Video");}else{sectionID=$(this).attr('id').split('h2');sectionTitle=$(this).attr('title');pageTracker._trackEvent("Mobile","Channel Expansion","Section - "+sectionTitle+"( "+sectionID+" )");}});}
function trackMoreStories(){$('.fetchMoreStories').click(function(){sectionID=$(this).attr('id').split('moreStories');sectionTitle=$(this).attr('title');pageTracker._trackEvent("Mobile","Fetch More Stories",sectionTitle+"( "+sectionID[1]+" )");});}
function trackSettingsToggle(){$('.iToggle').click(function(){sectionTitle=$(this).attr('title');if($(this).attr('class').match('iToggleOn'))
pageTracker._trackEvent("Mobile","Settings - Toggle Off",sectionTitle+"( "+$(this).attr('id')+" )");if($(this).attr('class').match('iToggleOff'))
pageTracker._trackEvent("Mobile","Settings - Toggle On",sectionTitle+"( "+$(this).attr('id')+" )");});}
function trackTopStoryClick(){$('.topStoryLink').click(function(){pageTracker._trackEvent("Mobile","Top Story Click");});}
function trackVideoPlay(){$("li.videoChannel ul li").click(function(){pageTracker._trackEvent("Mobile","Video Play");});}
function trackStoryCommentsView(){$("#storyComments").click(function(){pageTracker._trackEvent("Mobile","Story","Comments View");});}
function trackStoryRecommendation(){$("span#recommendation a").click(function(){pageTracker._trackEvent("Mobile","Story","Recommendation");});}
function trackMenuOpen(){$('#menuLink').click(function(){pageTracker._trackEvent("Mobile","Menu","Open");});}
function trackStoryMenuEmail(){$("#emailStory").click(function(){pageTracker._trackEvent("Mobile","Menu","Email Story");});}
function trackStoryMenuTextIncrease(){$("#storyTextBig").click(function(){pageTracker._trackEvent("Mobile","Menu","Text Increase");});}
function trackStoryMenuTextDecrease(){$("#storyTextSmall").click(function(){pageTracker._trackEvent("Mobile","Menu","Text Decrease");});}
function trackMenuLoginClick(){$(".menuLogin a").click(function(){pageTracker._trackEvent("Mobile","Menu","Login");});}
function trackMenuHomeClick(){$(".menuHome a").click(function(){pageTracker._trackEvent("Mobile","Menu","Home");});}
function trackMenuChannelsClick(){$(".menuChannels a").click(function(){pageTracker._trackEvent("Mobile","Menu","Channels");});}
function trackMenuGalleriesClick(){$(".menuGalleries a").click(function(){pageTracker._trackEvent("Mobile","Menu","Galleries");});}
function trackMenuSettingsClick(){$(".menuSettings a").click(function(){pageTracker._trackEvent("Mobile","Menu","Settings");});}
function trackMenuFullClick(){$(".menuFull a").click(function(){pageTracker._trackEvent("Mobile","Menu","Full Site");});}
function trackMenuCloseClick(){$(".menuClose a").click(function(){pageTracker._trackEvent("Mobile","Menu","Close Menu");});}
function initiateEventTracking(){trackChannelExpansion();trackMoreStories();trackSettingsToggle();trackTopStoryClick();trackVideoPlay();trackStoryCommentsView();trackStoryRecommendation();trackMenuOpen();trackStoryMenuEmail();trackStoryMenuTextIncrease();trackStoryMenuTextDecrease();trackMenuLoginClick();trackMenuHomeClick();trackMenuChannelsClick();trackMenuGalleriesClick();trackMenuSettingsClick();trackMenuFullClick();trackMenuCloseClick();}

