var refreshPage = 'false';
var refreshAddress = '';
var builderType = "";
var showMyPoints = false;
var lbFrame;
var lb_style = '1';
var lb_id = 'lightbox';
var lb_overlay = 'overlay';
var lb_popup_frame = 'popup-frame';
var lb_popup_body = 'popup-body';
var lb_popup_container = 'popup-container';
var lb_photoholder = 'photoHolder';
var lb_mainframe = 'main';
var lb_cancel_conf_menu = 'cancelConfMenu';
var lb_cancel_msg = 'cancelMessage';
var lb_popup_top = 340;
var lb_popup_left = 0;
var lb_hide_ads = true;
var updated = false;
var stat;
var sliderOpen = false;
var secureRetUrl='';

/******************************** START NEW GENERIC BUILDER FUNCTIONS *****************************************/

$(document).ready(LB_init);

//add thickbox to href elements that have a class of .thickbox
function LB_init(){
    $("a.popup,button.popup").bind('click',function(){
      var t = this.title || this.name || null;
            var href = $(this).attr('href');
            var params = $(this).attr('params') || '';
            var height = parseInt($(this).attr('ht'));
            var refresh = $(this).attr('ref');
            var refreshUrl = $(this).attr('refUrl') || '';
      launchPopup(t, href, params, height, '', refresh, refreshUrl);
      this.blur();
      return false;
    });
    checkHideAds();
}

/*
   Example Use:
     launchPopup('events','/community/event/rsvplist','&eventId=1&rsvpSortType=3','470','627',false,'doMagic();return false');
   Parameter Breakdown:
     REQUIRED:
       type:announcements,dating,events,guestbook,maps,messageboards,photos,survey
       iframeUrl: This is the url of what you want to show on the inside of the modal window
     OPTIONAL:
       params: For parameters that you need passed to the iframe
       height / width: To adjust the size of the modal window
       refresh: Make it so that when clicking the close popup button doesn't cause the page to refresh
       refreshUrl: Allow for a different url to be called on close
   Note:  By changing the height and width of the modal window the iframe size will adjust accordingly.
         To add more types, you just need to add a png graphic to /graphics/builder/headers/
*/

    function launchPopup(type,iframeUrl,params,height,width,refresh,refreshUrl,doNotScroll,secure){
        setLBStyle(lb_style);
        var e = top.document.getElementById(lb_id);
        var stillLoading = false;
        $('#'+lb_photoholder).hide();
        $('#'+lb_popup_container).show();
        try {
            if ( typeof e == 'undefined' || e == null){
                stillLoading = true;
            }
            else if ( e.style.display == 'none' || e.style.display == '' ) {
                stillLoading = false;
            }
        }
        catch(e){stillLoading = true;}

        if ( !stillLoading ){
            window.popupOpen = true;
            top.resPop = false;
            setAnchor = '';
            setUpdated(false);

            if ( e.style.display == 'none' || e.style.display == ''){
                if ( typeof refresh == 'undefined' || refresh   == null  || refresh    == '') {
                    refreshPage    = 'true';
                }
                else {
                    refreshPage = refresh;
                }
                if (typeof refresh == 'undefined' || refreshUrl == null || refreshUrl == '') {
                    refreshAddress = '';
                }
                else {
                    refreshAddress = refreshUrl;
                }
                if ( document.getElementById(lb_mainframe).src.indexOf('main.jsp') < 0 ){
                    if(doNotScroll != true) { window.scrollTo(0,0); }

                    if (document.getElementById('popupTitle'))
                      document.getElementById('popupTitle').innerHTML = type;
                    if( top.getPageHeight() < 2400)
                      $("#"+lb_overlay).css("height", 2400);
                    else
                      $("#"+lb_overlay).css("height", top.getPageHeight());
                    if (lb_style == '1') {
                      $("#"+lb_popup_body).attr("height", height);
                      $("#"+lb_mainframe).css("height", height - 23);
                    } else if (lb_style == '2') {
                      $("#"+lb_popup_frame).css("height", height+8 );
                    }

                    hideAllSelect();
                    hideAllAds();
                    e.style.display = 'block';
                    var href = top.location.href;
                    href = href.substring(0, href.indexOf('com') + 3);
                    //Check for custom ports
                    href += (top.location.href.split(href)[1].indexOf(":")==0)?top.location.href.split(href)[1].split("/")[0]:"";
                    if ( params.indexOf('&') == 0){
                        params = params.substring(1, params.length);
                    }
                    // Check for photos sub-domain (Perl issue)
                    if ( href.indexOf('photos.') > -1 ){
                        href = href.replace(/photos/, "www");
                    }
                    else if ( href.indexOf('secure.') > -1 ){
                        href = href.replace(/secure/, "www");
                    }
                    if ( href.indexOf('https') > -1 && (typeof secure == 'undefined' || !secure) ){
                      secureRetUrl=top.location.href.split(href)[1];                    	
                      href = 'http://' + href.substring(8, href.indexOf('com') + 3);
	                  if(secureRetUrl!='')  {
	                    params+="&secureRetUrl="+secureRetUrl;
	                  }                          
                    }
                    //Replace albumType param with photoType
                    params = params.replace("albumType", "photoType");
                    params = escape(params);
                    href += '/profile/builder/frames/main.jsp?lbSrc=' + iframeUrl + '?' + params;
                    document.getElementById(lb_mainframe).src = href;
                    setLBLayout(type, lb_style, width, height);
                }
                else {
                    popupSetup(e, type, height, width, iframeUrl, params, null, doNotScroll);
                }
            }
        }
    }
	
	function resetOverlayHeight(){
      $("#"+lb_overlay).css("height", top.getPageHeight());
    }
	
    function setLBLayout(type, p_style, width, height) {
	      if( type == 'Classmates maps' && iframeUrl.indexOf('indi_container') < 0 ) {
            $("#"+lb_popup_container).css("width", 817);
        } else if (type == 'Shortlists' ) {
            $("#"+lb_popup_container).css("width", width);
        } else if (p_style == '1'){
            $("#"+lb_popup_container).css("width", 675);
        } else {
        	$("#popup_canvas").css("width", width);
        	$("#popup_canvas").css("height", height);
        	if (lb_popup_left == 0) 
            lb_popup_left = top.getPageWidth()/2 - width/2;
            
            $("#"+lb_popup_frame).css({left: lb_popup_left, top: lb_popup_top});
            // set up shadow
            var frame_height = $("#popup_canvas")[0].offsetHeight;
            var frame_width = $("#popup_canvas")[0].offsetWidth;
            $("#bl_" + lb_popup_frame + "_Shadow").css ("width", 8);
            $("#tr_" + lb_popup_frame + "_Shadow").css ("height", 8);
            $("#br_" + lb_popup_frame + "_Shadow").css ({height: 8,width: 8});
            $("#b_" + lb_popup_frame + "_Shadow").css ("width", frame_width - 8);
            $("#r_" + lb_popup_frame + "_Shadow").css ({height: frame_height - 8,width: 8});
            $("#"+lb_cancel_conf_menu).css({left: Math.round(lb_popup_left + width - 100) , top:  Math.round(lb_popup_top + 35)});
        }
    }

    function popupSetup(e, type, height, width, iframeUrl, params, secure, doNotScroll){
        if(doNotScroll != true) { window.scrollTo(0,0); }

        if (document.getElementById('popupTitle'))
          document.getElementById('popupTitle').innerHTML = type;
        if( top.getPageHeight() < 2400)
          $("#"+lb_overlay).css("height", 2400);
        else
          $("#"+lb_overlay).css("height", top.getPageHeight());
        if (lb_style == '1') {
          $("#"+lb_popup_body).attr("height", height);
          $("#"+lb_mainframe).css("height", height - 23);
        } else if (lb_style == '2') {
                $("#"+lb_popup_frame).css("height", height+8 );
        }
        
        try{
            //Replace albumType param with photoType
            params = params.replace("albumType", "photoType");
            getLbFrame().src = iframeUrl + '?' + params;
            hideAllSelect();
            hideAllAds();
            e.style.display = 'block';
            setLBLayout(type,lb_style,width,height);
        }
        catch (e){
            // Must be https page. Need to reset the main.jsp src to http.
            var href = top.location.href;
            href += (top.location.href.split(href)[1].indexOf(":")==0)?top.location.href.split(href)[1].split("/")[0]:"";
            if ( href.indexOf('https') > -1 ){
                if ( typeof secure == 'undefined' || !secure ){
                  href = 'http://' + href.substring(8, href.indexOf('com') + 3);
                  if(secureRetUrl!='')  {
                    params+="&secureRetUrl="+secureRetUrl;
                  }                  
                }
                params = escape(params);                
                $('#'+lb_id).show();
                href = href + '/profile/builder/frames/main.jsp?lbSrc=' + iframeUrl + '?' + params;
                // Check for secure sub-domain
                if ( href.indexOf('secure.') > -1 ){
                    href = href.replace(/secure/, "www");
                }
                document.getElementById(lb_mainframe).src = href;
                hideAllSelect();
            }
        }
    }

  
  function hideAllSelect(){
      if ( isIE6() ){
          $('select').hide();
      }
  }

  function showAllSelect(){
      if ( isIE6() ){
          $('select').show();
      }
  }

  function hideAllAds(){
    if (lb_hide_ads) {
      $('div.OAS').hide();
      $('div.adTmp').hide();
    }
  }

  function showAllAds(){
    if (lb_hide_ads) {
      $('div.OAS').show();
      $('div.adTmp').show();
    }
  }
    
  function checkHideAds(){
    if ( $('#'+lb_id).css('display') == 'block' ){
        hideAllAds();
    }
  }
 

  function closeLBFrame(){
  
      if(top.document.getElementById("slideErrorsDiv") != null) {
        top.document.getElementById("slideErrorsDiv").style.display="none";
      }
      if ( sliderOpen ){
        top.hideMemberConduct();
      } else {
          if ( refreshPage == 'confirm' ){
              closeLBFrameConf(stat);
          } else {
            if ( refreshPage == 'false'){
                if ( refreshAddress != ''){
                  top.location.href = refreshAddress;
                }
            } else if ( refreshPage == 'conditional'){
                if (updated){
                    if ( typeof setAnchor != 'undefined' && setAnchor != ''){
                      LB_remove();
                      top.location.href = top.location + top.setAnchor;
                      return;
                    } else {
                      pageReload();
                      LB_remove();
                      return;
                    }
                }
            } else {
                pageReload();
                return;
            }
            window.popupOpen = false;
            LB_remove();
            if(top.closeCallBack) {
              top.closeCallBack();
              top.closeCallBack = null;
            }
          }
      }
      
  }
 
  function closeLBFrameConf() {
    if(stat!=true) {
      try {
      if($("#"+lb_mainframe)[0] && ($('#'+lb_mainframe)[0].contentWindow.document.getElementById('lbFrame') && ($('#'+lb_mainframe)[0].contentWindow.document.getElementById('lbFrame').contentWindow.requiresCloseConfirmation && ($('#'+lb_mainframe)[0].contentWindow.document.getElementById('lbFrame').contentWindow.requiresCloseConfirmation==true)))) {
        try {
          if($('#'+lb_mainframe)[0].contentWindow.document.getElementById('lbFrame').contentWindow.confMessage) {
            $("#"+lb_cancel_msg).html($('#'+lb_mainframe)[0].contentWindow.document.getElementById('lbFrame').contentWindow.confMessage);
          }
        } catch (ex){ $("#"+lb_cancel_msg).html("Are you sure you want to leave before saving?"); }
        $("#"+lb_cancel_conf_menu).show();
        makeShadow(lb_cancel_conf_menu);
        if (lb_style != '2') {
          $(document).bind("click", function() {
            hideCancelMenu();
          });
        }
        try {
          $($('#'+lb_mainframe)[0].contentWindow.document.getElementById('lbFrame').contentWindow.document).bind("click", function() {
            hideCancelMenu();
          });
        } catch(ex) {}
      } else {        
          if ( updated ){
              pageReload();
          }
          LB_remove();
      }
      } catch(e) {
        hideCancelMenu();
        LB_remove();
      }
    } else {
      hideCancelMenu();
      LB_remove();
    }
  }

  function hideCancelMenu() {
    setStat(false);
    $(document).unbind("click", function() {
      hideCancelMenu();
    });
    try {
      $($('#'+lb_mainframe)[0].contentWindow.document.getElementById('lbFrame').contentWindow.document).unbind("click", function() {
        hideCancelMenu();
      });
    } catch(ex){}
    $(".wrap").removeClass("wrap").remove();
    $("#"+lb_cancel_conf_menu).hide();
  }

  function LB_remove(){
    try{
        $('#'+lb_id).hide();
        showAllSelect();
        showAllAds();
        if (document.getElementById('popupTitle'))
          document.getElementById('popupTitle').innerHTML = '';
        getLbFrame().src = '/profile/builder/defaultLoader.jsp';
        if (document.getElementById('popup_container')){
          $('popup_container').css("width", 675);
          $('popup_container').show();
        } else {
          $('#'+lb_popup_container).hide();
          $('#'+lb_photoholder).hide();
        }
    } catch(e){}
    lb_style = '1';
  }

  function getLbFrame(){
    if ( typeof lbFrame == 'undefined'){
        var main = document.getElementById(lb_mainframe);
        lbFrame = main.contentWindow.document.getElementById('lbFrame');
    }

    return lbFrame;
  }

  function setLBStyle(style) {
    if (style == '2') { // non-modal popup
      lb_style = '2';
      lb_id = 'lightbox2';
      lb_overlay = 'overlay2';
      lb_popup_frame = 'popup-frame2';
      lb_popup_body = 'popup-body2';
      lb_popup_container = 'popup-container2';
      lb_photoholder = 'photoHolder2';
      lb_mainframe = 'main2';
      lb_cancel_conf_menu = 'cancelConfMenu2';
      lb_cancel_msg = 'cancelMessage2';
    } else { // default
      lb_style = '1';
      lb_id = 'lightbox';
      lb_overlay = 'overlay';
      lb_popup_frame = 'popup-frame';
      lb_popup_body = 'popup-body';
      lb_popup_container = 'popup-container';
      lb_photoholder = 'photoHolder';
      lb_mainframe = 'main';
      lb_cancel_conf_menu = 'cancelConfMenu';
      lb_cancel_msg = 'cancelMessage';
    }
  }
  function setUpdated(u){updated = u;}
  function setStat(s){stat = s;}

