//
// common.js
//
// These functions were extracted from wss.jsp and memberAcquisition.jsp to reduce html page size
//
// Created 8/7/2006 - Mike Austin
//

function createCookie(name,value,days){
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}

function readCookie(c_name) {	
	if (document.cookie.length > 0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) {
				c_end=document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return null;
}

function appendCookie(name, value){
  var oldValue = readCookie(name);
  var newValue = value.substring(value.indexOf("friend/") + 6);
  newValue = new Date().getTime() + newValue;
  if (oldValue == null || oldValue.length==0){
    oldValue = newValue;
  }
  else{
    oldValue = oldValue + "!" + newValue;
  }
  eraseCookie(name);
  createCookie(name, oldValue, 7);
  if (oldValue.split(",").length > 5)
  {
        return 1;
  }
  else
  {
    return 0;
  }
}

function hasHi5Cookie() {
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		if(c.match(/^hi5*/)) {
			return true;
		}		
	}
	
	return false;
}

function getViewerSegment() {
	
	var segment;
	if( readCookie("hi5loggedIn") != null) {		
		segment = '4'; //AUTH_MEMBER
	} else if ((readCookie("Email") != null)  || (readCookie("Userid") != null) ) {
		segment = '3'; //UNAUTH_MEMBER
	} else if (hasHi5Cookie()) {	
		segment = '2'; //RET_VISITOR
	} else {	
		segment = '1'; //NEW_VISITOR
	}
	return segment;
}

function getViewerId() {
	var viewerId;
	viewerId = readCookie("Userid");
	return viewerId;
}

function isUserInPopulation() {
	var flag = false;
	
	if(readCookie("hi5loggedIn") != null && readCookie("hi5loggedIn")=="true") { // if member
		var viewerId = getViewerId();
		if((viewerId > 0) && ((viewerId % 1000) <= 9)) { // if user in sample
			createCookie("WSSSampleCookie","Y",30*365);
			flag = true;	
		} else {
			createCookie("WSSSampleCookie","N",30*365);	
			flag = false;
		}
		
	} else { // else visitor
		if(readCookie("WSSSampleCookie") == null) { // if no sample cookie
			var jSessionId = readCookie("JSESSIONID");
			if(jSessionId != null && (getHashCode(jSessionId) % 100 == 0)) { // check visitor in sample from jsessionid
				createCookie("WSSSampleCookie","Y",30*365);		
			} else {
				createCookie("WSSSampleCookie","N",30*365);		
			}
		} 
		
		if(readCookie("WSSSampleCookie") == "Y") {
			flag = true;
		} else {
			flag = false;
		}
	}
	
	return flag;
}

function getHashCode(str) {
	var count = str.length;
	var hashcode = 0;
	for(var i=0;i<count;i++) {
		hashcode = parseInt(hashcode * 31 + str.charCodeAt(i));
		hashcode = hashcode & 0x00000000FFFFFFFF; // to convert long to int
	}
	return hashcode;
}

function getLoginMetrics() {
	var loginInfo = readCookie("LoginInfo");
	if( loginInfo != null) {
		eraseCookie("LoginInfo");		
		return loginInfo;
	}
	
	return null;
}

function hitServer(ajaxUrl) {
	var req = null;

	if(window.XMLHttpRequest)
			req = new XMLHttpRequest();
	else if (window.ActiveXObject)
			req  = new ActiveXObject(Microsoft.XMLHTTP);

	req.open("GET", ajaxUrl, true);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(null);
}

//
// This function is kept to ensure compatibility, since implementation of above readCookie() is different.
//

