// Purpose:  Classmates Utilities

// Namespace:  Core
var cmo = cmo ? cmo : {};
cmo.analytics = cmo.analytics ? cmo.analytics : {};
cmo.dom = cmo.dom ? cmo.dom : {};
cmo.ui = cmo.ui ? cmo.ui : {};
cmo.ui.ads = cmo.ui.ads ? cmo.ui.ads : {};
cmo.util = cmo.util ? cmo.util : {};
// Namespace:  Applications
cmo.profile = cmo.profile ? cmo.profile : {};
cmo.profile.story = cmo.profile.story ? cmo.profile.story : {};
cmo.profile.friends = cmo.profile.friends ? cmo.profile.friends : {};
cmo.profile.photos = cmo.profile.photos ? cmo.profile.photos : {};
cmo.profile.bb = cmo.profile.bb ? cmo.profile.bb : {};

cmo.ui.ads.bindAdRefresh = function(){
  $("a.refresh,button.refresh,div.refresh").bind('click', function(){
    var params = $(this).attr('refparams');
    setTimeout(function(){refreshOASAds(null, null, null, null, null, params);}, 500);
  });
  $("select.refresh").bind('change', function(){
    var params = $(this).attr('refparams');
    setTimeout(function(){refreshOASAds(null, null, null, null, null, params);}, 500);
  });
};

//cmo.dom.append = function(elem){
//  $(this).append(elem);
//  cmo.ui.ads.bindAdRefresh();
//  cmo.analytics.bindAnalytics();
//};
//
//cmo.dom.appendHtml = function(html){
//  $(this).html(html);
//  cmo.ui.ads.bindAdRefresh();
//  cmo.analytics.bindAnalytics();
//};

//jQuery.fn.appendHtml = cmo.dom.appendHtml;
//jQuery.fn.appendObject = cmo.dom.append;

// Error slider in Create Event popover
function ShowDiv(divid,iframe, state)  {
  var DivRef = document.getElementById(divid);
  var IfrRef = document.getElementById(iframe);
  if(state)  {
    DivRef.style.display = "block";
    IfrRef.style.width = DivRef.style.width;
    IfrRef.style.height = DivRef.style.height;
    IfrRef.style.zIndex = DivRef.style.zIndex - 1;
    IfrRef.style.display = "block";
    top.document.getElementById("slideErrorsDiv").style.display="block";
  }
  else  {
    DivRef.style.display = "none";
    IfrRef.style.display = "none";
    top.document.getElementById("slideErrorsDiv").style.display="none";
  }
}

function togglePopupHintText(eleId, set, hintClass) {
    if(set==true && (typeof $("#" + eleId).val() == 'undefined' || $("#" + eleId).val()=="")) {
      $("#" + eleId).val($("#" + eleId).attr('hint'));
      $("#" + eleId).addClass(hintClass);
    } else if(set!=true && $("#" + eleId).val()==$("#" + eleId).attr('hint')){
      $("#" + eleId).val("");
      $("#" + eleId).removeClass(hintClass);
    }
  }

function addOmniture(pagename,hierarchy,channel,prop2,prop3,prop4){
  addAnalytics(pagename,hierarchy,channel,null,prop2,prop3,prop4);
}

/**
 * addAnalytics provides Ajax support for calling events.
 * Usage:
 *   1.  Define all new Omniture values
 *       addAnalytics("My Page","","","","","","","event00");
 *   2.  Use default values from calling page (preferred since it uses FOO)
 *       s_events = "event00";
 *       addAnalytics();
 */