/******************************** END NEW GENERIC BUILDER FUNCTIONS *******************************************/

function launchAskMe(iframeUrl, params){
    launchPopup('Ask Me',iframeUrl,params,380,'', 'false');
}

function launchEvent(iframeUrl,params,height,width,refresh,refreshUrl){
    if ( typeof params == 'undefined')
        params = '';
    launchPopup('Events',iframeUrl,params,480,753,'true');
}

function launchPhoto(iframeUrl,params, refreshUrl){
  top.resPop = false;
  launchPopup('Photos', iframeUrl, params, 400, 625, 'confirm');
  try { if(top.needsIGAffiliation && (top.needsIGAffiliation==true)) { top.autoIGAffiliate(); } } catch(ex) {}
}

function showStreamlinedPopup(iframeUrl, params, refreshUrl, posLeft, posTop, width, height, hideAds) {
  lb_style = '2';
  if (params.length > 3) {
    params+='&popupStyle=2';
  } else { 
    params = 'popupStyle=2';
  }

  if (typeof width == 'undefined') width = 350;
  if (typeof height == 'undefined') height = 165;
  if (typeof posTop != 'undefined' && posTop != null) { lb_popup_top = posTop; } else { lb_popup_top = 340; }
  if (typeof posLeft != 'undefined' && posLeft != null) { lb_popup_left = posLeft; } else { lb_popup_left = 0; }
  if (typeof hideAds != 'undefined' && hideAds != null) { lb_hide_ads = hideAds; } else { lb_hide_ads = false; }
  launchPopup('', iframeUrl, params, height, width, 'confirm');
  try { if(top.needsIGAffiliation && (top.needsIGAffiliation==true)) { top.autoIGAffiliate(); } } catch(ex) {}
}


