Event.observe(window, 'load', function() { 

	//checkStatusAndBuild();
	//ms_initMrv();

	//setup browser obj
	browser = new Object();
	browser.name = jQuery.browser.name;
	browser.version = jQuery.browser.version;
		
	// Eventlisteners
	// my news
	$('all_followed').observe('click', swapMyNews);
	$('recently').observe('click', swapMyNews);
	$('saved').observe('click', swapMyNews);
	$('mycomments').observe('click', swapMyNews);
	$('mysettings').observe('click', swapMyNews);
	$('fbfriends').observe('click', swapMyNews);



	// my alerts
	$('breaknews_btn').observe('click', swapMyAlerts);
	$('programming_alerts_btn').observe('click', swapMyAlerts);
	$('email_alerts_btn').observe('click', swapMyAlerts);
	$('polbn_btn').observe('click', swapMyAlerts);
	
	jQuery(".overlay_close").click(function () { 
		jQuery('#profile_overlaybg').hide();
		jQuery('#overlay_cont').hide();
		jQuery('.overlay_content').hide();
	});	
	
	jQuery(".example_cont").click(function () { // example overlays
		profileOverlayClose();
		jQuery('.overlay_content').hide();
	});	
	
	jQuery(".news_unsubscribe2").click(function () { // newsletter unsub button on overlay
		cnn_newsletterChange = jQuery(this).parent().attr('id');
		//console.log(cnn_newsletterChange);
	});	
	
	jQuery(".news_subscribe2").click(function () { // newsletter subscribe button on overlay
		cnn_newsletterChange = jQuery(this).parent().attr('id');
		//console.log(cnn_newsletterChange);
	});	

	jQuery(".news_unsubscribe").click(function () {  // newsletter unsub button on main
		cnn_newsletterChange = jQuery(this).parent().attr('id');
		//console.log(cnn_newsletterChange);
		
	});	
	
	jQuery(".news_subscribe").click(function () { // newsletter subscribe button on main
		cnn_newsletterChange = jQuery(this).parent().attr('id');
		//console.log(cnn_newsletterChange);
	});
	
	jQuery(".news_subscribe3").click(function () { // newsletter subscribe button on main
		profileOverlayClose();
		showOverlay('profile_signin_overlay');
	});	
	
	newsletterReload = 0;
	jQuery("#profile_newsletter_overlay .overlay_close").click(function () { 
		//jQuery("iframe").remove();
		if (newsletterReload > 0) {
			location.hash = '#newsletters';
			location.reload(true);
		}
	});	
	
	jQuery("#overlaybtn").click(function () { // temp
		var viewheight = document.body.clientHeight;
		var theStyle = new Object;
		theStyle.height = viewheight + "px";
		$('profile_overlaybg').setStyle( theStyle ); // height of transparent overlay bg
		jQuery('#profile_overlaybg').show();
		jQuery('#overlay_cont').show();
		jQuery('.overlay_content').show();
	});	
	
	jQuery("#goalerts").click(function () { // go btn alerts
		jQuery('#pemail_ovly_state1').hide();
		jQuery('#pemail_ovly_state2').show();
		jQuery('.pemail_createalt').show();
		//jQuery('#pemail_ovly_state1').hide();
		jQuery('#alertActionTitle').html('Create a new alert');
		var alertname = jQuery('#emailalerts').val();
		jQuery('#create_alert_name').val(alertname);
		jQuery('#emailalerts').val('');
		jQuery('#create_alert_key').val('');
		jQuery('#create_alert_exclude').val('');
		jQuery('.pemail_createalt2').hide();
	});	
	
	jQuery(".pemail_createalrt").click(function () { // save alerts
		jQuery('#pemail_ovly_state2').hide();
		jQuery('#pemail_ovly_state1').fadeIn();
		jQuery('#emailalerts').val('');
		jQuery('#create_alert_name').val('');
		jQuery('#create_alert_key').val('');
		jQuery('#create_alert_exclude').val('');
	});	
	
	jQuery(".pemail_createalrt2").click(function () { // editalerts
		jQuery('#pemail_ovly_state2').hide();
		jQuery('.pemail_createalt2').hide();
		jQuery(".pemail_createalt").show();

		jQuery('#pemail_ovly_state1').fadeIn();
		jQuery('#emailalerts').val('');
		jQuery('#create_alert_name').val('');
		jQuery('#create_alert_key').val('');
		jQuery('#create_alert_exclude').val('');
	});	
	passwordSet = 0;
	jQuery("#editmy_oldpass, #editmy_newpass, #editmy_confirmpass").click(function () { 
		passwordSet++;
	});	
	
	jQuery("#editmy_oldpass, #editmy_newpass, #editmy_confirmpass").focus(function () { 
		passwordSet++;
	});	
	
	jQuery("#lstate").click(function () { // temp
		jQuery("#cnn_maincntnr").toggleClass('loggedin');
		jQuery("#cnn_maincntnr").toggleClass('loggedout');
	});	
	
	jQuery("#salert").click(function () { // temp
		 ms_getAlerts('ms_uiGetAlerts');
	});	
	
	/*jQuery(window).scroll(function () { //keep overlay centered
		if (jQuery("#overlay_cont").is(':visible')) { 
			//centerDivOfPage('overlay_cont'); 
		}
    });*/
	
	jQuery("input[type=file]").filestyle({ //restyle the file upload box
		image: "/.element/img/3.0/profile/browse.gif",
		imageheight : 28,
		imagewidth : 88,
		width : 173
	});
	
	//my alerts
	jQuery(".my_alerts_btn h3").hover( 
		  function () {
			jQuery(this).css({ "color" : "#ca0002"  });
		  }, 
		  function () {
			jQuery(this).css({ "color" : "#004276"  });
		  }
	);
	
	jQuery(".browsebtn").hover( 
		  function () {
		  	jQuery(this).css({ "background-image" : "url(/.element/img/3.0/profile/browse_over.gif)" });
		  }, 
		  function () {
		  	jQuery(this).css({ "background-image" : "url(/.element/img/3.0/profile/browse.gif)" });
		  }
	);
});