cmo.analytics.addAnalytics = function (pageName,hier1,channel,prop1,prop2,prop3,prop4,events,prop5) {
  if ( typeof $('#useOmnitureDop')[0] != 'undefined' && $('#useOmnitureDop').val() == 'true'){
    var type = 'link';
    var v = {pagename:'',hier:'',memtype:'',prsctst:'',sitetst:'',pgdtl:'',prepg:'',activity:''};
    if ( typeof pageName != 'undefined' && pageName != ''){
      v.pagename = pageName;
      type = 'view';
    }
    if ( typeof hier1 != 'undefined' && hier1 != ''){
      v.hier = hier1;
    }
    if ( typeof prop1 != 'undefined' && prop1 != ''){
      v.memtype = prop1;
    }
    if ( typeof prop2 != 'undefined' && prop2 != ''){
      v.prsctst = prop2;
    }
    if ( typeof prop3 != 'undefined' && prop3 != ''){
      v.sitetst = prop3;
    }
    if ( typeof prop4 != 'undefined' && prop4 != ''){
      v.pgdtl = prop4;
    }
    if ( typeof events != 'undefined' && events != ''){
      v.activity = events;
    }
    if ( typeof prop5 != 'undefined' && prop5 != ''){
      v.prepg = prop5;
    }
    trackEvent.event(type, v);
  }
  else {
    if(arguments.length > 0) {
      s_pageName = pageName;
      s_hier1 = hier1;
      s_channel = channel;
      s_prop1 = prop1;
      // Don't duplicate calls for pageName in the request if not in the spec
      if (prop2 === "") {
        s_prop2 = pageName;
      } else {
        s_prop2 = prop2;
      }
      if (prop3 === "") {
        s_prop3 = pageName;
      } else {
        s_prop3 = prop3;
      }
      // Append any filter events to the pageName
      if (prop4 === "") {
        s_prop4 = pageName;
      } else {
        s_prop4 = pageName + prop4;
      }
      if(typeof prop5 != 'undefined' && prop5 != null && prop5 != "") {
        s_prop5 = prop5;
      }
      s_events = events;
    }
    if (s_dc(s_account)) {
      s_d.write(s_code);
    }
  }
}
cmo.analytics.parseAnalytics = function(e, attrs){
    var pageName = ''; var hier1 = ''; var channel = ''; var prop1 = '';
    var prop2 = ''; var prop3 = ''; var prop4 = ''; var prop5 = ''; var events = '';
    if ( typeof attrs == 'undefined' || attrs == null || attrs == ''){
      if ( this[0] && (this[0].tagName == 'SELECT' || this[0].tagName == 'OPTION')){
        attrs = $(this.options[this.selectedIndex]).attr('omniture');
      }
      else if ( this && this.type == 'checkbox'){
        if ( this.checked ){
          attrs = $(this).attr('omniture');
        }
      }
      else {
        attrs = $(this).attr('omniture');
      }
    }
    attrs = attrs.split(':');
    if ( attrs && attrs.length > 0 ){
      for ( var i=0;i<attrs.length;i++){
        var attr = attrs[i].split('=');
        if ( attr[0] == 'pageName' || attr[0] == 'pagename'){ pageName = attr[1]; }
        if ( attr[0] == 'hier1' || attr[0] == 'hier'){ hier1 = attr[1]; }
        if ( attr[0] == 'channel'){ channel = attr[1]; }
        if ( attr[0] == 'prop1' || attr[0] == 'memtype'){ prop1 = attr[1]; }
        if ( attr[0] == 'prop2' || attr[0] == 'prsctst'){ prop2 = attr[1]; }
        if ( attr[0] == 'prop3' || attr[0] == 'sitetst'){ prop3 = attr[1]; }
        if ( attr[0] == 'prop4' || attr[0] == 'pgdtl'){ prop4 = attr[1]; }
        if ( attr[0] == 'prop5' || attr[0] == 'prepg'){ prop5 = attr[1]; }
        if ( attr[0] == 'events' || attr[0] == 'activity'){ events = attr[1]; }
      }
      if ( typeof pageName != 'undefined' && pageName != ''){
        if ( typeof prop2 == 'undefined' || prop2 == null || prop2 == ''){
          prop2 = pageName;
        }
        if ( typeof prop3 == 'undefined' || prop3 == null || prop3 == ''){
          prop3 = pageName;
        }
      }
      addAnalytics(pageName,hier1,channel,prop1,prop2,prop3,prop4,events,prop5);
    }
};

cmo.analytics.ajaxAnalyticsBinded = false;

cmo.analytics.bindAjaxAnalytics = function(){
  if(!cmo.analytics.ajaxAnalyticsBinded){
    cmo.analytics.ajaxAnalyticsBinded = true;
    $('body').ajaxComplete(function(event,request, settings){
      if ( request.responseText && request.responseText.indexOf('omniture=') > -1 ||
        request.responseText.indexOf('omniture:') > -1){
        var temp = request.responseText;
        var start = 0;
        if ( temp.indexOf('omniture=') > -1 ){
          start = temp.indexOf('omniture=') + 10;
        }
        else if ( temp.indexOf('omniture:') > -1 ){
          start = temp.indexOf('omniture:') + 11;
        }
        temp = temp.substring(start);
        var end = start + temp.indexOf('\"');
        if ( end <= start ){
          temp = temp.substring(1);
          end = start + temp.indexOf('\"');
        }
        var omValue = request.responseText.substring(start, end);
        if ( omValue.indexOf('defer') > -1 ){
          cmo.analytics.bindAnalytics();
        }
        else {
          cmo.analytics.parseAnalytics(null, request.responseText.substring(start, end));
        }
      }
    });
  }
}

cmo.analytics.bindAnalytics = function(){
  $("form[omniture]").unbind('submit', cmo.analytics.parseAnalytics);
  $('a[omniture],button[omniture="track"],input[type="checkbox"][omniture],input[type="radio"][omniture]').unbind('click', cmo.analytics.parseAnalytics);
  $('select[omniture]').unbind('change', cmo.analytics.parseAnalytics);
  $("form[omniture]").bind('submit', cmo.analytics.parseAnalytics);
  $('a[omniture],button[omniture],input[type="checkbox"][omniture],input[type="radio"][omniture]').bind('click', cmo.analytics.parseAnalytics);
  $('select[omniture="track"]').bind('change', cmo.analytics.parseAnalytics);
  cmo.analytics.bindAjaxAnalytics();
};

addAnalytics = cmo.analytics.addAnalytics;

$(document).ready(function(){
  cmo.analytics.bindAnalytics();
  cmo.ui.ads.bindAdRefresh();
});

function hasSpecialChars(str){
  var iChars = "*|,\":<>[]{}`\';()@&$#%";
  for (var i = 0; i < str.length; i++) {
    if (iChars.indexOf(str.charAt(i)) != -1){
      return true;
    }
  }
  return false;
}
function isIE6(){
    var browser=navigator.appName;
    var b_version=navigator.appVersion;
    var version=parseFloat(b_version);

    if ( browser == 'Microsoft Internet Explorer' && version < 7 ){
        return true;
    }

    return false;
}