function launchSinglePhoto(iframeUrl,params, refreshUrl){
  lb_style = '2';
  if (params.length > 3) {
    params+='&popupStyle=2';
  } else {
    params = 'popupStyle=2';
  }
  launchPopup('Photos', iframeUrl, params, 155, 336, 'confirm');
}

function launchNowPhotoPromo(dsource, posx, posy, width, height, hideAds) {
	if (typeof dsource == 'undefined') {
	  dsource = '';
	}
	showStreamlinedPopup('/photos/photo/uploader','promo=3&photoType=2&dsource=' + dsource, true, posx, posy, width, height, hideAds);
}

function launchThenPhotoPromo(dsource, posx, posy, width, height, hideAds) {
	if (typeof dsource == 'undefined') {
	  dsource = '';
	}
	showStreamlinedPopup('/photos/photo/uploader','promo=3&photoType=3&dsource=' + dsource, true, posx, posy, width, height, hideAds);
}

function launchThenPhotoPromo(dsource, posx, posy, width, height, hideAds) {
  if (typeof dsource == 'undefined') {
    dsource = '';
  }
  showStreamlinedPopup('/photos/photo/uploader','promo=3&photoType=3&dsource=' + dsource, true, posx, posy, width, height, hideAds);
}

function showHelpScreenshot(image, width, height) {
	showStreamlinedPopup('/graphics/helpcenter/' + image, '', false, null, null, width, height)
}

function editMsgBrdSubscription(){
    var uri = top.location.href;
    if ( uri.indexOf('https') > -1)
        uri = 'http' + uri.substring(uri.indexOf('://'), uri.indexOf('.com') + 4);
    else
        uri = uri.substring(0, uri.indexOf('.com') + 4);

    if ( uri.indexOf('secure') > -1 )
        uri = uri.substring(0, uri.indexOf('secure')) + 'www' + uri.substring(uri.indexOf('secure') + 6, uri.length);
    launchPopup('messageboards', uri + '/messageboards/ForumController','&action=ListSubscriptions&comingFrom=popup&hideNewStyle=false','450','630','true');
}
  /*
function datingOptIn(){
  launchSettingsPopup('dating', '/dating/settings/optInLoad.html', '', '450', '555', 'true' 'document.getElementById(\'panelFrame\').contentWindow.clickRemindMeLater()');
}
*/
function datingWhy(){
   launchSettingsPopup('dating', '/dating/settings/optInLoad.html', '', '450', '555', 'document.getElementById(\'panelFrame\').contentWindow.clickRemindMeLater()');
}

function datingWinkAdd(receiverId, successUrl, isGold){
    var escapedSuccessUrl = escape(successUrl);
    launchPopup('dating','/dating/possibilities/winks/add.html','&receiverId=' + receiverId + "&successUrl=" + escapedSuccessUrl + "&isGold=" + isGold,'350','600','false');
}

function datingWinkDelete(winkId, isGold){
  launchPopup('dating','/dating/possibilities/winks/delete.html','&winkId=' + winkId + "&isGold=" + isGold,'350','600','false');
}

function datingRegistrationWhy(){
    launchPopup('dating','/dating/info/why_dating.jsp','','350','740','false');
}

function datingRegistrationAgeError(){
    launchPopup('dating','/dating/info/age_error.jsp','','400','740','false');
}

function datingRegistrationConduct(){
    launchPopup('dating','/dating/info/conduct.jsp','','400','740','false');
}

function datingRegistrationPrivacy(){
    launchPopup('dating','/dating/info/privacy.jsp','','400','740','false');
}

function datingRegistrationTOS(){
    launchPopup('dating','/dating/info/tos.jsp','','400','740','false');
}

function inviteFriends(dsource,type){
        var reloadPref = 'conditional';
  var dsrc = '&dsource=' + dsource;
  if (typeof dsource == "undefined"){dsrc = '';}
        if ( dsrc.indexOf('ruhp') > -1 ){
            reloadPref = 'true';
        }
  if (typeof type == "undefined"){ type = 'invite a friend'}
  type = 'Invite&nbsp;Friends';
  builderType = type;
  iparams="&type=" + type + dsrc;
  launchPopup(type,'/profile/user/friends/invite/friends',iparams,500,625,reloadPref);
}
function eventInviteFriends(eventId,dsource){
  var dsrc = '&dsource=' + dsource;
  if (typeof dsource == "undefined"){dsrc = '';}
  if (typeof type == "undefined"){ type = ''}
  builderType = type;
  TB_show(this.innerHTML, '/profile/builder/frames/eventInviteFriends.jsp?eventId=' + eventId + '&height=420&amp;width=733' + dsrc );
}

function profileBuilder(action,type,dsource){
  var dsrc = '&dsource=' + dsource;
  if (dsource == undefined){dsrc = '';}

  var icon   = "";
  var panelUrl = "";
  if (action == "oz"){
    icon = "photos";
    panelUrl = "/cmo/user/builder/photo/photo.jsp";
    iparams="&photoform=addphoto&photoType=oz&action=" + action + "&type=" + type + dsrc + "&ms=" + new Date().getTime();
  }
  if (action == "photo"){
    icon = "photos";
    panelUrl = "/cmo/user/builder/photo/photo.jsp?photoform=addphoto&photoType="+ photoType + "&photoId="+photoId+"&type=" + type;
    iparams="&photoform=addphoto&photoType="+ photoType + "&photoId="+ photoId +"&action=" + action + "&type=" + type + dsrc + "&ms=" + new Date().getTime();
  }
  if (action == "bio"){
    icon = "announcements";
    panelUrl = "/cmo/user/builder/bio/bio.jsp";
    iparams="&action=" + action + "&type=" + type + dsrc + "&ms=" + new Date().getTime();
  }
  if (action == "myphotos"){
    icon = "photos";
    panelUrl = "/cmo/user/builder/photo/photo.jsp?photoform=addphoto&photoType=myphotos&type=" + type+"&seq=" + seq ;
    iparams="&action=" + action + "&type=" + type + dsrc + "&ms=" + new Date().getTime();
  }
  if (action == "editphotos"){
    icon = "photos";
    panelUrl = "/cmo/user/builder/photo/photo.jsp";
    iparams="&photoform=editphoto&photoType=editphotos&photoId="+ photoId +"&viewphoto=" + viewphoto +"&action=" + action + "&type=" + type + dsrc + "&ms=" + new Date().getTime();
  }
  if (action == "announcement"){
    icon = "announcements";
    panelUrl = "/cmo/user/builder/photo/photo.jsp";
    iparams="&photoform=addphoto&photoType=announcement&photoId="+ photoId +"&action=" + action + "&type=" + type + dsrc + "&ms=" + new Date().getTime();
  }
  if (action == "mystories"){
    icon = "stories";
    panelUrl = "/cmo/user/builder/photo/photo.jsp";
    iparams="&photoform=addphoto&photoType=mystories&action=" + action + "&type=" + type + dsrc + "&ms=" + new Date().getTime(); // + "&seq=" + seq ??
  }

  launchPopup(icon,panelUrl,iparams,440,733, 'false');
  if (type==undefined){ type = ''}
  builderType = type;
}

function addPhotos(sequence){
  var dsrc = '&seq=' + sequence;
  if (sequence == undefined){dsrc = '';}
  iparams="&action=myphotos&type=&ms=" + new Date().getTime() + dsrc;
  purl="/profile/builder/frames/profilebuilder.jsp";
  launchPopup("photos",purl,iparams,425,733,'conditional');
  builderType = "";
}

var announcementTitle ="" ;
var announcementText = "" ;
var announcementTopic = "";
var announcementTopicId = "";
var announcementPhotoUrl = "";

function addAnnouncementPhotos(photoId,title,text,occasionType){
  var dsrc = '' ;
  if (photoId != 0) {
    dsrc = "&photoId=" + photoId;
  }

  if (title !=""){
    announcementTitle = title;
  }
  if (text !=""){
    announcementText = text;
  }
  if(occasionType !=""){
    announcementTopic = occasionType;
  }

  iparams="&action=announcement&type=&ms=" + new Date().getTime() + dsrc;
  purl="/profile/builder/frames/profilebuilder.jsp";
  launchPopup("announcements",purl,iparams,425,733,'conditional');
  builderType = "announcement";
}