function readCookie2(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++){
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

//
// The following functions were moved from common/common.jsp
//

function init(){
	check_frame();
	if ( window.init_form ){
		init_form();
	}
}


function check_frame() {
	 if ( top.location != document.location ){
	  //top.location=document.location;
	 }
}

function init_login_form(){
	if (document.loginForm!=null){
		var email = getcookie("Email");
		if(email != null)
	   		document.loginForm.email.value=email;
		}
	
}

function getcookie(cookiename) {
 var cookiestring=""+document.cookie;
 var index1=cookiestring.indexOf(cookiename);
 if (index1==-1 || cookiename=="") return ""; 
 var index2=cookiestring.indexOf(';',index1);
 if (index2==-1) index2=cookiestring.length; 
 return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}


function popup(mylink, windowname, features)
{
	if (! window.focus){
		return true;
	}
	var href;
	if (typeof(mylink) == 'string'){
	   href=mylink;
	}else{
	   href=mylink.href;
	}
	window.open(href, windowname, features);
	return false;
}

//
// Common Dreamweaver functions
//

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



function showContextArrow(div) {
    if ($(div).style.display == 'none') {
        var arr_nodes = document.getElementsByTagName('div');

        for (i = 1; i < (arr_nodes.length); i++) {
            //hide all other profile arrows
            if (arr_nodes[i].className == 'ctx_menu_prompt') {
                arr_nodes[i].style.display = "none";
            }
            if (arr_nodes[i].className == 'link-menu') {
                arr_nodes[i].style.display = 'none';
            }
            if (arr_nodes[i].className == 'username-link') {
                arr_nodes[i].style.background = "";
                arr_nodes[i].style.borderLeft = "";
                arr_nodes[i].style.borderRight = "";
                arr_nodes[i].style.borderTop = "";
            }
        }

        //    new Effect.Appear($(div));
        $(div).style.display = "block";
        baseId = div.substring(6);
        $('username-link' + baseId).style.background = "#95b4e3";
        $('username-link' + baseId).style.borderLeft = "1px solid #bbbbbb";
        $('username-link' + baseId).style.borderRight = "1px solid #bbbbbb";
        $('username-link' + baseId).style.borderTop = "1px solid #bbbbbb";
    }
}

function showContextMenu(div, userId, originURI) {
  var isFriend = false;

  // don't make this request if the user is anonymous
  if (userId > 0) {
    var opt = {
      method: 'post',
      postBody: 'friendId=' + userId,
      onSuccess: function(t) {
        // construct the menu based on the relationship
        output = "";
        if (t.responseText.indexOf("true") < 0) {
          output = "<a class='menu' href='/friend/displayAddFriend.do?userid=" + userId + "&originURI=" + originURI + "'>Add as Friend</a><br>";
          output += "<hr size='1' width='50%'/>"
        }
//        if(t.responseText.indexOf(",") >= 0) {
//          var numPhotos = t.responseText.substring(t.responseText.indexOf(",")+1);
//          output += "<a class='menu' style='color:red !important;' href='/friend/profile/displayGallery.do?userid=" + userId + "'>" + numPhotos + " New Photos!</a><br>";
//        }
//        output += "<hr size='1' width='50%'/>"
        output += "<a class='menu' href='/friend/mail/displayComposeMail.do?toIds=" + userId + "&originURI=" + originURI +"'>Send Message</a><br>";
        output += "<a class='menu' href='/friend/fives/displayAddUserFive.do?userid=" + userId + "&originURI=" + originURI + "'>Give em Five</a><br>";
        output += "<a class='menu' href='/friend/book/displaySignBook.do?userid=" + userId + "&originURI=" + originURI + "'>Add Comment</a><br>";
        output += "<a class='menu' href='/friend/addBookmark.do?userid=" + userId + "&originURI=" + originURI + "'>Add to Favorites</a><br>";
        Element.update(div, output);
        //new Effect.BlindDown(document.getElementById(div));
        document.getElementById(div).style.display = 'block';
      },
      onFailure: function(t) {
        new Effect.Shake(div);
      }
    }
    new Ajax.Request('/friend/checkFriend.do', opt);
  }

}

function changeArrow(img) {
  img.src = 'http://images.hi5.com/images/context_menu_arrow2.gif';
}

function contains(a, b) {
  while (b.parentNode)
    if ((b = b.parentNode) == a)
      return true;
  return false;
}
function closeMenu(element, event) {
  var current, related;

  if (window.event) {
      current = window.event.fromElement;
      related = window.event.toElement;
  } else {
    current = event.currentTarget;
    related = event.relatedTarget;
  }

//    if(current.className == "ctx_menu_prompt") {
//        current.style.display = 'none';// Effect.Fade(element);
//    } else if(current.className == "link-menu" && !contains(current, related)) {
//        //current.style.display = 'none';//        new Effect.BlindUp(element);
//    } else {
//        var baseId = current.id;
//        if(baseId.indexOf("friend") > -1) {
//            baseId = baseId.substring(6);
//        } else if(baseId.indexOf("menu") > -1) {
//            baseId = baseId.substring(4);
//        }
//        var friendId = "friend"+baseId;
//        var menuId = "menu"+baseId;
//        $(friendId).style.display = 'none';//new Effect.Fade(friendId);
//        $(menuId).style.display = 'none';//new Effect.BlindUp(menuId);
//    }
}
//  if (current != related && !contains(current, related) && related.className != "ctx_menu_prompt") {
//        var friendId = "friend"+baseId;
//        var menuId = "menu"+baseId;
//        new Effect.Fade(friendId);
//        new Effect.BlindUp(menuId);
//  }
  //}

/*
function closeMenu(element) {
    if(element.className == "ctx_menu_prompt") {
        new Effect.Fade(element);
    } else if(element.className == "link-menu") {
        new Effect.BlindUp(element);
    }
}
*/