// Flash JS
//Sample use:
//<div id="flashDiv">
/*<script>displayFlash("flashDiv", "pathToSwfFile/filename.swf:String", width:Number, height:Number, "nameForSwf:String", AnyVars);</script>*/
//</div>
function displayFlash(myDiv, objSwf, myWidth, myHeight, name, varValue) {
        var swfText = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
        swfText += 'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" ';
        swfText += 'width="' + myWidth + '" height="' + myHeight + '" id="' + name + '" align="middle">';
        swfText += '<param name="allowScriptAccess" value="always" />';
        swfText += '<param name="movie" value="' + objSwf + '" />';
        swfText += '<param name="menu" value="false" />';
        swfText += '<param name="quality" value="high" />';
        swfText += '<param name="wmode" value="transparent" />';
        swfText += '<param name="bgcolor" value="#000000" />';
        swfText += '<param name="FlashVars" value="' + varValue + '">';
        swfText += '<embed src="' + objSwf + '" menu="false" quality="high" wmode="transparent" bgcolor="#000000"';
        swfText += ' FlashVars="' + varValue + '"';
        swfText += 'width="' + myWidth + '" height="' + myHeight + '" name="' + name + '" align="middle" ';
        swfText += 'allowScriptAccess="always" ';
        swfText += 'type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
        swfText += '</object>';

        var swfDiv = document.getElementById(myDiv);
        swfDiv.innerHTML = swfText;
}

/***** TABS CODE *****/
function whichBrowser() {
        var theBrowser;
        if (window.ActiveXObject) {
                theBrowser = "IE";
        }
        else if (window.XMLHttpRequest) {
                theBrowser = "Moz";
        }
        return theBrowser;
}
function getNextSibling(startBrother){
  endBrother=startBrother.nextSibling;
  while(endBrother.nodeType!=1){
    endBrother = endBrother.nextSibling;
  }
  return endBrother;
}
//Special function count node length properly because Firefox counts a line break as a "node"
function getNodeLength(objNode, count) {
        var newcount = count;
        for (i=0; i<newcount; i++) {
                if (objNode.childNodes[i].nodeType != 1){
        count--;
        }
        }
        return count;
}
function selectOn(objLink, tabType) {
        var tabNav = objLink.parentNode.parentNode.parentNode;

        var tabAmt = getNodeLength(tabNav, tabNav.childNodes.length);
        var tabDiv = objLink.parentNode.parentNode;
        var tabTxt = objLink.innerHTML;
        //First make sure all the tabs are NOT on the "on" state
        var tempObjL;
        var tempObjM;
        var tempObjR;
        var cssClass;
        if (whichBrowser() == 'IE') {
                cssClass = "className";
        } else {
                cssClass = "class";
        }
        for (i=1; i<=tabAmt; i++) {
                        tempObjL = document.getElementById(tabType+'tab'+i+'_L');
                        tempObjM = document.getElementById(tabType+'tab'+i+'_M');
                        tempObjR = document.getElementById(tabType+'tab'+i+'_R');
                        tempObjL.setAttribute(cssClass, tabType+'NavL');
                        tempObjM.setAttribute(cssClass, tabType+'NavMid');
                        tempObjR.setAttribute(cssClass, tabType+'NavR');
                        if (tabType+'tab'+i == tabDiv.id) {
                                tempObjL.setAttribute(cssClass, tabType+'NavL_on');
                                tempObjM.setAttribute(cssClass, tabType+'NavMid_on');
                                tempObjR.setAttribute(cssClass, tabType+'NavR_on');
                        }
        }
}
/**** END TAB CODE ****/
/**** INPUT CODE ****/
function onlyDigits(event) {
    var keycode;

    if(window.event) // Windows IE
    {
        keycode = window.event.keyCode;
    }
    else if(event.which) // Netscape/Firefox/Opera
    {
        keycode = event.which;
    }

    return ((keycode >= 48 && keycode <= 57) || keycode == 8 || keycode == 9 || keycode == 29
        || keycode == 37 || keycode == 39 || keycode == 46);

}