function editPhotos(photoId,viewPhoto){
  var dsrc = '&photoId=' + photoId + "&viewphoto="+viewPhoto;
  if (photoId == undefined){dsrc = '';}
  launchPopup('photos', '/profile/builder/frames/profilebuilder.jsp' , '&action=editphotos&type=&fixedSize=false&ms=' + new Date().getTime() + dsrc, '425', '753', 'conditional' );
  builderType = "";
}

function showPhotoHelpPanel(photoType, photoId){
    if ( typeof photoType == 'undefined' || photoType == '')
        photoType = 'help';
    var width = '635';
    if ( navigator.userAgent.indexOf("MSIE") > -1 ) width = '645';
    launchPopup('Learn More','/profile/builder/frames/profilebuilder.jsp','&photoId=' + photoId + '&action=learnMore&photoform=help&photoType=' + photoType + '&singleton=true&fixedSize=false','400',width,'false');
}

function addNowThenPhotos(photoType) {
  purl="/cmo/user/builder/photo/photo.jsp";
  launchPopup("photos", purl, "photoType=" + (isNaN(photoType)?((photoType=="now")?"2":"3"):photoType) , 425, 625, "conditional");
  builderType = "";
}


var msstate = "";
var msphone = "";
var mspostal = "";
var mstopic = "";
var msstory = "";
var mscaption1 = "";
var msphoto1Id = "";
var msphoto1Url = "";
var msphoto1Width = "";
var msphoto1Height = "";
var msthumbnail1Url = "";
var msthumbnail1Width = "";
var msthumbnail1Height = "";
var mscaption2 = "";
var msphoto2Id = "";
var msphoto2Url = "";
var msphoto2Width = "";
var msphoto2Height = "";
var msthumbnail2Url = "";
var msthumbnail2Width = "";
var msthumbnail2Height = "";
var mscaption3 = "";
var msphoto3Id = "";
var msphoto3Url = "";
var msphoto3Width = "";
var msphoto3Height = "";
var msthumbnail3Url = "";
var msthumbnail3Width = "";
var msthumbnail3Height = "";
var msagree = "";


function addMyStoriesPhotos(sequence,state,phone,postal,topic,story,
        caption1,photo1Id,photo1Url,photo1Width,photo1Height,thumbnail1Url,thumbnail1Width,thumbnail1Height,
        caption2,photo2Id,photo2Url,photo2Width,photo2Height,thumbnail2Url,thumbnail2Width,thumbnail2Height,
        caption3,photo3Id,photo3Url,photo3Width,photo3Height,thumbnail3Url,thumbnail3Width,thumbnail3Height,agree){


 var dsrc = '&seq=' + sequence;
 if (sequence == undefined){dsrc = '';}


 TB_show(this.innerhtml, '/profile/builder/frames/profilebuilder.jsp?height=440&amp;width=733&action=mystories&type=&ms=' + new Date().getTime() + dsrc );

 builderType = "";
 if (state !=""){
   msstate = state;
 }
 if (phone !=""){
   msphone = phone;
 }

 if (postal !=""){
   mspostal = postal;
 }

 if (topic !=""){
    mstopic = topic;
 }
 if (story !=""){
   msstory = story;
 }
 if (caption1 !=""){
   mscaption1 = caption1;
 }
 if (photo1Id !=""){
   msphoto1Id = photo1Id;
 }
 if (photo1Url !=""){
   msphoto1Url = photo1Url;
 }
 if (photo1Width !=""){
   msphoto1Width = photo1Width;
 }
 if (photo1Height !=""){
   msphoto1Height = photo1Height;
 }
  if (thumbnail1Url !=""){
   msthumbnail1Url = thumbnail1Url;
 }
 if (thumbnail1Width !=""){
   msthumbnail1Width = thumbnail1Width;
 }
 if (thumbnail1Height !=""){
   msthumbnail1Height = thumbnail1Height;
 }
 if (caption2 !=""){
   mscaption2 = caption2;
 }
 if (photo2Id !=""){
   msphoto2Id = photo2Id;
 }
 if (photo2Url !=""){
   msphoto2Url = photo2Url;
 }
 if (photo2Width !=""){
   msphoto2Width = photo2Width;
 }
 if (photo2Height !=""){
   msphoto2Height = photo2Height;
 }
  if (thumbnail2Url !=""){
   msthumbnail2Url = thumbnail2Url;
 }
 if (thumbnail2Width !=""){
   msthumbnail2Width = thumbnail2Width;
 }
 if (thumbnail2Height !=""){
   msthumbnail2Height = thumbnail2Height;
 }
 if (caption3 !=""){
   mscaption3 = caption3;
 }
 if (photo3Id !=""){
   msphoto3Id = photo3Id;
 }
 if (photo3Url !=""){
   msphoto3Url = photo3Url;
 }
 if (photo3Width !=""){
   msphoto3Width = photo3Width;
 }
 if (photo3Height !=""){
   msphoto3Height = photo3Height;
 }
  if (thumbnail3Url !=""){
   msthumbnail3Url = thumbnail3Url;
 }
 if (thumbnail3Width !=""){
   msthumbnail3Width = thumbnail3Width;
 }
 if (thumbnail3Height !=""){
   msthumbnail3Height = thumbnail3Height;
 }
 if (agree !=""){
   msagree = agree;
 }
}

function addCommunities(action,type,dsource){
  var dsrc = '&dsource=' + dsource;
  if (dsource == undefined){dsrc = '';}
  launchPopup('add communities', '/profile/builder/frames/addcommunities.jsp?height=440&amp;width=733&action=' + action + '&type=' + type + "&ms=" + new Date().getTime() + dsrc, 400, 1 , 'true');
  if (type==undefined){ type = ''}
  builderType = type;
}

function ugcReg(baseUrl){
  launchPopup('Profile Builder','/photos/photo/uploader','photoType=2&ac=d&textHeader=true&type=PBnowThen', 550, 615, 'false');
  builderType = 'ugcReg';
  showMyPoints = true;
}

function myVisitorASettings(visitedRegId, fName, lName, dsource){
  var dsrc = '&dsource=' + dsource;
  if (dsource == undefined){dsrc = '';}
  iparams='&visitedRegId='+visitedRegId+'&fName='+fName+'&lName='+lName+dsrc;
  launchPopup('guestbook','/profile/builder/frames/myvisitorBsettings.jsp',iparams,425,733,'false');
}

function myVisitorASettingsPopup(dsource){
  var dsrc = dsource;
  if (dsource == undefined){dsrc = '';}
  myVisitorASettings('','','',dsrc);
}

function myVisitorBSettings(visitedRegId, fName, lName){
    launchPopup('guestbook','/profile/myvisitors/settings/index.html' , 'action=lookupSettingsPopupB&vID=' + visitedRegId + '&fN=' + fName + '&lN=' + lName,400,733, 'conditional');
    addAnalytics('Guest Book Change Setting');
    builderType = '';
}

function viewDatingBasic(regId){
  var ran = Math.random();
  launchPopup('Dating', '/dating/profile/basic.html?height=720&width=690&registrationId='+regId+'&ran='+ran, 425, 1, 'false');
  TB_ajaxContent.style.height = "100%";
}

function individualMap(regId) {
  individualMap(regId, null, null);
}

function individualMap(regId, source) {
  individualMap(regId, source, null);
}

function individualMap(regId, source, communityId) {
  individualMap(regId, source, communityId,null);
}
function individualMap(regId, source, communityId,entityCommunitySource) {
  individualMap(regId, source, communityId,null,null);
}

function individualMap(regId, source, communityId,entityCommunitySource,entityCommunityId) {
  var height = window.innerHeight ? window.innerHeight : document.body.clientHeight;
  iparams='&registrationId=' + regId ;

  if (source) {iparams = iparams + '&source=' + source;}
  if (communityId) {iparams = iparams + '&communityId=' + communityId;}
  if (entityCommunitySource) {iparams = iparams + '&entityCommunitySource=' + entityCommunitySource;}
  if (entityCommunityId) {iparams = iparams + '&entityCommunityId=' + entityCommunityId;}

  if(height < 430)
    height = 410;
  else if(height < 530)
    height = 460;
  else
    height = 560;

  launchPopup('Classmates maps','/community/maps/indi_container.jsp',iparams,450,733, 'false');
}