function showProfileOverlay(divid) {
	var theHeight = jQuery(document).height();
	jQuery("#profile_overlaybg").css({ "height" : theHeight  });
	$("profile_overlaybg").show();
	$(divid).show();
	centerDivOfPage(divid);
}

function profileOverlayClose() {
	jQuery('#profile_overlaybg').hide();
	jQuery('#overlay_cont').hide();
	jQuery('.overlay_content').hide();
 }

function checkStatusAndBuild() {

	if (!ms_isNull(allCookies['authid'])) {
		if(!ms_isNull(allCookies['displayname'])) { 
			var username = allCookies['displayname'];
		}
		else if (!ms_isNull(allCookies['firstName'])) { 
			var username = allCookies['firstName'].replace(/\+/g, " "); 
			
		}
	}
				
	if (Member.isLoggedIn('cnn')) {
		
		var cnnUserName = (Member.isLoggedIn('facebook') && Member.isConnected()) ? CNN_FB_user.accounts[CNN_FB_user.namePref].displayName : CNN_FB_user.accounts.cnn.displayName;
		
		$('cnn_maincntnr').className = 'loggedin';
		$('displayname').update(cnnUserName);
		
		//commented out to switch to CSI method of overlays to edit my details
		//$('editmy_username').update(username);
		
		
		$('cnn_ftopicshdr1').update('ALL FOLLOWED TOPICS'); //was "ALL FOLLOWED TOPICS" bstephens 11/13
		$('cnn_ftopicshdr2').update('ALL FOLLOWED TOPICS'); //was "ALL FOLLOWED TOPICS" bstephens 11/13
		
		//These all need to be updated to use new MSIB
		ms_getEmails('ms_uiGetEmails');
		ms_initNewsletter();
		ms_initAlert();
		//ms_initOverlay();
		ms_initProfile();
	
	}

}

function showAvatar() {

	var screenname = CNN_FB_user.accounts.cnn.displayName;
	if (screenname === '') { screenname = 'null' }
	var avatarsrc = "http://avatar.cnn.com/people/" + screenname + "/avatar/70.png?" + (new Date().getTime());
	
	if(Member.isConnected() && !Member.isLoggedIn('cnn')) {
			
				FB.api({
					method: 'fql.query',
					query: 'SELECT pic_square FROM profile WHERE id=' + FB.getAuthResponse().userID
				},
				function(response) {
					var user = response[0];
					$('user_avatar_img').src = user.pic_square;
					
				});
			
	} else { 
		$('user_avatar_img').src = avatarsrc;
	}

	//$('avatar_60x60').src = avatarsrc;

 }
var myAlertsArray = new Array("breaknews_btn","programming_alerts_btn","email_alerts_btn", "polbn_btn");
var myAlertsContentArray = new Array("breaking_news","programming_alerts","email_alerts","polbn_alerts");
function swapMyAlerts() { // my alerts module
	for (var n in myAlertsArray) {
		if (this.id == myAlertsArray[n]) {
			$(myAlertsArray[n]).hide();
			$(myAlertsContentArray[n]).show();
		} else {
			if (n==0 || n==1 || n==2 || n==3) { //prototype workaround, n to length
				$(myAlertsArray[n]).show();
				$(myAlertsContentArray[n]).hide();
			}
		}
	}
}