function consumeEnter(event){
    var keycode;

    if(window.event) // Windows IE
    {
        keycode = window.event.keyCode;
    }
    else if(event.which) // Netscape/Firefox/Opera
    {
        keycode = event.which;
    }

    if (keycode == 13){ return false;}

    return true;
}
/**** END INPUT CODE ****/
/**** MOUSEOVER CODE ****/
function swapImg(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('_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 buttonHover(source, obj){
  obj.src = source;
  return true;
}
/**** END MOUSEROVER ****/
/*** JUMPNAV CODE ***/
function jumpNav(objDiv, status) {
        var ulDiv = getNextSibling(objDiv);
        var objWidth;
        var objHeight;
        var titleWidth;
        if (whichBrowser() == 'IE') {
                hrefObj = objDiv.childNodes[0];
        } else {
                hrefObj = objDiv.childNodes[1];
        }

        if (status == 'hide') {
                //Hides Expanded Nav
                $(ulDiv).hide();
                //Hides Title Right Shadow
                $("div", objDiv).hide();
                //Remove Selected Class From Title
                $(objDiv).removeClass('jNavTitleSel');
                //Add Back Original Class From Title
                $(objDiv).addClass('jNavTitle');
                //Remove Bottom Border
                $("a", objDiv).css("borderBottom","none");
                //Show Select Arrow
                $("img", objDiv).css("visibility","visible");
        } else {
                //Fade In Expanded Nav
                //$(ulDiv).fadeIn("medium");
                $(ulDiv).show();
                //Show Title Right Shadow
                $("div", objDiv).show();
                //Bring Focus to Nav Title
                hrefObj.focus();
                //Remove Original Class From Title
                $(objDiv).removeClass('jNavTitle');
                //Add Selected Class For Title
                $(objDiv).addClass('jNavTitleSel');
                //Add Bottom Border
                $("a", objDiv).css("borderBottom","1px solid #CCCCCC");
                //Hide Select Arrow
                $("img", objDiv).css("visibility","hidden");
                //Resize Width of Expanded Nav
                tempObj = ulDiv.getElementsByTagName('ul');
                //alert(tempObj[0].offsetWidth);
                if (whichBrowser() == 'Moz') {
                    objWidth = tempObj[0].offsetWidth + 10;
                }
                else {
                    objWidth = tempObj[0].offsetWidth + 12;
                }
                objHeight = tempObj[0].offsetHeight;
                //New Expanded Nav Width
                $("div", ulDiv).css("width",objWidth);
                //Width for Expanded Nav Bottom Shdw
                $("div", $("div", ulDiv)).css("width",(objWidth));
                //Position & Width Adjustment for Expanded Nav Right Shdw
                $('div.crnrNavRLong').css("marginLeft",(objWidth+1));
                $('div.crnrNavRLong').css("height",(objHeight+27));
                $('div.crnrNavRLong').css("width","4px");
                //Position title nav shadow for Firefox
                titleWidth = objDiv.offsetWidth - 5;
                if (whichBrowser() == 'Moz') {
                        //Position and size for non IE
                        $("div", objDiv).css("margin-left",titleWidth);
                        $('div.crnrNavRLong').css("height",(objHeight+18));
                }

        }
}
function hideJumpNav(objDiv) {
        setTimeout(function() { jumpNav(objDiv, 'hide'); }, 500);
}
/*** END JUMPNAV CODE ***/
/*** FORM SUBMIT CODE ***/
/*
  For use with select boxes
  Make the select option have a value of ''
  All other values should be the full url of where you want to go
*/
function go(sBoxName){
  var selectBox = document.getElementById(sBoxName);
  destination = selectBox.value;
  if (destination) location.href = destination;
}

function goMemberListOptions(frmId,classUrl){
  var frm = document.getElementById(frmId);
  var startYear = document.getElementById('startYear').value;
  var endYear = document.getElementById('endYear').value;
  var yearRangeType = document.getElementById('yearRangeType').value;
  var tab = document.getElementById('tab').value;
  if (startYear > endYear){
    alert(startYear + ' greater than ' + endYear);
  }else if(yearRangeType == 0 && startYear == endYear){
    var classListUrl;
    classListUrl = classUrl + '&year=' + startYear + '&tab=' + tab;
    top.location = classListUrl;
  }else{
    frm.submit();
  }
}


function goSchoolMemberListOptions(frmId,classUrl){
  var frm = document.getElementById(frmId);
  var startYear = document.getElementById('startYear').value;
  var endYear = document.getElementById('endYear').value;
  var yearRangeType = 1;
  var tab = document.getElementById('tab').value;
  if (startYear > endYear){
    alert(startYear + ' greater than ' + endYear);
  }else if(yearRangeType == 0 && startYear == endYear){
    var classListUrl;
    classListUrl = classUrl + '&year=' + startYear + '&tab=' + tab;
    alert(classListUrl);
    top.location = classListUrl;
  }else{
    frm.submit();
  }
}
/*** END FORM SUBMIT CODE ***/
function changeRemaining(input, element, max) {
  var testStr = input.value;
  testStr = testStr.replace(/\r\n|\n/g, "\r\n");
  var rem = max - testStr.length;
  if (rem <= 0){
    input.value = testStr.substring(0, max);
    rem = 0;
  }
  document.getElementById(element).innerHTML = rem + " characters remaining<br>";
}

function setEnabled(id){
    var btn = document.getElementById(id);

    if ( typeof btn != 'undefined' && btn.src.indexOf('disabled') > -1 ){
        btn.disabled = false;
        var source = btn.src;
        btn.src = source.replace('_disabled.', '_off.');
    }
}
/*** POP UP FUNCTIONS     ***/

function redirectPage(url){
    var refreshUrl = top.location.href;
    if ( url.indexOf('com') < 0 ){
        refreshUrl = refreshUrl.substring(0, refreshUrl.indexOf('.com') + 4) + url;
    }
    else {
        refreshUrl = url;
    }
    top.location = refreshUrl;
}


function pageReload(){
    var refreshUrl, urlquery, params, isAction, count, prepend, isEmailActionEntry, isEmailAction;
    count = 0;
    prepend = '?';
    var url = top.location.href;

    if ( url.indexOf('#') > -1 )
        url = url.substring(0, url.indexOf('#'));
    urlquery= url.split('?');

    refreshUrl = urlquery[0] ;
    if(urlquery[1]){
        params=urlquery[1].split("&");
        for (var i=0; i<params.length; i++){
            isAction = params[i].indexOf("autoPopup");
            isEmailAction = params[i].indexOf("emailAction");
            isEmailActionEntry = !(urlquery[1].indexOf("emailAction")!=-1 && params[i].indexOf("entryId")!=-1);
            if (isAction && isEmailAction && isEmailActionEntry){
                if(count!=0){
                    prepend = '&';
                }
                refreshUrl += prepend + params[i];
                count++;
            }
            if ((params[i].indexOf("action=categoryGateway") == 0) ||(params[i].indexOf("action=DisplayDiscussion") == 0) ||(params[i].indexOf("action=DisplayViewPreference") == 0)){
                if(count!=0){
                    prepend = '&';
                }
                refreshUrl += prepend + params[i];
                count++;
            }else{
                isAction = params[i].indexOf("action");
                if (isAction){
                    if(count!=0){
                        prepend = '&';
                    }
                }
            }
        }
    }

    if(top.location.hash!=null && (top.location.hash!="" & top.location.hash!="#") && (top.location.href.split("#")[0]==refreshUrl)) {
      var tempForm = document.createElement("form");
      document.getElementsByTagName("body")[0].appendChild(tempForm);
      tempForm.setAttribute("action", refreshUrl + top.location.hash);
      tempForm.setAttribute("method", "POST");
      tempForm.submit();
    } else {
      top.location = refreshUrl;
    }
}

function successClose() {
  //window.parent.location.reload(true);
  pageReload();
}

function hideMemberConduct(hideDiv, showDiv, linkDisplay){
    document.getElementById('sliderFrame').scrolling = 'no';
    $("#slideDown").slideUp('slow', function(){
      top.window.scrollTo(0,0);
      if(top.origMainHeight) {
        $("#main").css({height: top.origMainHeight});
      }
      top.origMainHeight = null;
    });
    top.sliderOpen = false;
    if(typeof(showing) != "undefined"){
	  showing = false;
    }
}

function showMemberConduct(hideDiv, showDiv, uri, anchor){
    if ( top.sliderOpen ){ //Slider is already open. Just reset the src of the slideframe
        var href = top.location.href;
        href = href.substring(0, href.indexOf('com') + 3);
        href += '/cmo/terms.jsp?noNav=true';
        document.getElementById('sliderFrame').src = href;
    }
    else {
        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(){
            if ( document.getElementById('sliderFrame').src.indexOf('terms.jsp') < 0){
                var src = '';
                if ( typeof uri == 'undefined'){
                    var href = top.location.href;
                    href = href.substring(0, href.indexOf('com') + 3);
                    uri = href + '/cmo';
                }
                src += uri + '/terms.jsp?noNav=true';
                if ( typeof anchor == 'undefined') anchor = 'conduct';
                src += '&anchor=' + anchor;
                document.getElementById('sliderFrame').src = src;
            }
            else {
                try {
                if ( typeof document.getElementById('sliderFrame').contentWindow.document.getElementById(anchor) != 'undefined' && anchor != '' )
                    document.getElementById('sliderFrame').contentWindow.document.getElementById(anchor).scrollIntoView(true);
                } catch(ex) {}
                top.window.scrollTo(0,0);
            }
        });
    }
}