function mapsOptIn() {
  iparams="&welcome=";
  launchPopup('Classmates maps','/community/maps/promopop.jsp',iparams,400,740,'conditional');
}

function mapsAskMe() {
  iparams="&welcome=true";
  launchPopup('Classmates maps','/community/maps/settings/optZipView.html',iparams,400,740,'conditional');
}

function mapsMsgcenter(markAlertUrl) {
  // send request to server to mark alert as "read"
  asyncRequest(markAlertUrl);
  // show map popover
  iparams="&welcome=true";
  launchPopup('Classmates maps','/community/maps/promopop.jsp',iparams,400,780,'conditional');
}    
    
// Makes asynchronous HTTP request to the server in order to perform
// a task when reponse from server is not actually renerred by browser
// and trown away.
function asyncRequest(url) {

  // A XMLHttpRequest object is created and configured
  if (typeof XMLHttpRequest != "undefined") {
    asyncHttpRequest = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    asyncHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }

  // Send request
  asyncHttpRequest.open("GET", url, true);
  asyncHttpRequest.onreadystatechange = noopCallback;
  asyncHttpRequest.send(null);
}

// No-op callback - just ignores response from server
function noopCallback() {
  /*
    /dev/null
  */
}


function openMemberConductGMaps(){
  getLbFrame().src = "/profile/builder/member_conduct_gmaps.jsp?rt=Return to Profile Builder";
}

function openMemberConduct(returntitle){
  var rt = '';
  if (returntitle == undefined){rt = '?rt=Return to Profile Builder';}else{rt='?&rt=' + returntitle}
  getLbFrame().src = "/profile/builder/member_conduct.jsp" + rt;
}

function hideAds(){
  document.getElementById('pushDown').style.display = 'block';
}

var pId = "";
var pUrl = "";
var pWidth = "";
var pHeight = "";
var tUrl = "";
var tWidth = "";
var tHeight = "";
var pSeq = "" ;

function initialize(id,url,width,height,thumburl,thumbwidth,thumbheight,seq) {

 pId = id ;
 pUrl = url;
 pWidth = width;
 pHeight = height;
 tUrl = thumburl;
 tWidth = thumbwidth;
 tHeight = thumbheight;
 pSeq = seq;

}

function closeBuilder(){

  var builderType = parent.getBuilderType();
  if (builderType=="silver"){
    parent.window.location = "/rewardsCenter/rewards/completeTasks";
  }else{
    TB_remove();
    var loc = top.location.toString();
    if (loc.indexOf("autoPopup") > 0 ){
      var refreshUrl, urlquery, params, isAction, count, prepend;
      count = 0;
      prepend = '?';
      var url = top.location.href;
      if ( url.substring(url.length -1, url.length) == '#')
      url = url.substring(0, url.length -1);
      urlquery= url.split('?');
      refreshUrl = urlquery[0] ;
      if(urlquery[1]){
        params=urlquery[1].split("&");
        for (x in params){
          isAction = params[x].indexOf("autoPopup");
          if (isAction){
            if(count!=0){
              prepend = '&';
            }
            refreshUrl += prepend + params[x];
            count++;
          }
        }
      }
      top.location.replace(refreshUrl);
    }
    else if (loc.indexOf("_DARGS") > 0){
     loc = loc.substring(0,loc.indexOf("_DARGS"));
     top.location.replace(loc);
    }
    else if (loc.indexOf("announcement") > 0){
      if (loc.indexOf("url") > 0)
             loc = loc.substring(0,loc.indexOf("url")-1);

      if (loc.indexOf("?") > 0 )
        loc = loc + "&";
      else
        loc = loc + "?";

      loc = loc +"url="+pUrl+"&photoId="+pId+"&topic="+announcementTopic+"&width="+pWidth+"&height="+pHeight+"&thumburl="+tUrl+"&thumbwidth="+tWidth+"&thumbheight="+tHeight+"&title="+announcementTitle+"&text="+announcementText;
      top.location.replace(loc);
    }
    else if (loc.indexOf("submitstory") > 0){
      if (loc.indexOf("state") > 0)
             loc = loc.substring(0,loc.indexOf("state")-1);

      if (loc.indexOf("?") > 0 )
        loc = loc + "&";
      else
        loc = loc + "?";

      loc += "state="+msstate +"&postal="+mspostal+"&phone=" +msphone+"&topic=" + mstopic+"&story="+msstory;

      if (pSeq == "1"){
          loc += "&caption1="+mscaption1+"&photo1Id="+pId+"&photo1Url="+pUrl+"&photo1Width="+pWidth+"&photo1Height="+pHeight+"&thumbnail1Url="+tUrl+"&thumbnail1Width="+tWidth+"&thumbnail1Height="+tHeight+"&caption2="+mscaption2+"&photo2Id="+msphoto2Id+"&photo2Url="+msphoto2Url+"&photo2Width="+msphoto2Width+"&photo2Height="+msphoto2Height+"&thumbnail2Url="+msthumbnail2Url+"&thumbnail2Width="+msthumbnail2Width+"&thumbnail2Height="+msthumbnail2Height+"&caption3="+mscaption3+"&photo3Id="+msphoto3Id+"&photo3Url="+msphoto3Url+"&photo3Width="+msphoto3Width+"&photo3Height="+msphoto3Height+"&thumbnail3Url="+msthumbnail3Url+"&thumbnail3Width="+msthumbnail3Width+"&thumbnail3Height="+msthumbnail3Height+"&agree="+ msagree + "&sequence="+pSeq;
          }
      if (pSeq == "2"){
          loc += "&caption1="+mscaption1+"&photo1Id="+msphoto1Id+"&photo1Url="+msphoto1Url+"&photo1Width="+msphoto1Width+"&photo1Height="+msphoto1Height+"&thumbnail1Url="+msthumbnail1Url+"&thumbnail1Width="+msthumbnail1Width+"&thumbnail1Height="+msthumbnail1Height+"&caption2="+mscaption2+"&photo2Id="+pId+"&photo2Url="+pUrl+"&photo2Width="+pWidth+"&photo2Height="+pHeight+"&thumbnail2Url="+tUrl+"&thumbnail2Width="+tWidth+"&thumbnail2Height="+tHeight+"&caption3="+mscaption3+"&photo3Id="+msphoto3Id+"&photo3Url="+msphoto3Url+"&photo3Width="+msphoto3Width+"&photo3Height="+msphoto3Height+"&thumbnail3Url="+msthumbnail3Url+"&thumbnail3Width="+msthumbnail3Width+"&thumbnail3Height="+msthumbnail3Height+"&agree="+ msagree  + "&sequence="+pSeq;
          }
      if (pSeq == "3"){
          loc += "&caption1="+mscaption1+"&photo1Id="+msphoto1Id+"&photo1Url="+msphoto1Url+"&photo1Width="+msphoto1Width+"&photo1Height="+msphoto1Height+"&thumbnail1Url="+msthumbnail1Url+"&thumbnail1Width="+msthumbnail1Width+"&thumbnail1Height="+msthumbnail1Height+"&caption2="+mscaption2+"&photo2Id="+msphoto2Id+"&photo2Url="+msphoto2Url+"&photo2Width="+msphoto2Width+"&photo2Height="+msphoto2Height+"&thumbnail2Url="+msthumbnail2Url+"&thumbnail2Width="+msthumbnail2Width+"&thumbnail2Height="+msthumbnail2Height+"&caption3="+mscaption3+"&photo3Id="+pId+"&photo3Url="+pUrl+"&photo3Width="+pWidth+"&photo3Height="+pHeight+"&thumbnail3Url="+tUrl+"&thumbnail3Width="+tWidth+"&thumbnail3Height="+tHeight+"&agree="+ msagree  + "&sequence="+pSeq;
      }

      top.location.replace(loc);

    }
    /* Only call the nextImg() function if photoDeleted is true and view.jsp is in the url.
       Otherwise the edit photo window must have been launched from the my profile page instead of
       the view photo page. */
    else if ( (typeof photoDeleted != "undefined" && photoDeleted == true) && loc.indexOf("view.jsp") > 0 ){
      try {
        nextImg();
      } catch (e){}
    }
    else
     top.location.reload(true);

  }
}