var myNewsArray = new Array("fbfriends", "all_followed","recently","saved","mycomments","hottopics","mysettings");

var myNewsContentArray = new Array("fbfriends_topics", "all_followed_topics","recently_topics","saved_topics","mycomments_topics","hottopics_topics", "mysettings_topics");

var myNewsStoryContainerArray = new Array("stories_fbfriends_topics", "stories_followed_topics","stories_recently_topics","stories_saved_topics","stories_mycomments_topics","stories_hottopics_topics", "stories_mysettings_topics");

var cnn_mynewscurr = 'recently';

function cnn_loadMyNews(mynews_id) {

	//hide current
	jQuery("#"+cnn_mynewscurr).show();
	jQuery("#"+cnn_mynewscurr+"_on").hide();						
	jQuery("#"+cnn_mynewscurr+"_topics").hide();
	jQuery("#stories_"+cnn_mynewscurr+"_topics").hide();

	
	//show new
	jQuery("#"+mynews_id+"_on").show();
	jQuery("#"+mynews_id).hide();
	jQuery("#stories_"+mynews_id+"_topics").fadeIn();
	
	//console.log('Initializing My News: ' + mynews_id);
	//cnn_prfmynwsobj[mynews_id].li_mode.init();

	//Determine whether to do logged in or logged out init
	if(Member.isLoggedIn('cnn')) { cnn_prfmynwsobj[mynews_id].li_mode.init(); }
	else { cnn_prfmynwsobj[mynews_id].lo_mode.init(); }

	cnn_mynewscurr = mynews_id;
	
}

function setDefaultTabId() {
	var setTabChoice = location.href.toQueryParams()['setTab'];
	if (typeof setTabChoice !== 'undefined') { //passed in URL
		//console.log('tab set: url');
		this.id = setTabChoice;
	} else if (Member.isConnected()){ //logged into FB
		//console.log('tab set: connected');
		this.id = 'fbfriends';
	} else if (typeof this.allCookies["profile.lastNewsID"] !== 'undefined') { //sticky cookie
		//console.log('tab set: cookie');
		this.id = this.allCookies["profile.lastNewsID"];
	} else {
		//console.log('tab set: default recently');
		this.id = 'recently';	
	}

}

//TODO: Add all the little if / else clause that handles cases into the my_news.config init fuctions and drop this old function for the new one above.
function swapMyNews() { // my news module

	cnn_mynewscurr = this.id;
	
	for (var n in myNewsArray) {

		if (this.id == myNewsArray[n]) {

			jQuery("#"+myNewsArray[n]+"_on").show();
			jQuery("#"+myNewsArray[n]).hide();
			jQuery("#"+myNewsStoryContainerArray[n]).fadeIn();

			//fade last 10 viewed message
			if (this.id == "recently") { 
				jQuery("#last10view").fadeIn();
			}
			else {
				jQuery("#last10view").fadeOut('fast');
			}

			if (this.id == "all_followed" || this.id == "hottopics" ) { 
				//console.log('calling AFT');
				cnn_mynloadAFT();
				jQuery("#stay12").fadeIn();
			}
			else {
				jQuery("#stay12").fadeOut('fast');
			}
			
			if(this.id == "saved") {
				cnn_myndataload('stories_saved_topics');
			}
			
			//console.log('Initializing My News: ' + this.id);

			//Determine whether to do logged in or logged out init
			if(Member.isLoggedIn('cnn')) { cnn_prfmynwsobj[this.id].li_mode.init(); }
			else { cnn_prfmynwsobj[this.id].lo_mode.init(); }

			
			if (myNewsArray[n] == 'all_followed' || myNewsArray[n] == 'hottopics' ) { 
				if ( browser.name == "msie" && browser.version == "6.0" || browser.name == "msie" && browser.version == "7.0" ) {
					jQuery("#"+myNewsContentArray[n]).show();
				} else { 
					jQuery("#"+myNewsContentArray[n]).slideDown();
				}
			}
			
			//adding stickyness
			CNN_setCookie('profile.lastNewsID', this.id, 24 * 30 * 12, '/', document.domain);
			
			location.hash = "#mynewstop2"; //reset for webkits
			location.hash = "#mynewstop";
		}
		else {
			if (n==0 || n==1 || n==2 || n==3 || n==4 || n==5 || n==6 || n==7) { //prototype workaround, n to length
				jQuery("#"+myNewsArray[n]).show();
				jQuery("#"+myNewsArray[n]+"_on").hide();						
				jQuery("#"+myNewsContentArray[n]).hide();
				jQuery("#"+myNewsStoryContainerArray[n]).hide();
			}
		}
	}
}