function hidePrivacyPolicy(hideDiv, showDiv){
  document.getElementById(hideDiv).style.display = 'none';
  document.getElementById(showDiv).style.display = 'block';
}

function showPrivacyPolicy(hideDiv, showDiv){
  document.getElementById(hideDiv).style.display = 'none';
  document.getElementById(showDiv).style.display = 'block';
}

/*** END POP UP FUNCTIONS ***/

function ReadCookie (CookieName){
  var CookieString = document.cookie;
  var CookieSet = CookieString.split (';');
  var SetSize = CookieSet.length;
  var CookiePieces;
  var ReturnValue = "";
  var x = 0;

  for (x = 0; ((x < SetSize) && (ReturnValue == "")); x++){
    CookiePieces = CookieSet[x].split ('=');
    if (CookiePieces[0].substring (0,1) == ' '){
      CookiePieces[0] = CookiePieces[0].substring (1, CookiePieces[0].length);
    }

    if (CookiePieces[0] == CookieName){
      ReturnValue = CookiePieces[1];
    }
  }

  return ReturnValue;
}

function WriteCookie (CookieName, CookieValue, ExpireDays) {
  var today = new Date();
  var expire = new Date();
  if (ExpireDays==null) ExpireDays=0;
  if (ExpireDays>0)  expire.setTime(today.getTime() + 3600000*24*ExpireDays);
  if (ExpireDays==0)
  	document.cookie = CookieName+'='+CookieValue+'; path=/';
  else
  	document.cookie = CookieName+'='+CookieValue+'; expires='+expire.toGMTString()+'; path=/';
}

function swapImg(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('_off.') != -1)
                                        img.src = src.replace('_off.', '_on.');
                        else if(src.indexOf('_on.') != -1)
                                        img.src = src.replace('_on.', '_off.');
                        break
        }
}


function makeShadow(eleId, parentEle) {
  $(parentEle?parentEle:"body").append("<div class='wrap hide' id='tr" + eleId + "Wrap'><div class='trShadow' id='tr" + eleId + "'></div></div><div class='wrap hide' id='r" + eleId + "Wrap'><div class='rShadow' id='r" + eleId + "'></div></div><div class='wrap hide' id='br" + eleId + "Wrap'><div class='brShadow' id='br" + eleId + "'></div></div><div class='wrap hide' id='bl" + eleId + "Wrap'><div class='blShadow' id='bl" + eleId + "'></div></div><div class='wrap hide' id='b" + eleId + "Wrap'><div class='bShadow' id='b" + eleId + "'></div></div>");
  var w = $("#" + eleId)[0].offsetWidth;
  var h = $("#" + eleId)[0].offsetHeight;
  var l = parentEle?$("#" + eleId)[0].offsetLeft:getElementPosition(eleId).left;
  var t = parentEle?$("#" + eleId)[0].offsetTop:getElementPosition(eleId).top;

  $("#bl" + eleId + "Wrap").css({left: l, top: t+h});
  $("#br" + eleId + "Wrap").css({left: l+w, top: t+h});
  $("#tr" + eleId + "Wrap").css({left: l+w, top: t});
  $("#b" + eleId + "Wrap").css ({left: l+8, top: t+h, width: w-8});
  $("#r" + eleId + "Wrap").css ({left: l+w, top: t+8, height: h-8});
  $("#b" + eleId).css ({width: w-8});
  $("#r" + eleId).css ({height: h-8});
  $('div.wrap').show();
}

function hideShadow(eleId) {
  $("#bl" + eleId + "Wrap").remove();
  $("#br" + eleId + "Wrap").remove();
  $("#tr" + eleId + "Wrap").remove();
  $("#b" + eleId + "Wrap").remove();
  $("#r" + eleId + "Wrap").remove();
}


function getElementPosition(elemID) {
  var offsetTrail = document.getElementById(elemID);
  var offsetLeft = 0;
  var offsetTop = 0;
  while (offsetTrail) {
    offsetLeft += offsetTrail.offsetLeft;
    offsetTop += offsetTrail.offsetTop;
    offsetTrail = offsetTrail.offsetParent;
  }
  if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") {
        offsetLeft += parseInt(document.body.leftMargin);
        offsetTop += parseInt(document.body.topMargin);
  }
  return {left:offsetLeft, top:offsetTop};
}