function closeMyVisitor(appendValue, refreshParent){
  if (refreshParent){
    parent.window.location.reload();
  } else {
    TB_remove();
  }
  setOmniture('Guest Book ' + appendValue);
}

function silverOffer(action,dsource){
  var dsrc = '';
  if (dsource == undefined){dsrc = '';}
  switch(action){
   case 'invite':
     inviteFriends(dsrc,'silver');
   break
   case 'bio':
     profileBuilder('bio','silver',dsrc);
   break
   case 'oz':
     profileBuilder('oz','silver',dsrc);
   break
   case 'all':
     addCommunities('all','silver',dsrc);
   break
   case 'school':
     addCommunities('school','silver',dsrc);
   break
   case 'college':
     addCommunities('college','silver',dsrc);
   break
   case 'workplace':
     addCommunities('workplace','silver',dsrc);
   break
   case 'military':
     addCommunities('military','silver',dsrc);
   break
  }
}

function showBuilder(action,dsource){
  var dsrc = '';
  if (dsource == undefined){
    dsrc = '';
  }else{
    dsrc = dsource;
  }
  switch(action){
   case 'wizard':
     profileWizard(dsrc,'');
   break
   case 'invite':
     inviteFriends(dsrc,'');
   break
   case 'bio':
     profileBuilder('bio','',dsrc);
   break
   case 'now':
     profileBuilder('photo','',dsrc);
   break
   case 'oz':
     profileBuilder('oz','',dsrc);
   break
   case 'all':
     addCommunities('all','',dsrc);
   break
   case 'school':
     addCommunities('school','',dsrc);
   break
   case 'college':
     addCommunities('college','',dsrc);
   break
   case 'workplace':
     addCommunities('workplace','',dsrc);
   break
   case 'military':
     addCommunities('military','',dsrc);
   break
  }
}
/* DATING PHOTO FUNCTION */
function datingPhoto(seq,action,photoId){
  if(action=="add") {
    launchPhoto("/photos/photo/uploader", "photoType=4&sequence=" + seq);
  } else {
      if(action=="edit") {
        launchPopup("edit photos", "/photos/photo/edit-photo", "photoId=" + photoId, 425, 625, "conditional");
      } else {
    try{
      document.getElementById('TB_window').innerHTML='';
    } catch(err){}
    var params = "&seq=" + seq;
    if (photoId){ params = params + "&photoId=" + photoId;  }
  if (action) { params = params + "&action=" + action;    }
    TB_show(this.innerHTML, "/dating/builder/frames/addphoto.jsp?height=440&amp;width=733" + params);
    document.getElementById('TB_overlay').style.visibility='visible';
  }
 }
}

function datingPhotoHelp(photoId) {
  TB_show(this.innerHTML, "/dating/builder/photohelp.jsp?height=340&amp;width=733&photoId=" + photoId);
  document.getElementById('TB_overlay').style.visibility='hidden';
}

/* PROFILE BUILDER FUNCTIONS */
var photoComplete = false;
var avatarphotoComplete = false;
var storyComplete = false;
var bioComplete = false;
var inviteComplete = false;
var mypointsComplete = false;
var storyOnlyPromo = false;

function handleResponse(step) {
  var nextStep = "";

  if(step=="photo"){
    photoComplete = true;
    nextStep = "avatarphoto";
  }
  
  if(step=="photouploadsuccess"){
    photoComplete = true;
    avatarphotoComplete = true;    
    nextStep = "story";
  }
  
  if(step=="avatarphoto"){
  	avatarphotoComplete = true;
  	nextStep = "story";
  }

  if(step=="photoback"){
    photoComplete = false;    
    addNowPhoto();
  }
  
  if(step=="story"){
    storyComplete = true;
    nextStep = "invite";
  }

  if(step=="invite"){
    inviteComplete = true;
    if (showMyPoints) {
      nextStep = "mypoints";
    }
    else
      nextStep = "close";

    toggleDiv('privacyPolicy', 0);
  }

  if(step=="mypoints"){
    mypointsComplete = true;
    nextStep = "photo";
  }

  if((nextStep=="mypoints") && (!mypointsComplete)){
    addMyPoints();
  }

  if((nextStep=="invite") && (!inviteComplete)){
    addInvite();
  }

  if((nextStep=="photo") && (!photoComplete)){
    addPhoto();
  }

  if((nextStep=="story") && (!storyComplete)){
    storyOnlyPromo = false;
    addStory();
  }
  
   if((nextStep=="avatarphoto") && (!avatarphotoComplete)){
    addAvatarphoto();
  }
  
  if (avatarphotoComplete && photoComplete && storyComplete && inviteComplete && (showMyPoints == false || mypointsComplete)){
    nextStep = "close";
    builderType = "";
    closeLBFrame();
  }
  
  if(nextStep=="close"){
    builderType = "";
    closeLBFrame();  
  }
}

function getBuilderType(){
  return builderType;
}

function skipStep(step) {
  if (typeof step != 'undefined'){
    switch(step){
     case 'photo':
      if (!photoComplete){
        setOmniture('Profile Builder Photo Skipped');
        handleResponse('photo');
      }
     break
     case 'avatarphoto':
      if (!avatarphotoComplete){
        setOmniture('Profile Builder Avatar Photo Skipped');
        handleResponse('avatarphoto');
      }
     break
    case 'story':
      if (!storyComplete){
        setOmniture('Profile Builder Story Skipped');
        handleResponse('story');
      }
     break
     case 'invite':
      if (!inviteComplete){
        setOmniture('Profile Builder Invite A Friend Skipped');
        handleResponse('invite');
        nextStep = "invite";
      }
     break
     case 'mypoints':
      if (!mypointsComplete){
        setOmniture('Profile Builder MyPoints Signup Skipped');
        handleResponse('mypoints');
      }
     break
     default:
      if (!photoComplete){
        setOmniture('Profile Builder Photo Skipped');
        handleResponse('photo');
      }else if (!avatarphotoComplete){
        setOmniture('Profile Builder Avatar Photo Skipped');
        handleResponse('avatarphoto');
      }else if (!storyComplete){
        setOmniture('Profile Builder Story Skipped');
        handleResponse('story');
      }else if (!inviteComplete){
        setOmniture('Profile Builder Invite A Friend Skipped');
        handleResponse('invite');
      }else if (showMyPoints && !mypointsComplete){
        setOmniture('Profile Builder MyPoints Signup Skipped');
        handleResponse('mypoints');
      }
     break
    }
  }else{
    if (!photoComplete){
      setOmniture('Profile Builder Photo Skipped');
      handleResponse('photo');
    }else if (!avatarphotoComplete){
        setOmniture('Profile Builder Avatar Photo Skipped');
        handleResponse('avatarphoto');
    }else if (!storyComplete){
        setOmniture('Profile Builder Story Skipped');
        handleResponse('story');
    }else if (!inviteComplete){
      setOmniture('Profile Builder Invite A Friend Skipped');
      handleResponse('invite');
    }else if (showMyPoints && !mypointsComplete){
      setOmniture('Profile Builder MyPoints Signup Skipped');
      handleResponse('mypoints');
    }
  }
}

function addNowPhoto(){
	getLbFrame().src = "/photos/photo/uploader?photoType=2&ac=d&textHeader=true&type=PBnowThen";
}

function addStory(){
  getLbFrame().src = "/profile/user/my/story/popup";
}

function addPhoto(){
  getLbFrame().src = "/cmo/user/builder/photo/photo.jsp?photoform=addphoto&photoType=now?type=silver";
}

function addAvatarphoto(){
  getLbFrame().src = "/photos/photo/avatarPhoto/list?type=PBnowThen&photoTypeId=11";
}

function addInvite(){
  getLbFrame().src = "/profile/inviteWrapper.jsp";
}

function addMyPoints(){
  getLbFrame().src = "/profile/rewards/signup?type=silver";
  addAnalytics('Profile Builder MyPoints Signup');
}

function showPromoEndBanner(){
  getLbFrame().src = "/profile/user/my/story/promo?screen=2";
}