var cnn_prfnwstggls = Array();
function cnn_prfnwsTggl(list_id) { // newsletters
	//check for open
	if(cnn_prfnwstggls[list_id] == 1) {
		$('cnn_prfnwsl' + list_id).removeClassName('cnn_prfnwsolon');
		cnn_prfnwstggls[list_id] = 0;
	}
	else {
		$('cnn_prfnwsl' + list_id).addClassName('cnn_prfnwsolon');
		cnn_prfnwstggls[list_id] = 1;
	}
}

// edit my details - avatar

function errorScreenName() {
	$('screennameerror').show();
	var errordelay = function() { $('screennameerror').hide(); };
	errordelay.delay(3); 
}
document.domain = "cnn.com";
function avatarUploadOnLoad(window) {
 //
}
function updateAvatarImg() {
	var rawAvatarSrc = $('user_avatar_img').src;
	if (rawAvatarSrc.indexOf('avatar') > -1) {
		var avatarsrc = "http://avatar.cnn.com/people/" + allCookies.displayname + "/avatar/70.png?" + (new Date().getTime());
		//var avatarsrc = 'http://i.cdn.turner.com/cnn/.element/img/2.0/sect/connect/avatar.gif';
		if ($('avatar_60x60')) {
			$('avatar_60x60').src = avatarsrc;
		}
		if ($('user_avatar_img')) {
			$('user_avatar_img').src = avatarsrc;
		}
	}
}
function avatarUploadStatus(success,code,message) {
	if (success) {
	   updateAvatarImg();
		//jQuery('#cnnConnChangeMyPhoto').hide();
		//jQuery('#cnnConnProfile-screenName-container').show();
		//frames['uploadFrame'].location.replace('http://avatar.cnn.com/services/profile/avatar'); 
		updateAvatarImg();
	} else {
		//frames['uploadFrame'].location.replace('http://avatar.cnn.com/services/profile/avatar'); 
		updateAvatarImg();
	}
	/* Result code list:
		FIELD_ERROR(-1,"Internal error"),
		UNAUTHORIZED(-100,"Unauthorized"), // User not logged in or doesn't have screen name.
		NO_FILE(-200,"No file specified"),
		INVALID_FILE(-205,"Unsupported file type or file is corrupt"),
		IMAGE_TOO_BIG(-210,"Image dimensions too large"),
		UPLOAD_SUCCESS(200,"Upload successful"),
		DELETE_SUCCESS(250,"Delete successful");
	*/
}

function findTargetFrame(name) {
	return document.getElementById("uploadFrame");
}

function findContentDoc(iframe) {
	var cdoc = iframe;
	if (cdoc.contentWindow) cdoc = cdoc.contentWindow;
	if (cdoc.contentDocument) cdoc = cdoc.contentDocument;
	if (cdoc.document) cdoc = cdoc.document;
	return cdoc;
}
function doUpload() {
	var targetFrame = findTargetFrame();
	var targetForm = findContentDoc(targetFrame).getElementById("uploadForm");
	targetForm.submit();
}


// !!#!! jquery plugin - filestyle
/*
 * Style File - jQuery plugin for styling file input elements
 *  
 * Copyright (c) 2007-2008 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Based on work by Shaun Inman
 *   http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
 *
 * Revision: $Id: connect_profile.js,v 1.8 2010/04/20 19:56:04 wsheldon Exp $
 *
 */

(function($) {
    $.fn.filestyle = function(options) {
        var settings = {
            width : 250
        };
        if(options) {
            $.extend(settings, options);
        };
        return this.each(function() {
            var self = this;
            var wrapper = $("<div>")
                            .css({
                                "width": settings.imagewidth + "px",
                                "height": settings.imageheight + "px",
                                "background": "url(" + settings.image + ") 0 0 no-repeat",
                                "background-position": "right",
                                "display": "inline",
                                "position": "absolute",
                                "overflow": "hidden"
                            }).addClass('browsebtn');
                            
            var filename = $('<input class="file">')
                             .addClass($(self).attr("class"))
                             .css({
                                 "display": "inline",
                                 "width": settings.width + "px"
                             });

            $(self).before(filename);
            $(self).wrap(wrapper);
            $(self).css({
                        "position": "relative",
                        "height": settings.imageheight + "px",
                        "width": settings.width + "px",
                        "display": "inline",
                        "cursor": "pointer",
                        "opacity": "0.0"
                    });

            if ($.browser.mozilla) {
                if (/Win/.test(navigator.platform)) {
                    $(self).css("margin-left", "-142px");                    
                } else {
                    $(self).css("margin-left", "-168px");                    
                };
            } else {
                $(self).css("margin-left", settings.imagewidth - settings.width + "px");                
            };
            $(self).bind("change", function() {
                filename.val($(self).val());
            });
        });
    };
})(jQuery);




// !!#!! jquery plugin - browser detection
(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);})(jQuery);