function getPageHeightWithScroll(){
    var _docHeight = (document.height || document.body.offsetHeight) + (window.scrollMaxY || document.body.scrollHeight) ;
    return _docHeight;
}

function getPageHeight(){
    if (window.innerHeight && window.scrollMaxY) {
      var docHeight = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
      var docHeight = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      var docHeight = document.body.offsetHeight;
    }

    return docHeight + 200;
}

function getPageWidth(){
    if (window.innerWidth && window.scrollMaxX) {
      var docWidth = window.innerWidth + window.scrollMaxX;
    } else if (document.body.scrollWidth > document.body.offsetWidth){ // all but Explorer Mac
      var docWidth = document.body.scrollWidth;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      var docWidth = document.body.offsetWidth;
    }

    return docWidth;
}
function getPageScrollY(){
	var yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	}else {
     // all other Explorers
		if(document.documentElement){
			try{
			yScroll=document.documentElement.scrollTop;
			if(!yScroll && document.body){
				yScroll = document.body.scrollTop;
			}
			}catch(e){
				yScroll = document.body.scrollTop;
			}
		} else{			
		  yScroll = document.body.scrollTop;
		}
	}			
	return yScroll;
}
function textAreaReplaceBreaks(id){
    var element = document.getElementById(id);
    var text = new String(element.value);
    while ( text.indexOf('<br\/') > -1 ){
      text = text.replace(/<br\/>/, "\n");
    }
    element.value = text;
}

function textAreaReplaceNewlines(id){
    var element = document.getElementById(id);
    var text = new String(element.value);
    while ( text.indexOf('\n') > -1 ){
      text = text.replace(/\n/, "<br>");
    }
    element.value = text;
}

function divReplaceBreaks(id){
    var element = document.getElementById(id);
    var text = new String(element.innerHTML);
    while ( text.indexOf('<br\/') > -1 ){
      text = text.replace(/<br\/>/, "\n");
    }
    element.innerHTML = text;
}

function divReplaceNewlines(id){
    var element = document.getElementById(id);
    var text = new String(element.innerHTML);
    while ( text.indexOf('\n') > -1 ){
      text = text.replace(/\n/, "<br>");
    }
    element.innerHTML = text;
}

// Remove whitespace in a string
// This will have no newlines and only single spaces
cmo.util.collapseWhitespace = function(string) {
  // Replace newlines with spaces (to be cleaned later)
  string = string.replace(/(\r\n|\r|\n)/g, ' ');
  string = string.replace(/(\s+)/g, ' ');
  // Chomp spaces at beginning and end of string.
  string = string.replace(/(^\s)/g, '');
  string = string.replace(/(\s$)/g, '');
  return string;
};


/* Get all relevant text entries and data from an element.
 * Alias:  dom2text
 */
cmo.util.getText = function(eId) {
    e = document.getElementById(eId);
    var strings = [];
    getStrings(e,strings);
    return cmo.util.collapseWhitespace(strings.join(""));

    function getStrings(n, strings) {
        if (n.nodeType == 3) {  // Text node so just add the text
            strings.push(n.data);
        } else if (n.nodeType == 1) { // Element node so check for data and keep processing
            switch (n.nodeName)
            {
            case "TEXTAREA":
                // Check for a value otherwise put in underscores or default value
                value = n.value;
                strings.push(n.value);
								//n.value='';
                break;
            case "INPUT":
                // Check for a value otherwise put in underscores or default value
                value = n.value;
                strings.push(n.value);
								//n.value='';
                break;
            case "IMG":
                value = n.alt;
                strings.push(n.value);
								//n.value='';
                break;
            }
            for (var m = n.firstChild; m != null; m = m.nextSibling) {
								if(n.nodeName == "TEXTAREA"){
									continue;
								} else {
	                getStrings(m, strings);
								}
            }
        }

    }
};

function inputFindSpaces(id)  {
    var inputValue = document.getElementById(id).value;
    var text=inputValue.replace(/^\s+|\s+$/g, '');
    document.getElementById(id).value=text;
}


cmo.util.clearText = function(eId) {
    e = document.getElementById(eId);
    clearStrings(e);
    //return cmo.util.collapseWhitespace(strings.join(""));

    function clearStrings(n) {
        if (n.nodeType == 1) { // Element node so check for data and keep processing
            switch (n.nodeName)
            {
            case "TEXTAREA":
								n.value='';
                break;
            case "INPUT":
								n.value='';
                break;
            case "IMG":
								n.value='';
                break;
            }
            for (var m = n.firstChild; m != null; m = m.nextSibling) {
								if(n.nodeName == "TEXTAREA"){
									continue;
								} else {
	                clearStrings(m);
								}
            }
        }
    }
};

function storyWizInputs(eId) {
    var w = document.getElementById(eId);
		var thelengths = [];
    var thelen = 0;
		getLengths(w,thelengths);
		for(c = 0;c < thelengths.length;c++){
			if(thelengths[c] == 0) {
				return 0;
			} else {
				thelen = thelen + thelengths[c];
			}
		}
    return thelen;

    function getLengths(n, thelen) {
				if (n.nodeType == 3) {  // Text node so just count the text
						theValue = n.data.replace(/\r\n|\n/g, "\r\n");
						theValueLength = theValue.length;
						thelengths.push(theValueLength);
				} else if (n.nodeType == 1) { // Element node so check for data and keep processing
							switch (n.nodeName)
							{
							case "TEXTAREA":
									thelengths.push(n.value.length);
									break;
							case "INPUT":
									thelengths.push(n.value.length);
							}
							for (var m = n.firstChild; m != null; m = m.nextSibling) {
									if(n.nodeName == "TEXTAREA"){
										continue;
									} else {
										getLengths(m, thelengths);
									}
							}
				}
    }
};