function toggleDiv(szDivID, iState) { // 1 visible, 0 hidden
  var obj = null;
  if(document.getElementById(szDivID)) {
    obj = document.getElementById(szDivID).style;
  }
  else if(document.all) {
    if(document.all[szDivID]) {
      obj = document.all[szDivID].style;
    }
  }
  else if(document.layers) {
    obj = document.layers[szDivID];
  }

  //Fail if object has no properties
  if(obj == null) {
    return false;
  }

  obj.visibility = document.layers ? (iState ? "show" : "hide") : (iState ? "visible" : "hidden");
  obj.display = iState ? "block" : "none";
}

function iconSwitchImg(img) {
  src = document.images[img].src;

  if(src.indexOf('_comp.') == -1){
    if(src.indexOf('_off.') == -1){
      document.images[img].src = src.replace('_on.', '_off.');
      document.images[img].src = src.replace('_sel.', '_off.');
    } else {
      document.images[img].src = src.replace('_off.', '_off.');
    }
  }
}

function swapIconImg(img,type) {
  src = img.src;
  switch(type){
  case 'hi':
    if(src.indexOf('_hi.') != -1)
      img.src = src.replace('_hi.', '_on.');
    else if(src.indexOf('_on.') != -1)
      img.src = src.replace('_on.', '_hi.');
  break
  default:
    if(src.indexOf('_sel.') == -1){
      if(src.indexOf('_off.') != -1){
        img.src = src.replace('_off.', '_on.');
      }else if(src.indexOf('_on.') != -1){
        img.src = src.replace('_on.', '_off.');
      }
    }
  break
  }
}

function preloadImg(img,type) {
  src = img.src;
  document.onImg = new Image();
  switch(type){
  case 'hi':
    document.onImg.src = src.replace('_hi.', '_on.');
  break
  default:
    document.onImg.src = src.replace('_off.', '_on.');
  }
}

function selectCommunity(community){
  if ( typeof community != 'undefined' && community != null && community != ''){
    iconCommunityRotateImg(community + 'Icon');
    if (document.images[community + 'Icon']){
      document.images[community + 'Icon'].src = '/graphics/pbuilder/task_' + community + '_sel.gif';
    } else {
      document.images['taskIcon'].src = '/graphics/pbuilder/task_' + community + '_sel.gif';
    }
    getLbFrame().src ="/registration/builder/add_communities.jsp?action=addCommunity&type=" + community;
  }
}

function iconCommunityRotateImg(img) {
  if(document.images[img]){
    var theCommunities = new Array()
    theCommunities[0] = 'schoolIcon'
    theCommunities[1] = 'collegeIcon'
    theCommunities[2] = 'workplaceIcon'
    theCommunities[3] = 'militaryIcon'
    var p = theCommunities.length;
    src = document.images[img].src;
    for (i = 0; i < p; i++){
      if(document.images[theCommunities[i]].src.indexOf('_off.') == -1){
        document.images[theCommunities[i]].src = document.images[theCommunities[i]].src.replace('_on.', '_off.');
        document.images[theCommunities[i]].src = document.images[theCommunities[i]].src.replace('_sel.', '_off.');
      }
    }
  } else {
    src = document.images['taskIcon'].src;
    if(src.indexOf('_off.') == -1){
        src = src.replace('_on.', '_off.');
        src = src.replace('_sel.', '_off.');
      }
  }
}

function setOmniture(pageName) {
  var bType = getBuilderType();
  $('#omnitureFrame').attr('src','/profile/builder/omniture.jsp?pagename=' + bType + ' ' + pageName);
  return false;
}

function hideElement(comp){
    document.getElementById(comp).style.display = "none";
}

function showElement(comp){
    document.getElementById(comp).style.display = "block";
}

function learnMore(returnUrl, fromPopover){
    var e = top.document.getElementById(lb_id);
    if ( e.style.display == 'none' || e.style.display == ''){
        launchPopup('Learn More','/profile/learn_more.html','returnUrl=' + returnUrl,'450','600','false');
    }
    else if ( fromPopover ) {
        top.sliderOpen = true;
        $("#slideDown").css('margin', '0px 64px 0px -6px');
        if(parseInt($("#main")[0].style.height)<400) {
          top.origMainHeight = parseInt($("#main")[0].style.height);
          $("#main").css({height: "400px"});
        } else {
          top.origMainHeight = null;
        }
        document.getElementById('sliderFrame').scrolling = 'yes';
        $("#slideDown").slideDown('slow', function(){
            var href = top.location.href;
            href = href.substring(0, href.indexOf('com') + 3);
            href += '/profile/learn_more.html?sliderMode=true&returnUrl=javascript:top.hideMemberConduct()';
            document.getElementById('sliderFrame').src = href;
        });
    }
}

function fixHeight() {
  try {
    if(top.sliderOpen != true) {
      $("#main").css({height: $("#main")[0].contentWindow.document.getElementById('lbFrame').contentWindow.getPageDimensions()[1]});
    }
    if(top.origMainHeight && top.sliderOpen==true) {
      top.origMainHeight = $("#main")[0].contentWindow.document.getElementById('lbFrame').contentWindow.getPageDimensions()[1];
    }
  } catch (ex) { }
}

function photoUploadPromo1(dsource, title, width, height) {
  if (typeof dsource == 'undefined') {
    dsource = '';
  }
  if (typeof title == 'undefined' || title == ''){
    title = 'photos';
  }
  if (typeof width == 'undefined') {
    width = 625;
  }
  if (typeof height == 'undefined') {
    height = 425;
  }
  launchPopup(title, '/photos/photo/promo', '&promo=1&dsource=' + dsource, height, width, 'conditional');
}

function photoUploadPromo2(dsource, title) {
  if (typeof dsource == 'undefined') {
    dsource = '';
  }
  if (typeof title == 'undefined' || title == ''){
    title = 'photos';
  }
  launchPopup(title, '/photos/photo/uploader', '&promo=2&photoType=2&dsource=' + dsource, 425, 625, 'conditional');
}

function storyPromo(dsource,title) {
  storyOnlyPromo = true;
  if (typeof dsource == 'undefined') {
    dsource = '';
  }
  if (typeof title == 'undefined' || title == ''){
    title = 'story';
  }
  launchPopup(title, '/profile/user/my/story/promo', '&screen=1&dsource=' + dsource, 425, 625, 'conditional');
}

function showPopupPromo(type,dsource,title) {
  if (type == 'story') {
    storyPromo(dsource,title);
  }
  else if (type == 'photo') {
    photoUploadPromo1(dsource,title);
  }
  var promoCookieValue = ReadCookie ('promo');
  if ((promoCookieValue != null) && (promoCookieValue.length > 0))
    WriteCookie('promo',promoCookieValue+','+type,0);
  else
    WriteCookie('promo',type,0);
}

function checkPopupPromoShown(promoType){
  var promoCookieValue = ReadCookie ('promo');
  
  if ((promoCookieValue != null) && (promoCookieValue.length > 0))
  { 
    if ((typeof promoType != 'undefined') && 
      (promoType.length > 0))
    {
      if (promoCookieValue.indexOf(promoType) >= 0)
      { return true;}
      else
      { return false;}
  }
  return true;
  }
  return false;
}

function showBigPic(profileUrl, bigPicUrl, picWidth, picHeight, pageName, isNowThen, currentType, otherPicUrl, otherPicWidth, otherPicHeight) {
    if(profileUrl.indexOf("profile") == -1){
      bigPicUrl=profileUrl;
      profileUrl="/profile";
    }
    setLBStyle(lb_style);
    jQuery.ajax({
       type: "GET",
       dataType: "html",
       url: profileUrl + '/builder/frames/photoViewer.jsp',
       success: function( html ){
          window.scrollTo(0,0);
          $("#"+lb_overlay).css("height", top.getPageHeightWithScroll());
          $('#'+lb_photoholder).html(html);
          $('#'+lb_popup_container).hide();
          $(".bigPic").attr("src", bigPicUrl);
          $(".bigPicTemp").attr("width", picWidth);
          $(".bigPicTemp").attr("height", picHeight);
          $(".bigPicTemp").attr("align", "center");

          if(isNowThen==true && otherPicUrl!=null) {
            $(".nowThenLinksBig").css({display: "block"});
            $(".dummyClose").css({display: "block"});
            if(currentType.toLowerCase()=="now") {
                    $(".nowBigE").hide();
                    $(".nowBigD").show();
                    $(".thenBigD").hide();
                    $(".thenBigE").show();
                    ntPicHash.nowUrl = bigPicUrl;
                    ntPicHash.thenUrl = otherPicUrl;
                    ntPicHash.nowWidth = picWidth;
                    ntPicHash.thenWidth = otherPicWidth;
                    ntPicHash.nowHeight = picHeight;
                    ntPicHash.thenHeight = otherPicHeight;
            } else if(currentType.toLowerCase()=="then") {
                    $(".nowBigD").hide();
                    $(".nowBigE").show();
                    $(".thenBigE").hide();
                    $(".thenBigD").show();
                    ntPicHash.thenUrl = bigPicUrl;
                    ntPicHash.nowUrl = otherPicUrl;
                    ntPicHash.thenWidth = picWidth;
                    ntPicHash.nowWidth = otherPicWidth;
                    ntPicHash.thenHeight = picHeight;
                    ntPicHash.nowHeight = otherPicHeight;
            }
          }
       },
       complete: function(){
          hideAllSelect();
          top.document.getElementById(lb_id).style.display = 'block';
          $('#'+lb_photoholder).show();
          if ( typeof pageName != 'undefined'){
              addAnalytics(pageName);
          }
       }
    });
}

function changeBigPic(picType) {
  
  if(picType=="now") {
    $(".nowBigE").hide();
    $(".nowBigD").show();
    $(".thenBigD").hide();
    $(".thenBigE").show();
    $(".bigPicTemp").attr("height", ntPicHash.nowHeight);
    $(".bigPicTemp").attr("align", "center");
    $(".bigPic").attr("src", ntPicHash.nowUrl);
  }
  if(picType=="then") {
    $(".nowBigD").hide();
    $(".nowBigE").show();
    $(".thenBigE").hide();
    $(".thenBigD").show();
    $(".bigPicTemp").attr("height", ntPicHash.thenHeight);
    $(".bigPicTemp").attr("align", "center");
    $(".bigPic").attr("src", ntPicHash.thenUrl);
  }
}

function linkAndAnimate(newHeight, iframeUrl, refresh, refreshUrl){
        if ( typeof refresh == 'undefined' || refresh   == null  || refresh    == '') {
            refreshPage    = 'true';
        }
        else {
            refreshPage = refresh;
        }
        if (typeof refresh == 'undefined' || refreshUrl == null || refreshUrl == '') {
            refreshAddress = '';
        }
        else {
            refreshAddress = refreshUrl;
        }

        getLbFrame().src = '/profile/builder/defaultLoader.jsp';
        $("#popup-body").attr("height", newHeight);
        $("#main").animate({'height': newHeight -23}, 'slow', '', function(){
            getLbFrame().src = iframeUrl;
        });
    }

/*
   Example Use:
     var newObject = cookieReader("dontStopPop");
     var firstName = newObject.firstNameKeyFromCookie;
   Parameter Breakdown:
     REQUIRED:
       name: The name of the cookie to read.
   This is a method to read a cookies and return a js object with
   all the name/value pairs added to it as properties.

*/

function cookieReader(name){
  //Remember the name of the cookie/
  this.$name = name;
  
  //Grab the list of cookies
  var allCookies = document.cookie;
  
  //If there are no cookies return
  if (allCookies == "") return;
  
  //Split the list of cookies into an array and initilize the
  //cookie variable
  var cookies = allCookies.split(';');
  var cookie = null;
  
  //Interate over the  list of cookies looking for the dontStopPop
  //cookie
  for ( var i=0;i < cookies.length; i++){
    if(cookies[i].substring(1,name.length+2) == (name + "=")) {
      cookie = cookies[i];
      break;
    }
  }
  
  //If we can't find the dontStopPop cookie do nothing.
  if (cookie == null) return;
  
  //The cookie value is the part after the equal sign
  var cookieValue = cookie.substring(name.length + 2);
  
  //Break into an array of name value pairs/
  var cookieValues = cookieValue.split('&');

  //Create a new object to store the cookie values
  var cookieObj = new Object(); 

  //Interate over the list of name/value pairs
  //spliting them into keys and values.
  for(var i=0;i < cookieValues.length; i++ ){
    if(cookieValues[i] != ""){
      cookieValues[i] = cookieValues[i].split('=');
    }     
  }
  
  //Iterate over the keys and values and add them as
  //properties to the cookie object.
  for(var i=0;i < cookieValues.length;i++){
    if(cookieValues[i][1] != null){
      cookieObj[cookieValues[i][0]] = decodeURIComponent(cookieValues[i][1]);
    }
  }
  
  //Return the object.    
  return cookieObj;
  
}

//Method to convert an object into a query string
function obj2query(obj, forPHP, parentObject){
   if( typeof obj != 'object' ) return '';

   if (arguments.length == 1)
      forPHP = /\.php$/.test(document.location.href);
   
   var rv = '';
   for(var prop in obj) if (obj.hasOwnProperty(prop) ) {

      var qname = parentObject
         ? parentObject + '.' + prop
         : prop;

      // Expand Arrays
      if (obj[prop] instanceof Array)
         for( var i = 0; i < obj[prop].length; i++ )
            if( typeof obj[prop][i] == 'object' )
               rv += '&' + obj2query( obj[prop][i], forPHP, qname );
            else
               rv += '&' + encodeURIComponent(qname) + (forPHP ? '[]' : '')
					+ '=' + encodeURIComponent( obj[prop][i] );

      // Expand Dates
      else if (obj[prop] instanceof Date)
         rv += '&' + encodeURIComponent(qname) + '=' + obj[prop].getTime();

      // Expand Objects
      else if (obj[prop] instanceof Object)
         // If they're String() or Number() etc
         if (obj.toString && obj.toString !== Object.prototype.toString)
            rv += '&' + encodeURIComponent(qname) + '=' + encodeURIComponent( obj[prop].toString() );
         // Otherwise, we want the raw properties
         else
            rv += '&' + obj2query(obj[prop], forPHP, qname);

      // Output non-object
      else
         rv += '&' + encodeURIComponent(qname) + '=' + encodeURIComponent( obj[prop] );

   }
   return rv.replace(/^&/,'');
}

function dontStopPopCheck(){
  //Read the cookie
  var dontStopPopCookie = cookieReader("dontStopPopCookie");
  
  //If there is no cookie return
  if (dontStopPopCookie == null) return;
  
  //Call a  method to convert the object to a query string.
  var qString = obj2query(dontStopPopCookie);
  
  //Grab properties from the cookie object  
  var showTheDontStopPop = dontStopPopCookie.popup;
  var refferingCheckoutProcess = dontStopPopCookie.processName;
  
  if( (showTheDontStopPop == "true") && ( refferingCheckoutProcess != "regco" ) ){
    $('#lightbox').addClass('checkout');
    launchPopup('Dont\'t Stop Pop','/checkout/dontStopPopStart',qString, '30', '30', "false" );
  }
}

function animateLBdimensions(width, height){
  $("#popup-body").attr("height", height);
  $("#main").animate({'height': height -23}, 'slow', '', function(){
    $("#popup-body").animate({'width': width + 145}, 'slow', '');
      $("#main").animate({'width': width}, 'slow', '');
  });
}

function setLBdimensions(width,height) {
  $("#popup-container").width(width);
  $("#popup-body").width(width);
  $("#main").height(height);
  $("#main").width(width);
}

/**
 * quiz popup function
 */
function takeQuiz(dsource) {
  if (typeof dsource == 'undefined') {
      dsource = '';
    }
  launchPopup('Quizzes!', '/profile/user/my/quiz/list', 'dsource=' + dsource, '470', '400', 'conditional');
}


function takeSelectedQuiz(quiz,close) {
  if (typeof close == 'undefined') {
      close = 0;
    }
  launchPopup('Quizzes!', '/profile/user/my/quiz/question', 'loadQuiz=' + quiz + '&closeMenuOnLoad=' + close, '470', '400', 'conditional');
}

function loadBTDT(layout,dsource) {
  $.ajax({
      type: "GET",
      url: "/profile/user/btdt",
      data: "layout="+ layout + "&dsource=" + dsource,
      cache: false,
      success: function (html){$("#btdtBlock").html(html);}
    });
}