// Process additions of any handlers for the booklet or pagination
// after an update of the wizard
// Requires #storyWizardGenerate for the location of the generation features   --- <a href='#' id='storyWizardAddToStory'>ADD TO STORY</a> ---
cmo.profile.story.prepareWizard = function(page) {
  pageClasses = page.attr("class");
  pageTitle = page.attr("title");
	defaultstory = "Catch 'em up on what you've done and who you are.";
  switch (pageClasses)
    {
    case "swc":
        jQuery("#storyWizardGenerate")
        .html("<br><button class='btn-dead' style='cursor:default;' id='storyWizardAddToStory'><span class='outer'><span class='inner'>ADD TO STORY</span></span></button>");

				jQuery("#storyWizardBooklet")
					.keyup(function(){
					inputLength = storyWizInputs("storyWizardBooklet");
					if(inputLength > 0 && jQuery("#storyWizardAddToStory").hasClass("btn-dead")){
						enableCssBtn("storyWizardAddToStory");
						jQuery("#storyWizardAddToStory").css("cursor","pointer");
						jQuery("#storyWizardAddToStory")
						.click(function(){
								response = cmo.util.getText("storyWizardBooklet");
								var theElen = jQuery("#editStory").val();
								theElen = theElen.replace(/\r\n|\n/g, "\r\n");
								totalLength = theElen.length + inputLength;
								if(totalLength > 20050){
									bubbles.showMessage("You've exceeded the maximum character count.","storyWizardAddToStory", "notclickable");
								} else {
									if(jQuery("#editStory").val().length == 0 || jQuery("#editStory").val() == defaultstory){
										jQuery("#editStory").val(response + "\r\n");
									} else {
										jQuery("#editStory").val(jQuery("#editStory").val() + "\r\n" + response + "\r\n");
									}
									response = cmo.util.clearText("storyWizardBooklet");
									bubbles.showMessage("To keep what you've written, click SAVE YOUR STORY.", "storyWizardAddToStory", "notclickable");
									disableCssBtn('storyWizardAddToStory');
									jQuery("#storyWizardAddToStory").unbind("click");
									jQuery("#storyWizardAddToStory").css("cursor","default");
									enableCssBtn("saveStoryButton");
                  enableCssBtnSubmit("saveStoryButton");
									// Get the appending value for the main page
									s_prop4 = s_pageName + "_" + pageTitle;
									cmo.analytics.addAnalytics();
									return false;
								}
						});
					} else if(inputLength == 0 && jQuery("#storyWizardAddToStory").hasClass("btn-hover")) {
						disableCssBtn("storyWizardAddToStory");
						jQuery("#storyWizardAddToStory").css("cursor","default");
						jQuery("#storyWizardAddToStory").unbind("click");
					}
				});
       break;
    case "swb":
        jQuery("#storyWizardGenerate")
        .html("<textarea id='storyWizardTextarea' rows='5' cols='14'></textarea>" +
              "<br><br><button class='btn-dead' style='cursor:default;' id='storyWizardAddToStory'><span class='outer'><span class='inner'>ADD TO STORY</span></span></button>");

				jQuery("#storyWizardTextarea")
        .keyup(function(){
					if(jQuery("#storyWizardTextarea").val().length > 0 && jQuery("#storyWizardAddToStory").hasClass("btn-dead")){
						enableCssBtn("storyWizardAddToStory");
						jQuery("#storyWizardAddToStory").css("cursor","pointer");
						jQuery("#storyWizardAddToStory")
							.click(function(){
									response = cmo.util.getText("storyWizardTextarea");
									var theElen = jQuery("#editStory").val()  + response;
									theElen = theElen.replace(/\r\n|\n/g, "\r\n");
									if(theElen.length > 20050){
										bubbles.showMessage("You've exceeded the maximum character count.", "storyWizardAddToStory", "notclickable");
									} else {
										if(jQuery("#editStory").val().length == 0 || jQuery("#editStory").val() == defaultstory){
											jQuery("#editStory").val(response + "\r\n");
										} else {
											jQuery("#editStory").val(jQuery("#editStory").val() + "\r\n" + response + "\r\n");
										}
										response = cmo.util.clearText("storyWizardTextarea");
										bubbles.showMessage("To keep what you've written, click SAVE YOUR STORY.", "storyWizardAddToStory", "notclickable");
										disableCssBtn('storyWizardAddToStory');
										jQuery("#storyWizardAddToStory").unbind("click");
										jQuery("#storyWizardAddToStory").css("cursor","default");
										enableCssBtn("saveStoryButton");
                    enableCssBtnSubmit("saveStoryButton");
										s_prop4 = s_pageName + "_" + pageTitle;
										cmo.analytics.addAnalytics();
										return false;
									}
							});
					} else if(jQuery("#storyWizardTextarea").val().length == 0 && jQuery("#storyWizardAddToStory").hasClass("btn-hover")) {
						disableCssBtn("storyWizardAddToStory");
						jQuery("#storyWizardAddToStory").css("cursor","default");
						jQuery("#storyWizardAddToStory").unbind("click");
					}
				});
       break;
    default:
      jQuery("#storyWizardGenerate").html("");
      break;
    }
}
function validateWizard(wiztype,wid,wizbtn){
	switch(wiztype){
		case "swb":
			alert('hohoho');
			f=document.getElementById(wid);
			if(f.value.length > 0 && $("#"+wizbtn).hasClass("btn-dead")  ){
				enableCssBtn(wizbtn);
			}
	}
}
function disableCssBtn(id){
	$("#"+id).removeClass('btn-hover');
	$("#"+id).addClass('btn-dead');
}
function enableCssBtn(id){
	$("#"+id).removeClass('btn-dead');
	$("#"+id).addClass('btn-hover');
}

function getPageDimensions(){
  var xScroll, yScroll;
  if (window.innerHeight && window.scrollMaxY) {
    xScroll = document.body.scrollWidth;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }
  var windowWidth, windowHeight;
  if (self.innerHeight) {       // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }
  pageHeight = document.body.scrollHeight;
  pageWidth = xScroll;
  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
  return arrayPageSize;
}

function addScrollerPhotoShadow(elem){
    if ( elem.parentNode.className.indexOf('thumb') == -1){
        elem = $(elem).wrap('<span class="thumb"></span>');
    }
}
function addShadow(elem){
    if ( elem.parentNode.className.indexOf('shadowContent') == -1){
      elem = $(elem).wrap('<div class=\"shadowBox\"></div>');
      elem = $(elem).wrap('<div class=\"shadow1\"></div>');
      elem = $(elem).wrap('<div class=\"shadow2\"></div>');
      elem = $(elem).wrap('<div class=\"shadow3\"></div>');
      elem = $(elem).wrap('<div class=\"shadow4\"></div>');
      elem = $(elem).wrap('<div class=\"shadowContent\"></div>');
    }
}

function calculateIEimgWidth(width, height){
    if ( width > 80 ){
        if ( width > height ){
            return "80px";
        }
        else{
            var t = 80/height;
            t = t*width;
            return t + "px";
        }
    }
    else {
        return "auto";
    }
}

function calculateIEimgHeight(height, width){
    if ( height > 80 ){
        if ( height > width ){
            return "80px";
        }
        else{
            var t = 80/width;
            t = t*height;
            return t + "px";
        }
    }
    else {
        return "auto";
    }
}

// This  functuion truncates the string to the specified trunction limit, ignoring the wordbreaks while calculating the length of the substring to be displyed.


function truncIgnoringWordBreak(cname, truncateLimit, counter) {

  var fullNameLen = cname.length;
  var spaceLen = cname.split(" ").length - 1;
  var nameWithoutSpaceLen= fullNameLen - spaceLen;
  var dispName=cname;
  var extraChar = nameWithoutSpaceLen - truncateLimit;

  if(extraChar > 0) {
    var nameEndingStr=cname.substring(fullNameLen-extraChar, fullNameLen);
    var theSpaceLen = nameEndingStr.split(" ").length -1;
    dispName = cname.substring(0,fullNameLen-(extraChar+theSpaceLen));
    dispName = dispName +"...";
  }
  $("#CREName"+counter).html(dispName);
}

function getCookie(name){
    var cookies = document.cookie.split(';');
    for ( var i = 0; i < cookies.length; i++ ){
        var cookie = cookies[i];
        while(cookie.charAt(0)==' ')
            cookie=cookie.substring(1,cookie.length);
        if(cookie.indexOf(name)==0)
            return cookie.substring(name.length + 1,cookie.length);
    }
    return '';
}

function setCookie( name, value, expires, path, domain, secure ){
  var today = new Date();
  today.setTime( today.getTime() );

  if ( expires ){
  expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );

  document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}


function checkAskMeLimit(checkboxIndex) {

  var warningDisp=$("#warningDisp").html();
  var threshold=$("#threshold").html();
  var reqMadeSoFar=$("#updateReqMadeSoFar").html();
  var reqPending=$("#updateReqPending").html();


if(parseInt($("#updateReqMadeSoFar").html()) <= parseInt(threshold)){
  if ($('#'+checkboxIndex).attr('checked')){
     $("#updateReqMadeSoFar").html(parseInt(reqMadeSoFar)+1);
     $("#updateReqPending").html(((parseInt(reqPending)-1) == 0)?"0": (parseInt(reqPending)-1) );
      if(parseInt($("#updateReqMadeSoFar").html()) == parseInt(warningDisp)){
        $("#warningMsgDynamic").css({display:""});
      }
  }else{
    $("#updateReqMadeSoFar").html(((parseInt(reqMadeSoFar)-1) == 0)?"0":(parseInt(reqMadeSoFar)-1));
    $("#updateReqPending").html(parseInt(reqPending)+1);
      if(parseInt($("#updateReqMadeSoFar").html()) < parseInt(warningDisp)){
        $("#warningMsgDynamic").css({display:"none"});
      }
  }
}


if(parseInt($("#updateReqMadeSoFar").html()) >= parseInt(warningDisp)){

  $("#warningMsgStatic").css({display:"none"});
  $("#warningMsgDynamic").css({display:""});

  if(parseInt($("#updateReqMadeSoFar").html()) == parseInt(threshold)){
    $("#askMeCheckList input[type='checkbox']").each(function(){
        if (!this.checked){
          $(this).attr("disabled","disabled");
          $(this).parent().css({color:'#cccccc'});
        }
    });
  }else if(parseInt($("#updateReqMadeSoFar").html()) < parseInt(threshold)){
    $("#askMeCheckList input[type='checkbox']").each(function(){
       if (this.disabled){
          $(this).removeAttr('disabled');
          $(this).parent().css({color:'#666666'});
       }
    });
 }

 }

}


function askMeDisableAll() {
    $("#askMeCheckList input[type='checkbox']").each(function(){
          $(this).attr("disabled","disabled");
          $(this).parent().css({color:'#cccccc'});
    });
}
