//************************ ISBN LOGIC **********************************

var timerID = null;
var inputText;
var DVDWarnMsg = "NOTE: You MUST have the original artwork and case to list a DVD for trade.";
var CDWarnMsg = "NOTE: to list a CD for trade, all tracks MUST be playable";
var college_name;
var sItemImagePath=''; //this variable maintains item image path
function setItemImagePath(sImagePath) //function to set item imagepath
{
	sItemImagePath=sImagePath;
}

function ISBNKeyPress2() {
    inputText = $F('txtISBN');
    inputText = inputText.replace(/\W+/g,"").replace(/[a-wA-Wy-zY-Z]/g,"").replace("_","");
    if (inputText.length > 9) { 
		if (timerID != null) {window.clearTimeout(timerID);}
		timerID = window.setTimeout('AJAXISBNRequest2()', 400);  // waits a period of time without any keypresses before firing the ajax call
	}
}

function AJAXISBNRequest2() {
 //   onFailure : function(resp) {alert("There's been an error.");},
  new Ajax.Request(baseUrl + "AJAXISBNSearch.aspx", {
    onSuccess : function(resp) {UpdateImage2(resp);},
    parameters : "ISBN2=" + inputText
  });
}

function CollegesKeyPress() {
    college_name = $F('txtColleges');
    if ($F('txtColleges').length > 2) { 
		if (timerID != null) {window.clearTimeout(timerID);}
		timerID = window.setTimeout('CollegesRequest()', 300);  // waits a period of time without any keypresses before firing the ajax call
	}
}

function CollegesRequest() {
   new Ajax.Autocompleter('txtColleges', 'autocomplete_choices', baseUrl + 'AjaxDisplayCollegeNames.aspx', {paramName:'txtColleges',token:',',frequency:0.4,minChars:3,field: college_name}); 
   Field.focus('txtColleges');
}

function PopulateCollegesField(collegeID) {
  var objTemp = $("hdCollegeID");
	if (objTemp) { 
	  objTemp.value="0";
      objTemp.value=collegeID;
    }
}


function UpdateImage2(resp) {
	if (resp.responseText.length > 0) {
		var strReturn = resp.responseText.split("||");
		if ("*" == strReturn[0]) {
			$("divInvalidItem").innerHTML = strReturn[1];
			$("divLeftAJAXItem").hide();
			Effect.BlindDown("divInvalidItem", {duration:0.6});
		}
		else {
			$("imgLeftISBNMatch").src = sItemImagePath + strReturn[2];
			$("spanLeftTitleMatch").innerHTML = strReturn[0];
			$("spanLeftAuthorMatch").innerHTML = strReturn[1];
			Effect.BlindDown("divLeftAJAXItem", {duration:0.6});
			$("divInvalidItem").hide();
		}
	} else {
		$("divLeftAJAXItem").hide();
		$("divInvalidItem").hide();
	}
}

function ISBNKeyPress() {
    inputText = $F('txtISBNNo');
    inputText = inputText.replace(/\W+/g,"").replace(/[a-wA-Wy-zY-Z]/g,"").replace("_","");
    if (inputText.length > 9) { 
		if (timerID != null) {window.clearTimeout(timerID);}
		timerID = window.setTimeout('AJAXISBNRequest()', 400);  // waits a period of time without any keypresses before firing the ajax call
	}
}

function AJAXISBNRequest() {
 //   onFailure : function(resp) {alert("There's been an error.");},
  new Ajax.Request(baseUrl + "AJAXISBNSearch.aspx", {
    onSuccess : function(resp) {UpdateImage(resp);},
    parameters : "ISBN=" + inputText
  });
}

function UpdateImage(resp) {	
	if (resp.responseText.length > 0) {
		// need to hide error message caused by button click in case user typed in correct ISBN or ISBN with different reject code		
		var objTemp = $("UctrlSubMenu_divPageAlert");
		if (objTemp) { objTemp.hide(); }
		var strReturn = resp.responseText.split("||");
		if ("*" != strReturn[0]) {
			$("imgISBNMatch").src = sItemImagePath + strReturn[4];
			$("spanTitleMatch").innerHTML = strReturn[1];
			$("spanAuthorMatch").innerHTML = strReturn[2];
			//$("spanFormatType").innerHTML = strReturn[5];
			$("tblAJAXResult").show();
			
			//show high value message box
			if (strReturn[9] == 1){
				$('trHighValue').show();
			}

			//user entered valid ISBN/UPC, hide warnings
			$('imgUPC_ISBN_help').hide();
			$('divNumDigits').hide();
			objTemp = $('trBadUPCSelectMT');
			if (objTemp) {objTemp.hide();}
			$('divContactUs').hide();
			objTemp = $("imgNotAvailable")
			if (objTemp) { objTemp.hide(); };
			
			//show required fields that may have been hidden
			objTemp = $('trCondition')
			if (objTemp) {objTemp.show();}
			
			objTemp = $('trDescription')
			if (objTemp) {objTemp.show();}
			
			$('trButtons').show();

			objTemp = $("spanDVDWarning");
			if (objTemp) { objTemp.hide(); }
			if (strReturn[4].indexOf("/dvd") == 0) {
				if (objTemp) {
					objTemp.show(); 
					objTemp.innerHTML = DVDWarnMsg;
				}
			}
			else {
				if (objTemp) { objTemp.hide(); }
			}

			objTemp = $("divAddToTradeInvalidItem");
			if (objTemp) { objTemp.hide(); }
			
			objTemp = $("SingleItemDisplaySpacer"); 
			if (objTemp) { objTemp.hide(); };
			
		}
		else {
			objTemp = $("imgNotAvailable")
			if (objTemp) { objTemp.hide(); };

			objTemp = $("divAddToTradeInvalidItem");
			if (objTemp) { 
				objTemp.show();
				objTemp.innerHTML = strReturn[1];
			}
			objTemp = $("tblAJAXResult");
			if (objTemp) { objTemp.hide(); };
			objTemp = $("spanDVDWarning");
			if (objTemp) { objTemp.hide(); }
			objTemp = $("trHighValue");
			if (objTemp) { objTemp.hide(); }
			
		}
		/*
		var formatField = $("tdFormat")
		//Effect.BlindDown("tblAJAXResult", {duration:0.6});
		alert("strReturn[5] = " + strReturn[5]);
		switch (parseInt(strReturn[5]))
			{
			case 100: 
				alert("got here!");
				formatField.innerHTML = "<b>format:</b>&nbsp:&nbsp;hardcover<br>";
				//$("trFormat").show();
			default:
				formatField.hide();
			}
		*/
	} else {
		var objTemp = $("tblAJAXResult");
		if (objTemp) { objTemp.hide(); }
		objTemp = $("divAddToTradeInvalidItem");
		if (objTemp) { objTemp.hide(); }
		objTemp = $("SingleItemDisplaySpacer"); 
			if (objTemp) { objTemp.hide(); };
		objTemp = $("imgNotAvailable");
		if (objTemp) { objTemp.show(); }
		objTemp = $("trHighValue");
			if (objTemp) { objTemp.hide(); }
	}
}

function BadCDWarningDisplay(cmbConditionValue) {
	var objToShow = $("spanDVDWarning");
	// there are two controls to hold the item image: imgISBNMatch, which displays the image with the ajax code,
	// and imgItemImage, which is part of the single item user control, therefore I cannot call it by id, so I call it by tag name.
	// the trick is that I cannot check existence of tblAJAXResult (contains imgISBNMatch) or SingleItemDisplaySpacer (contains imgItemImage)
	// as they can appear together on the same page when we came from "have it" link, then user enters ISBN and imgItemImage is replaced by imgISBNMatch
	// therefore I check the existence of txtISBNNo, the alternative is spanISBN, which contains uneditable ISBN and dictates the existence of the single item user control.
	var objTemp = $("txtISBNNo");
	var blnImageExists=false;
	var blnShowMessage=false;
	var blnDVDMessage=false;
	var sInnerHtml='';
	CDWarnMsg = 'NOTE: to list a CD for trade, all tracks MUST be playable';
	if (objTemp) 
	{ 
		objTemp = $("imgISBNMatch");
		blnImageExists=true;
	} 
	else 
	{ 
		objTemp = $("SingleItemDisplaySpacer");
		if (objTemp) 
			{ 
				objTemp = objTemp.getElementsByTagName('img')[0]
				blnImageExists=true;
			
			}
	}
	if(blnImageExists==true) //if image exists then by it source determine media type
	{
		if (objTemp.src.indexOf("/music/") > 0) //show message for music media type
		{
			if (cmbConditionValue == 0) 
			{
				blnShowMessage=true;
			}
			else if(cmbConditionValue==3)
			{
				CDWarnMsg='NOTE: Use "like new" for CDs ONLY if the CD is in brand new condition, except that it has been opened.&nbsp;It should show NO signs of wear.<br><br>';
				blnShowMessage=true;
			}
			else if(cmbConditionValue==4)
			{
				CDWarnMsg='NOTE: Use "brand new" for CDs ONLY if the CD is new, unused, unopened and undamaged.<br><br>';
				blnShowMessage=true;
			}
		}
		else if (objTemp.src.indexOf("/dvd/") > 0)  //show message for dvd media type
		{
			blnDVDMessage=true;
			if(cmbConditionValue==3)
			{
				CDWarnMsg=DVDWarnMsg +  '&nbsp;Use "like new" for DVDs ONLY if the DVD is in brand new condition, except that it has been opened.&nbsp;It should show NO signs of wear.<br><br>';
				blnShowMessage=true;
			}
			else if(cmbConditionValue==4)
			{
				CDWarnMsg=DVDWarnMsg +  '&nbsp;Use "brand new" for DVDs ONLY if the DVD is new, unused, unopened and undamaged.<br><br>';
				blnShowMessage=true;
			}
		}
		else if (objTemp.src.indexOf("/Books/") > 0)  //show message for books media type
		{
			if(cmbConditionValue==4)
			{
				CDWarnMsg='NOTE: use "brand new" for books ONLY if the book is new and unread.<br><br>';
				blnShowMessage=true;
			}
			else if(cmbConditionValue==3)
			{
				CDWarnMsg='NOTE: Use "like new" for books ONLY if the book is in brand new condition, except that it has been read once.&nbsp;It should show NO signs of wear.<br><br>';
				blnShowMessage=true;
			}
		}
		else if (objTemp.src.indexOf("/vg/") > 0) //show message for vg media type
		{
			if(cmbConditionValue==4)
			{
				CDWarnMsg='NOTE: Use "brand new" for video games ONLY if the game is new, unused, unopened and undamaged.<br><br>';
				blnShowMessage=true;
			}
			else if(cmbConditionValue==3)
			{
				CDWarnMsg='NOTE: Use "like new" for video games ONLY if the game is in brand new condition, except that it has been opened.&nbsp;It should show NO signs of wear.<br><br>';
				blnShowMessage=true;
			}
		}
		if (blnShowMessage==true) //if any of prvious condition is true
		{
			objToShow.show(); 
			objToShow.innerHTML=CDWarnMsg;//show message
		}
		else //if we are not showing message them replace previous message  blank
		{
			if(blnDVDMessage==true)
			{
				objToShow.show(); 
				objToShow.innerHTML=DVDWarnMsg;
			}
			else
			{
				objToShow.hide();
			}
		}
	}		
};

function BadUPCSelectMT() {
	//check is for guests b/c condition fields will not be present	
	if($('trCondition'))
	{
	$('trCondition').hide();
	$('trDescription').hide();
	$('trButtons').hide();
	};	
	var sMediaType = $F('ddMediaType');		
	if(sMediaType == "1") {					//media type: books
		$('imgUPC_ISBN_help').src = '/images/isbn_book_help.jpg';	
		$('imgUPC_ISBN_help').show();		
		$('trEnterIsbnUPC').show();
		$('divNumDigits').show();
		$('divContactUs').show();
		$('spanWrongNumOfDigits').innerHTML = "make sure that you have entered a <b>10-digit or 13-digit</b> book ISBN (see image)";		
	} else if (sMediaType == "5") {			//media type: not selected
		$('imgUPC_ISBN_help').hide();
		$('trEnterIsbnUPC').hide();
		$('divNumDigits').hide();
		$('divContactUs').hide();
	} else {								//media type: CD, DVD, or VG
		$('imgUPC_ISBN_help').src = '/images/upc_NonBook_help.jpg';
		$('imgUPC_ISBN_help').show();
		$('divNumDigits').show();
		$('trEnterIsbnUPC').show();		
		$('divContactUs').show();
		$('spanWrongNumOfDigits').innerHTML = "make sure that you have entered a <b>12-digit</b> UPC (see image)";		
	}
	
}


//************************ RATING LOGIC **********************************

var hasRatingText=false;
var LoginMsg = "join now or login to save your rating";
var SuspMsg = "you cannot rate items because your account has been suspended";
var	DisableRollOver=false; //public variable to control rollover
var prevReviewText="";//keeps track of previous review text
var Score = Class.create();
var isclicked=false;

var itemReview = false;

function afterRatingCallback(resp){

	if(!(itemReview && hasRatingText) && g_TypeOfControl != 8)
		return;

	//reload page and jump to customer reviews section - includes timestamp variable for uniqueness if user resubmits review
	var currentLocation = window.location;
	var newLocation = "http://" + currentLocation.host + currentLocation.pathname;
	var d = new Date();
	var timestamp = Math.floor(d.getTime() / 1000);
	var fields = "";

	//we now want the page to reload when on reviews tab of a profile so we don't need the form values since there is no form

	if ($('__aspnetForm')){
		fields = Form.getElements("__aspnetForm");
	}

	if(currentLocation.search != ""){
		newLocation = newLocation + "?page=1";
	} 

	if(fields.length > 0){
		$('__aspnetForm').select('.cmbAvgRating')[0].value = 0
		document.__aspnetForm.action = newLocation + "#UserReviews";
		document.__aspnetForm.submit();
	}else{
		//reload current page
		window.location = currentLocation;
	}

}

Score.prototype = {
	initialize : function(id) {
    	this.id = id;
	}
};

Score.NONE = new Score(-1);

var Rating = Class.create();
Rating.prototype = {
	initialize : function(score) {
		this.score = score;
	}
};

var RatingManager = {
	ratings : new Array(),
	reviews : new Array(),
	findRatingScore : function(stid) {
		return this.ratings[stid];
	},
	findRatingReview : function(movie) {
		return this.reviews[stid];
	},
	saveRatingReviewAndScore : function(usertype, stid, rating, review, clickType, bPageReload) {
		this.reviews[stid] = review;
		this.ratings[stid] = rating;
		

		if (usertype=='a') {
			review = review.replace(/</g, "&lt;");
			review = review.replace(/>/g, "&gt;");
			
			var params = "rateAction=doRateScoreReview&rateitem="+stid+"&rateScore="+rating.score.id+"&review="+encodeURIComponent(review);
			var myAjaxRating

			if ((clickType=='starClick' && g_TypeOfControl != 8) || bPageReload == 'False'){
				myAjaxRating = new Ajax.Request(baseUrl + 'AJAXRating.aspx', { method: 'post', parameters: params});
			}else{
				myAjaxRating = new Ajax.Request(baseUrl + 'AJAXRating.aspx', { method: 'post', parameters: params, onSuccess: afterRatingCallback });
			}
			if (itemReview && clickType!='starClick' && (g_TypeOfControl == 3 || g_TypeOfControl == 8))
			{
				$("divReviewTextThanks").show();
			}
			if (clickType!='starClick' && (g_TypeOfControl == 3 || g_TypeOfControl == 8))
			{
				$("divReviewText").hide();
			}
		} else {
			if (usertype=='s')	{
				alert(SuspMsg);
			}
			else {
				alert(LoginMsg);
			}
		}
		
	},
	saveListRatingScore : function(usertype, listID, rating, clickType) {
		if (usertype=='a') {
			var params = "rateAction=doListRateScore&rateList="+listID+"&rateScore="+rating.score.id;
			var myAjaxRating = new Ajax.Request(baseUrl + 'AJAXRating.aspx', { method: 'post', parameters: params, onSuccess: afterRatingCallback });
		} else {
			if (usertype=='s')	{
				alert(SuspMsg);
			}
			else {
				alert(LoginMsg);
			}
		}		
	}
};


/*******************************************************************************
 RATING METHODS
 *******************************************************************************/
var doRate=false;
var RatingWidget = Class.create();
RatingWidget.prototype = {
		initialize : function(id, usertype, stid, rating) {
		this.id  = id;
		this.usertype = usertype;
		this.stid = stid;		
		this.rating = rating;
		isclicked=false;
		prevReviewText=""; //reinitialize previous review text
		
		if($("txtReviewRO")!=null)
		{
			prevReviewText=$("txtReviewRO").value;//assign value of textbox to previous text
			if (g_TypeOfControl!=3){
			$("imgSubmit").show();
			}
		}

		if (g_TypeOfControl == 3 || g_TypeOfControl == 8) // item review popup
		{
			itemReview=true;
			$("divReviewText").show();
		}	
	},
		
	handleStarHover:function(evt,noOffset) {
		var score = this.starMap(evt, noOffset);
		this.paintStars(score);
	},
		
	handleStarReset:function(evt) {
		var score = (this.rating == null || this.rating.score == null) ? Score.NONE : this.rating.score;
		this.paint(score);
	},
	
	handleStarClick:function(evt) {
		
			if ($('spanRatingErrorMsg-txtReviewRO') && $('spanRatingErrorMsg-txtReviewRO').visible()){
				$('spanRatingErrorMsg-txtReviewRO').hide();
			}
			//review
			DisableRollOver=true;
			var score = this.starMap(evt);
			
			if (!(this.rating != null && this.rating.score != null && this.rating.score.id == score.id))
			{
				this.rating = new Rating(score);
				doRate=true;
			}
			this.paint(this.rating.score);
			var reviewText = "";
			
			var objReviewText = $("txtReviewRO");
			if (!itemReview)
			{
				$("divReviewText").show();												
				
				if (objReviewText.value.length==0) {
					if(isclicked==false) {
						hasRatingText = false;
						objReviewText.value="You can type an optional text review here.";
						$("imgSubmit").hide();																
					}
				} else {
					if(isclicked==false) hasRatingText = true;
				}
			}
			else{
				hasRatingText = objReviewText.value.length > 0;
				reviewText = objReviewText.value;
			}										
				
		
		//if user gave rating then remove current balloon object from caching so that it can be refreshed next time user see item
		if(typeof(reviewBalloon)!='undefined')
			reviewBalloon.delFromCache("stid="+this.stid.id);
			
		isclicked=true;		
	},
	handleReviewStarClick:function(evt) {
		if ($('spanRatingErrorMsg-txtReview') && $('spanRatingErrorMsg-txtReview').visible()){
			$('spanRatingErrorMsg-txtReview').hide();
		}
		
		var score = this.starMap(evt, true);

		if (!(this.rating != null && this.rating.score != null && this.rating.score.id == score.id))
		{
			this.rating = new Rating(score);
			doRate=true;
		}
		this.paint(this.rating.score);
		var reviewText = "";			
	},
	//this function is used for the user list rating page
	handleListStarClick:function(evt) {
		var score = this.starMap(evt);
		
		if (!(this.rating != null && this.rating.score != null && this.rating.score.id == score.id))
		{
			this.rating = new Rating(score);
			doRate=true;
		}
		this.paint(this.rating.score);
				
		if (this.usertype=='a')	{
			$("spanListRatingSaved").show();
			$("tdUserRating").update("your rating:");
			$("trUserReview").show();
			var objReviewText = $("txtReviewRO");
				if (!itemReview)
				{										
					if (objReviewText.value.length==0) {
						if(isclicked==false) {
							hasRatingText = false;
							objReviewText.value="Comment about this list";																
						}
					} else {
						if(isclicked==false) hasRatingText = true;
					}
				}
				else{
					hasRatingText = objReviewText.value.length > 0;
					reviewText = objReviewText.value;
				}			
		}
		
		if(doRate==true) {
			RatingManager.saveListRatingScore(this.usertype, this.stid.id, this.rating, '', 'starClick');
		}
		
		isclicked=true;		
	},
	
	handleListStarClickBottom:function(evt) {
		var score = this.starMap(evt);
		
		if (!(this.rating != null && this.rating.score != null && this.rating.score.id == score.id))
		{
			this.rating = new Rating(score);
			doRate=true;
		}
		this.paint(this.rating.score);
		
		if (this.usertype=='a')	{
			$("spanRatingLabel").update("your rating:");
			$('txtListReview').setStyle({color:'#4d4d4d'});
			var objReviewText = $("txtListReview");
			if (!itemReview)
			{									
				if (objReviewText.value=='write a review on this list (optional)') {
					if(isclicked==false) {
						hasRatingText = false;							
						objReviewText.value="";																
					}
				} else {
					if(isclicked==false) hasRatingText = true;
				}
			}
			else{
				hasRatingText = objReviewText.value.length > 0;
				reviewText = objReviewText.value;
			}			
		}
		
		$$('input[name="txtScore"]')[0].value = score.id;
		isclicked=true;		
	},
	
	handlePaintOnlyClick:function(evt){
		var score = this.starMap(evt, true);
		if (!(this.rating != null && this.rating.score != null && this.rating.score.id == score.id))
		{
			this.rating = new Rating(score);
			doRate=true;
		}
		this.paint(this.rating.score);
		isclicked=true;	
		
		var txtBox = $$('input[name="txtScore"]')[0];
		if (txtBox != undefined){
			txtBox.value = score.id;
		}
	},
	
	clearLink:function() //function for clear rating
	{
		//when user submit button for review enable rollover again
		DisableRollOver=false;
		
		
		isclicked=false;
		if (this.usertype=='a')	{
			if (itemReview) {
				balloonPilot.hide();
			}
			else{
				$("divReviewText").hide();
			}
			$("txtReviewRO").value=prevReviewText;//assign previous review text to textbox
		} else {
			//if NOT looking at review popup on item details
			if (itemReview==false) {
				$("divReviewText").hide();
				//if user is not registered or user is suspended user then hide review text
				if (this.usertype=='s')	{
					alert(SuspMsg);
				}
				else {
					alert(LoginMsg);
				}
			}else {
				balloonPilot.hide();
			}
		}
		/*we don't want to change rating or review text while clicking on Cancel button*/
		/*****************************************************************************************************************/
		//this.rating.score = Score.NONE;
		//this.paintStars(this.rating.score);
		//RatingManager.saveRatingScore(this.usertype, this.stid.id, this.rating);
		//RatingManager.saveRatingReview(this.usertype, this.stid.id, '');
		//if user gave rating then remove current balloon object from caching so that it can be refreshed next time user see item
		if(typeof(reviewBalloon)!='undefined')
			reviewBalloon.delFromCache("stid="+this.stid.id);
		/*****************************************************************************************************************/
	},
	
	starMap:function(evt, noOffset) {
		var evt = evt || window.event;
		var offsets = Position.cumulativeOffset(Event.element(evt));
		var el = Event.element(evt);
		if(noOffset=="undefined"){
			noOffset = false
		}
		
		// get the relative mouse coordinates
		var x=0;
		if (evt.offsetX) { //This is for IE
			x = evt.offsetX;
		} else if (el.offsetX!=null) {
			var offX = el.offsetX;
			x = evt.layerX-offX;
		} else if (evt.layerX) {  // This is for FF
			// This explains the problem: https://bugzilla.mozilla.org/show_bug.cgi?id=122665
			// These two lines worked, but they required that we never change the DOM hierarchy
			// offX = el.offsetLeft + el.parentNode.offsetLeft;
			// x = evt.layerX-offX;			
			
			var offX = Position.cumulativeOffset(el)[0];  // this is the left from the edge of the screen			
			// glb_balloonLeft - this is distance from the edge of the screen to the edge of the balloon (layer) - it is coming from balloon.js
			// evt.layerX - this is the distance from the cursor to the edge of the balloon (layer)
			
			//this test is used for User List Star Ratings that we don't want a balloon offset added to it
			if (noOffset){			
				x = (evt.layerX) - offX;
			}else{
				x = (evt.layerX + glb_balloonLeft) - offX;
			}
		}

		//var x = - Event.pointerX(evt) - offsets[0];
		var score = new Score(-1);
		if (x < 8) {
			score.id = 6;
		} else if (x < 16) {
			score.id = 1;
		} else if (x < 24) {
			score.id = 7;
		} else if (x < 32) {
			score.id = 2;
		} else if (x < 40) {
			score.id = 8;
		} else if (x < 48) {
			score.id = 3;
		} else if (x < 56) {
			score.id = 9;
		} else if (x < 64) {
			score.id = 4;
		} else if (x < 72) {
			score.id = 10;
		} else if (x <= 81) {
			score.id = 5;
		}
		return score;
	},
		
	handleSaveReview : function(review, pageReload, displayType) { //function to save review text
		if (this.usertype=='s')	{
			alert(SuspMsg);
			return;
		}
			
		if (this.rating.score.id == 0){
			$('spanRatingErrorMsg-'+review).show();
			return;
		}
		
		var me = this;
		var sReview="";
		isclicked=false;
		//when user submit button for review enable rollover again
		DisableRollOver=false;
					
		if ($(review)!=null) {
			sReview=$(review).value;
			prevReviewText=sReview;//assign previous review text to text we currently saved to the database
			
			if (sReview == 'write a review for this item (optional)') sReview = '';		
		} else {
			return;
		}
		
		if(displayType == 'inline'){
			loginSubmit('recognize',
						true,
						function(){
							hasRatingText = true;
							RatingManager.saveRatingReviewAndScore(((me.usertype == 's')?'s':'a'), me.stid.id, me.rating, sReview, '', true);
							if(typeof(reviewBalloon)!='undefined')
								reviewBalloon.delFromCache("stid="+me.stid.id);
						}, 
						function(){ 							
							$('spanRatingErrorMsg-'+review).innerHTML = 'you must login to submit your review';
							$('spanRatingErrorMsg-'+review).show();
						});	
		} else {
			hasRatingText = true;
			RatingManager.saveRatingReviewAndScore(this.usertype, this.stid.id, this.rating, sReview, '', pageReload);
			if(typeof(reviewBalloon)!='undefined')
				reviewBalloon.delFromCache("stid="+this.stid.id);
		}
		
									
	},
	paint : function(score) {
		this.paintStars(score);
	},
	paintStars : function(score) {
		if ($(this.id) != null) {
			switch (score.id) {			
				case 6:  $(this.id).src = "/images/starRating_05.gif"; break;
				case 1:  $(this.id).src = "/images/starRating_10.gif"; break;
				case 7:  $(this.id).src = "/images/starRating_15.gif"; break;
				case 2:  $(this.id).src = "/images/starRating_20.gif"; break;
				case 8:  $(this.id).src = "/images/starRating_25.gif"; break;
				case 3:  $(this.id).src = "/images/starRating_30.gif"; break;
				case 9:  $(this.id).src = "/images/starRating_35.gif"; break;
				case 4:  $(this.id).src = "/images/starRating_40.gif"; break;
				case 10: $(this.id).src = "/images/starRating_45.gif"; break;
				case 5:  $(this.id).src = "/images/starRating_50.gif"; break;
				default: $(this.id).src = "/images/starRating_00.gif"; break;
			}
		}
	}
};

function CheckRatingText() {
	//if user clicks on texbox then disable rollover until submit or cancel button is not clicked
	DisableRollOver = true;
	if (itemReview==false)
	{
		if (!hasRatingText) {
			$("txtReviewRO").value="";
			hasRatingText=true;
		}
	}	
}

function CheckListRatingText() {
	if (itemReview==false)
	{
		if (!hasRatingText) {
			$("txtReviewRO").value="";
			hasRatingText=true;
		}
	}	
}

function friendComments(elem, username, useractionid,itemNumber,isReview, STID, firstFriend) {
	$("commentMsg").hide();
	$("friendCommentBox").show();		
	$("friendProfileLink").update("view " + username + "'s profile")
	$("friendProfileLink").writeAttribute("href", baseUrl + "user/" + username); 
	
	//for preloading first friend on item details
	if (elem != '0' && firstFriend != 'true') {
		var activeLinks = $("tdScrollContent").select('a[class="noFocus active"]');
		for(var i = 0; i < activeLinks.length; i++) {
			var value = activeLinks[i];
			$(value).removeClassName("active");
		}
		$(elem).addClassName("active");
	}
			
	//positioning for arrow that points to user image
	var startPosition
	if ($('scrollLeft') != null) {
		startPosition = 32;
	}else{
		startPosition = 17;
	}
	if (itemNumber >= 7) {itemNumber = (itemNumber - 7);}
	if ($('commentPointer')) {
		if (itemNumber > 0) {
			$('commentPointer').setStyle({marginLeft:(startPosition + (itemNumber * 78)) + 'px'});
		}else{
			$('commentPointer').setStyle({marginLeft: startPosition + 'px'});
		}
		document.getElementById("focus").focus();
	}
	
	//set review text or empty the div
	if (isReview == 'True') {
		getUserReview(username, STID);
	}else {
		$('divFriendReview').update(""); //clear contents rather than hide due to IE bug
		$('divFriendReview').setStyle({height:'1px'}); //clear contents rather than hide due to IE bug
		$('divCommentTypes').hide();
	}
			
	$('lnkSaveComment').stopObserving();
	$('lnkSaveComment').observe('click', function(event){ 
		var commentType = "action";
		var isPublic = 1;
		var optionList = $('divCommentTypes').select('input[type="radio"]');

		if(optionList.length == 2 && optionList[0].checked){
			if(this.actionId == 21){
				commentType = "user";				
			}
			isPublic = 0;
		}
	
		if ($('txtFriendComment').value == '' || $('txtFriendComment').value == 'write a comment...'){
			$('spanFriendCommentErrorMsg').show();
			return;
		}
		if ($('spanFriendCommentErrorMsg') && $('spanFriendCommentErrorMsg').visible()) {
			$('spanFriendCommentErrorMsg').hide();	
		}
	
		//userActionId, toUsername, commentType, comment, displayType, isPublic, showLogin, onSuccess, onFailure
		SwapComment.staticSaveComment(
			useractionid, 
			username,
			commentType,
			$('txtFriendComment').value, 
			'none',
			isPublic,
			true, 											
			function(response){ 
				$("friendCommentBox").hide();
				$("commentMsg").update("<div class='pageAlertTopCurvesFlexGreen'><div></div></div><div class='pageAlertCurvesFlexGreenInside'><img src='/images/alert_greencheck_sm.gif' width='11' height='10' alt='your comment has been sent' title='your message has been sent' class='icon'> your message has been sent</div><div class='pageAlertBottomCurvesFlexGreen'><div></div></div>");
				$("commentMsg").show();	
				$('txtFriendComment').value = 'write a comment...';						
			}, 
			function(response){
				$("friendCommentBox").hide(); 
				$("commentMsg").update("<div class='pageAlertTopCurvesFlexRed'><div></div></div><div class='pageAlertCurvesFlexRedInside'>We're sorry but your comment was not sent. Please try again or contact support@swaptree.com</div><div class='pageAlertBottomCurvesFlexRed'><div></div></div>");
				$("commentMsg").show();	
				$('txtFriendComment').value = 'write a comment...';		
			},
			function(){});
		});		
	}

	function getUserReview(sUsername, iSTID){
		new Ajax.Request(baseUrl + "AJAXGetUserItemReview.aspx", {
				onSuccess : function(resp) {$('divFriendReview').update(resp.responseText);$('divFriendReview').show();$('divFriendReview').setStyle({height:'auto'});},
				parameters : "username=" + sUsername + "&stid=" + iSTID
		});
	}


//************************ BALLOON LOGIC **********************************
var prevSTID=0;
var g_TypeOfControl='';
var glb_balloonLeft=0;
var g_activeSTID=0;

var Balloon = Class.create();
Balloon.prototype = {

	STATES : { DEFLATED : 0, INFLATING : 1, INFLATED : 2 },
	
	VERTICAL_POSITIONS : { UPPER : 0, LOWER : 1 },
	HORIZONTAL_POSITIONS : { LEFT : 0, RIGHT : 2 },
 
	state : 0,
	anchor : null,
	page : '',
	elements : { balloon : 'balloon', balloonArrow : 'balloonArrow', balloonArrowUL : 'balloonArrowUL', balloonArrowUR : 'balloonArrowUR', balloonArrowLL : 'balloonArrowLL', balloonArrowLR : 'balloonArrowLR' },

	initialize : function(url, anchor) {
		this.state = this.STATES.DEFLATED;
		this.url = url;
		this.anchor = anchor;
	},
	
	inflate : function() {
		this.state = this.STATES.INFLATING;
		params = this.url;
		page = this.page;
		new Ajax.Request(baseUrl + page, {parameters:params, onComplete:this.process.bind(this)});	
	},
	
	process : function(response) {
		this.state = this.STATES.INFLATED;
		this.html = response.responseText;
		balloonPilot.wake(this);
	},
	
	position : function() {
		// positions
		var balloonDimensions = Element.getDimensions(this.elements.balloon);
		var offsets = Position.cumulativeOffset(this.anchor);
		var deltas  = Position.Window.getDeltas();
		var windowDimensions = Position.Window.size();
		var anchorDimensions = Element.getDimensions(this.anchor);
		var quadrant = this.VERTICAL_POSITIONS.UPPER + this.HORIZONTAL_POSITIONS.LEFT;

		//logger.debug("balloon: " + balloonDimensions.width +":"+balloonDimensions.height + ", offsets: " + offsets + ", deltas: " + deltas.x + ":" + deltas.y + ", window: " + windowDimensions.width+":"+windowDimensions.height);
		
		// default baseline position
		var baseline = { x : offsets[0], y : offsets[1] - balloonDimensions.height/4 };
		var moveLeft = 0;
		var moveTop = -17;
		var moveTopLowerQuad = 0;

	    switch(parseInt(g_TypeOfControl)) {
			case 0:  //ImageRollover
				moveLeft = 35; 
				break;
				//alert("ImageRollover");
			case 1: //TextRolloverShowImg 
	
			case 2: //TextRolloverNoImg
				// code for case 1 AND case 2, b/c there's no break in case 1
				moveLeft = 0;
				moveTopLowerQuad = - 60;  //to fix problems at bottom of screen
				break;
			case 3: //Item Review
				moveTopLowerQuad = - 60;  //to fix problems at bottom of screen	
				// had to preset height of balloon since the height is determined before the javscript has a chance to
				// show and hide the necessary fields and elements for this display
				balloonDimensions.height = 254;	
						
	    }

		// setTop		
		var top = baseline.y;
		if (baseline.y + balloonDimensions.height > windowDimensions.height + deltas.y) {
			top = windowDimensions.height + deltas.y - balloonDimensions.height;
			quadrant += this.VERTICAL_POSITIONS.LOWER;
		}  else if (baseline.y < deltas.y) {
			top = deltas.y;
		}

		$(this.elements.balloon).style.top = "" + top + "px";
		
		// setLeft
		var left = baseline.x + anchorDimensions.width + 20;
		if (baseline.x + anchorDimensions.width > windowDimensions.width/2) {
			left = offsets[0] - 300 - 20;
			quadrant += this.HORIZONTAL_POSITIONS.RIGHT;
		}
		$(this.elements.balloon).style.left = left+"px";
			
		glb_balloonLeft = left;		
		
		// setArrow
		var arrowTop = 0;
		switch(quadrant) {
			case 0:
				$(this.elements.balloonArrow).style.left = left - 15 + "px";
				arrowTop = offsets[1] + moveTop; //change this to change the location of the arrow tip
				Element.show(this.elements.balloonArrowUL);
				break;
			case 1:
				$(this.elements.balloonArrow).style.left = left - 15 + "px";
				arrowTop = offsets[1] + moveTop;
				Element.show(this.elements.balloonArrowLL);
				break;
			case 2:
				$(this.elements.balloonArrow).style.left = left + 292 + "px";
				arrowTop = offsets[1] + moveTop;
				Element.show(this.elements.balloonArrowUR);
				break;
			case 3:
				$(this.elements.balloonArrow).style.left = left + 292 + "px";
				arrowTop = offsets[1] + moveTop;
				Element.show(this.elements.balloonArrowLR);
				break;
		}
			
		if (arrowTop + 45 > windowDimensions.height + deltas.y) {
			arrowTop = windowDimensions.height + deltas.y - 56;
		} else if (arrowTop < deltas.y || (arrowTop - deltas.y) < 10) {
			arrowTop = deltas.y + 12;
		}

		$(this.elements.balloonArrow).style.top = arrowTop + "px";
		
	},
	
	paint : function() {
		$('popupdata').update(this.html);
		Effect.Appear(this.elements.balloon, {duration:0.5});	
		Effect.Appear(this.elements.balloonArrow, {duration:0.5});	
		this.position();
	},
	
	hide : function() {
		Element.hide(this.elements.balloon);
		Element.hide(this.elements.balloonArrow);	
		Element.hide(this.elements.balloonArrowUR);
		Element.hide(this.elements.balloonArrowUL);
		Element.hide(this.elements.balloonArrowLR);
		Element.hide(this.elements.balloonArrowLL);
	}
};

var balloonPilot = {

	cache : new Array(),
	
	requested : null,
	pending : null,
	hiding : null,
	findOrAdd : function(url, node, page) {
		for (i=0;i<this.cache.length;i++) {
			if (url == this.cache[i].url) {
				this.cache[i].anchor = node;
				return this.cache[i];
			}
		}
		var balloon = new Balloon(url);
		balloon.anchor = node;
		balloon.page = page;
		this.cache.push(balloon);
		return balloon;
	},

	show : function(node, url, page) {

		if (g_pageLoaded == 0){
			//alert('notloaded');
			return;
		}
		this.requested = this.findOrAdd(url, node, page);
		
		//get the type of control value out of the url. If it is 3 then its the Item Review balloon that requires no delay.
		//var controlTypePosition = url.indexOf("typeofcontrol=");		
		//var controlType = url.substring(controlTypePosition + 14);
		var timeOut
		if (g_TypeOfControl == 3 || g_TypeOfControl == 8)
		{
			timeOut = 5;
		}
		else if (page == 'AJAXUserProfile.aspx')
		{
			timeOut = 5;
		}
		else
		{
			timeOut = 1000;
		}
	
		
		
		
		switch (this.requested.state) {
			case this.requested.STATES.DEFLATED: 
				//this controls the speed in which the balloon appears - default is 1400
				this.pending = setTimeout(this.requested.inflate.bind(this.requested), timeOut);
				break;
			case this.requested.STATES.INFLATING:
				break;
			case this.requested.STATES.INFLATED:
				this.pending = setTimeout(this.requested.paint.bind(this.requested), timeOut);
				break;				
		}
	},
	
	wake : function(balloon) {
		if (balloon == this.requested) {
			balloon.paint(balloon.anchor);
		}
	},

	hide : function() {
		prevSTID=0;
		if (this.requested != null) {
			this.requested.hide();
			this.requested = null;	
		}
		if (this.pending != null) {
			clearTimeout(this.pending);
			this.pending = null;
		}
		

	},
	delFromCache :function(url)	{
		for (i=0;i<this.cache.length;i++) {
			if (this.cache[i].url && this.cache[i].url.indexOf(url)>0) {
				this.cache.splice(i,1,"");
			}
		}		
	}


};
var movieBalloon = {
	show : function(event, stId, mediaType,wantList,haveList,getNow,typeOfControl,isbn) {
		if(DisableRollOver==true) {
			return;
		}
		//
		if (balloonPilot.hiding!=null) {  
			window.clearTimeout(balloonPilot.hiding);
			balloonPilot.hiding=null;
		}
		if(prevSTID==stId) {
			return true;	
		}
		this.hide('');
		var node = Event.element(event);
		prevSTID=stId;

		g_TypeOfControl=typeOfControl; 
		var url  = "ItemRollOver=&stid="+stId+"&mediaType="+mediaType + "&showWantList="+wantList + "&showHaveList="+ haveList + "&showGetNow="+getNow + "&typeofcontrol="+typeOfControl;
		if(isbn != null){
			url += "&isbn=" + isbn;
		}
		
		balloonPilot.show(node, url, 'AJAXItemDetail.aspx');
	},
	
	hide : function(strOption) {
		if(DisableRollOver==true) {
			return;
		}
		//
		if (balloonPilot.hiding!=null) {  
			window.clearTimeout(balloonPilot.hiding);
			balloonPilot.hiding=null;
		}
		if(strOption=='max') {
			//put more delay on link for which popup to be shown
			balloonPilot.hiding=window.setTimeout(function(){balloonPilot.hide();}, 1000);
		} else if(strOption=='med') {
			//put delay but execute faster
			balloonPilot.hiding=window.setTimeout(function(){balloonPilot.hide();}, 400);
			//hides the rate label
			if (g_TypeOfControl == 3 || g_TypeOfControl == 8){
				//$('rateReviewLabel-' + g_activeSTID).hide();
				hideRateReview(g_activeSTID);
			}					
			
		} else {
			balloonPilot.hide();
		}
		
		
	},
	
	dontHide : function() {
		//disable rollover
		if(DisableRollOver==true) {
			return;
		}
		if (balloonPilot.hiding!=null) {
			window.clearTimeout(balloonPilot.hiding);
			balloonPilot.hiding=null;
		}
		if (g_TypeOfControl == 3 || g_TypeOfControl == 8){
			//$('rateReviewLabel-' + g_activeSTID).show();
			showRateReview(g_activeSTID);
		}
	},
	
	delFromCache : function(stId) {
		balloonPilot.delFromCache(stId);
	}
};

var userBalloon = {

	show : function(event, userId, userName) {
		this.hide();
		var node = Event.element(event);
		var url  = "viewUserBalloon=&userId="+userId+"&userName="+userName;	
		balloonPilot.show(node, url, 'AJAXUserProfile.aspx');	
	},
	
	hide : function() {
		balloonPilot.hide();
	}
};

var reviewBalloon = {
	show : function(event, stId, mediaType,typeOfControl, elem, actionId){
		if(DisableRollOver==true) {
			return;
		}
		this.hide();
		var node = Event.element(event);
		g_activeSTID=stId;
		g_TypeOfControl=typeOfControl; 
		var url  = "ItemReviewRollOver=&stid="+stId+"&mediaType="+mediaType + "&typeofcontrol="+typeOfControl;
		var label = "rateReviewLabel-" + stId + (actionId == undefined ?'': '-' + actionId);
		$(label).show();
		balloonPilot.show(node, url, 'AJAXItemDetail.aspx');
	},
	// not used since we the balloon container code is reused for all type of balloons, 
	// therefore we are forced to use the movieBalloon.hide for all types
	hide : function(strOption, elem) {
		//disable rollover
		if(DisableRollOver==true) {
			return;
		}
		//
		if (balloonPilot.hiding!=null) {  
			window.clearTimeout(balloonPilot.hiding);
			balloonPilot.hiding=null;
		}			
		if(strOption=='max') {
			//put more delay on link for which popup to be shown
			balloonPilot.hiding=window.setTimeout(function(){balloonPilot.hide();}, 1000);
		} else if(strOption=='med') {
			//put delay but execute faster
			balloonPilot.hiding=window.setTimeout(function(){balloonPilot.hide();}, 400);
			
		} else {
			balloonPilot.hide();
		}		
	},
	
	dontHide : function() {
		//disable rollover
		if(DisableRollOver==true) {
			return;
		}
		if (balloonPilot.hiding!=null) {
			window.clearTimeout(balloonPilot.hiding);
			balloonPilot.hiding=null;
		}
	},
	
	delFromCache : function(stId) {
		balloonPilot.delFromCache(stId);
	}
};


var actorBalloon = {

	show : function(event, actorId) {
		this.hide();
		var node = Event.element(event);
		var url  = "viewActorBalloon=&actorId="+actorId;
		balloonPilot.show(node, url);
	},
	
	hide : function() {
		balloonPilot.hide();
	}
};


/*------------PROTOTYPE EXTENSIONS---------------------*/
Position.Window = {
    getDeltas: function() {
        var deltaX =  window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
        var deltaY =  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
        return { x : deltaX, y : deltaY };
    },
    size: function() {
        var winWidth, winHeight, d=document;
        if (typeof window.innerWidth!='undefined') {
            winWidth = window.innerWidth;
            winHeight = window.innerHeight;
        } else {
            if (d.documentElement && typeof d.documentElement.clientWidth!='undefined' && d.documentElement.clientWidth!=0) {
                winWidth = d.documentElement.clientWidth
                winHeight = d.documentElement.clientHeight
            } else {
                if (d.body && typeof d.body.clientWidth!='undefined') {
                    winWidth = d.body.clientWidth
                    winHeight = d.body.clientHeight
                }
            }
        }
        return {width : winWidth, height : winHeight};
    }
};

//************************ MAILTO LOGIC **********************************
// Function safeMail is a function whose sole purpose is to obscure the mailto href to make it more difficult
// for those who wish to harvest email addresses from our web pages.  The at sign and period in email addresses passed
// to this function will ordinarily be represented by their html escape codes further obscuring the fact that they are 
// email addresses when evaluated by harvesting agents.

	function safeMail(Address) {
		window.location.href = 'mailto: ' + Address;
	}


/**********************LightView******************************************/

	function openLightView(sURL, iWidth, iHeight, sTitle, sCaption, sType, sMenubar){
		if (sMenubar != false){ 
			sMenubar = 'top';
		}
		if (document.observe('lightview:loaded')){
			Lightview.show({ href: sURL, rel: ((sType==null)?'iframe':sType), title: sTitle, caption: sCaption, options: { width: iWidth, height: iHeight, overlayClose: false, autosize: true, menubar: sMenubar}});
		}
	}
	
	function hideLightView(){
		Lightview.hide();
	}
	
	function hideLightViewAndRedirect(sRedirect){
		location.href = sRedirect;
		Lightview.hide();
	}
	
	function hideLightViewAndReload(){
		Lightview.hide();
		location.reload(true);
	}
	
/********************** Twitter ******************************************/
	function countChars(controlToValidateRef, maxLength, outputControlRef) {
		var countString = maxLength - controlToValidateRef.value.length;
		if (countString < 0) {
			outputControlRef.style.color = "red";
		} else {
			outputControlRef.style.color = "#CCCCCC";
		}
		outputControlRef.value = countString;
	}
	
	function openTwitter(sURL, qsValues, forceLogin, sSecureUrl, sBaseUrl){
		if(forceLogin){
			sURL += qsValues + "&forceLogin=1"
			openTwitterInLightView(sURL, false, sSecureUrl, sBaseUrl);
		}else{
			var sTradeID = '';
			var iPosTradeID = qsValues.indexOf('&dtradeid=');
			
			if(iPosTradeID > -1){
				sTradeID = qsValues.substr(iPosTradeID + 10);
			}
			
			new Ajax.Request(baseUrl + 'AjaxGetUserPlatformInfo.aspx', {
				method: 'get',
				onSuccess: function(transport) {
					var result = transport.responseText;
					var iColon = result.indexOf(':');
					var code = result.substr(0, iColon);
					var message = result.substr(iColon + 1);
					switch(code){
						case '-1':
							//Show error message
							//alert(message);
							break;
						case '-2':
							//GUEST OR VISITOR so go to join
							location.href = message;
							break;
						case '-3':
							//Recognized, but not logged in, so show login screen
							location.href = message;
							break;
						case '0':
						case '1':
							var bHasAccount = (code == '1');
							sURL += "?ST=1" + qsValues + message;
							openTwitterInLightView(sURL, bHasAccount, sSecureUrl, sBaseUrl);
							break;
						default:
							//don't show alerts
							//alert('error');
							break;
					}
				},
				parameters: { 
					"PlatformType": 2, 
					"Location": location.href,
					"dTradeID": ((sTradeID == null) ? '' : sTradeID)
				}
			});
		}
	}
	
	// should not be called except by openTwitter
	function openTwitterInLightView(sURL, bHasAccount, sSecureUrl, sBaseUrl){
		var sTitle = 'sharing with <img src="/images/logo_twitter.gif" alt="twitter" title="twitter" style="vertical-align:text-bottom;">';
		var sCaption = '';
		var iWidth = 400;
		var iHeight = 380;

		if (bHasAccount){
			iHeight = 250;
			
			sURL = sBaseUrl + sURL;
		}
		else{
			sURL = sSecureUrl + sURL;
		}
		
		//alert(sURL);
		openLightView(sURL, iWidth, iHeight, sTitle, sCaption);
	}
	
	var setupFacebookCalled = false;
	
	function setupFacebook(apiKey, xdLocation){
		if(!setupFacebookCalled)
		{
			setupFacebookCalled = true;
			FB_RequireFeatures(["XFBML"], function()
			{
				FB.Facebook.init(apiKey, xdLocation);
				
				if(typeof afterSetupFacebook=='function'){
					afterSetupFacebook();
				}
			});
		}else{
			if(typeof afterSetupFacebook=='function'){
				afterSetupFacebook();
			}
		}
	}

	function openFacebookInLightView(sURL, qsValues){
		var sTradeID = '';
		var iPosTradeID = qsValues.indexOf('&dtradeid=');
		
		if(iPosTradeID > -1){
			sTradeID = qsValues.substr(iPosTradeID + 10);
		}
			
		new Ajax.Request(baseUrl + 'AjaxGetUserPlatformInfo.aspx', {
			method: 'get',
			onSuccess: function(transport) {
				var result = transport.responseText;
				var iColon = result.indexOf(':');
				var code = result.substr(0, iColon);
				var message = result.substr(iColon + 1);
				switch(code){
					case '-1':
						//Show error message
						//alert(message);
						break;
					case '-2':
						//GUEST OR VISITOR so go to join
						location.href = message;
						break;
					case '-3':
						//Recognized, but not logged in, so show login screen
						location.href = message;
						break;
					case '0':
					case '1':
						var bHasAccount = (code == '1'); //irrelevant for FBC
						
						var sTitle = 'sharing with <img src="/images/logo_facebook.gif" alt="facebook" title="facebook" style="vertical-align:text-bottom;">';
						var sCaption = '';
						var iWidth = 645;
						var iHeight = 435; //430 is enough for firefox but IE requires 435

						sURL = sURL + "?ST=1" + qsValues

						//alert(sURL);
						openLightView(sURL, iWidth, iHeight, sTitle, sCaption);
						
						break;
					default:
						//alert('error : '  + result);
						break;
				}
			},
			parameters: { 
				"PlatformType": 1, 
				"Location": location.href,
				"dTradeID": ((sTradeID == null) ? '' : sTradeID)
			}
		});
	}

	function attemptToSendToFacebook(user_message_prompt, user_message_text, template_data, template_id){
		var callback = function(){postToFB(user_message_prompt, user_message_text, template_data, template_id);};
		FB.ensureInit(function() {
			FB.Connect.ifUserConnected(callback, function(){ loginThenActionToFB(callback) });
		});
	}
	
	function postToFB(user_message_prompt, user_message_text, template_data, template_id, pu_window){
		var user_message = {value: user_message_text};
		FB.Connect.showFeedDialog(template_id, template_data, null, null, null, FB.RequireConnect.promptConnect, function() { location.href += '&ClosePopup=1&Message=' + user_message.value }, user_message_prompt, user_message);
	}
	
	function loginThenActionToFB(callback){
		FB.ensureInit(function() {
			FB.Connect.requireSession(callback);
		});
	}

	function addParamToLocation(paramNameAndValue){
		var loc = location.href;
		if(loc.indexOf(paramNameAndValue) == -1){
			var qsMarker = '?';

			if(loc.indexOf('?') > -1){
				qsMarker = '&';
			}
			
			loc += qsMarker + paramNameAndValue;
		}
		return loc;
	}
	
	function logoutAndDestroy(){
		var loc = addParamToLocation('ForceFBCLogout=1');
		
		FB.Connect.logoutAndRedirect(loc);
	}
	
	function switchFacebookUser(){
		FB.ensureInit(function() {
			FB.Connect.ifUserConnected( function(){ FB.Connect.logout(doUnloggedLogin); }, doUnloggedLogin );
		});
	}

	function doUnloggedLogin(callback){
		loginThenActionToFB(function(){
			FB.ensureInit(function() {
				FB.Connect.ifUserConnected(function(){
					if(callback != null){
						callback();
					}else{
						location.reload(true);
					}
				}, null);
			})
		});
	}
	
	function doLoggedLogin(callback){
		loginThenActionToFB( function(){
			FB.ensureInit(function() {
				FB.Connect.ifUserConnected( function(){ 
					var api = FB.Facebook.apiClient;
					var session = api.get_session();
					if(session == null){
						doLoggedLogin(callback);
						return;
					}
					var platformLogin = session.uid;
					//alert('before update');
					new Ajax.Request(baseUrl + 'AjaxUpdateUserPlatformInfo.aspx', {
						method: 'get',
						onSuccess: function(transport) {
							var result = transport.responseText;
							//alert('after update: ' + result);

							if(callback != null){
								callback();
							}else{
								location.reload(true);
							}
						},
						parameters: { 
							"PlatformType": '1', 
							"PlatformLogin": platformLogin
						}
					});
											
				}, null );
			});
		});		
	}
	
	//this method is currently defined for trade login scenarios, but can be redefined as necessary on the page level
	function doFBCLoginThenPost(postBackCall){
		doTradeLogin(false, postBackCall);
	}
	
	function doTradeLogin(isSecondTry, postBackCall){
		FB.ensureInit(function() {
			var api = FB.Facebook.apiClient;
			var session = api.get_session();
			if(session == null){
				if(isSecondTry){
					//if this is the second try and it still can't get the session uid, call requiresession
					loginThenActionToFB( function(){ doTradeLogin(false, postBackCall); } );
					return;
				}else{
					doTradeLogin(true, postBackCall);
					return;
				}
			}else{
				FB.Connect.ifUserConnected( 
					function(){
						var api = FB.Facebook.apiClient;
						var session = api.get_session();
						var platformLogin = session.uid;

						new Ajax.Request(baseUrl + 'AjaxGetUserPlatformInfo.aspx', {
							method: 'get',
							onSuccess: function(transport) {
								var result = transport.responseText;
								var iColon = result.indexOf(':');
								var code = result.substr(0, iColon);
								var message = result.substr(iColon + 1);
								switch(code){
									case '-4':
										//not login-linked
										//alert(result);
										location.href = message;
										break;
									case '0':
										location.href = message;
										break;
									case '1':
										postBackCall();
										break;
									default:
										//alert(result);
										break;
								}
							},
							parameters: { 
								"PlatformType": 1, 
								"PlatformLogin": platformLogin,
								"LoginIfFailed": 1
							}
						});
					},
					function(){
						loginThenActionToFB( function(){ doTradeLogin(false, postBackCall); } );
					}
				)
			}
		});
	}

	function doFbInviteLogin(){
		doUnloggedLogin(
			function(){
				//the output is irrelevant
				location.href = addParamToLocation('mode=fb');
			});
	}
	
	function doFbRegisterLogin(isSecondTry, page, afterLogin){
		doUnloggedLogin(function(){
			FB.Facebook.get_sessionState().waitUntilReady(function(){
				var api = FB.Facebook.apiClient;
				var session = api.get_session();
				var platformLogin = session.uid;
				FbRegisterLoginSecondStep(platformLogin, page, afterLogin);
			});

		});
	}
	
	function FbRegisterLoginSecondStep(platformLogin, page, afterLogin){
		FB.ensureInit(function() {
			FB.Connect.ifUserConnected( function(){ 
				//do ajax look up
				new Ajax.Request(baseUrl + 'AjaxGetUserPlatformInfo.aspx', {
					method: 'get',
					onSuccess: function(transport) {
						var result = transport.responseText;
						var iColon = result.indexOf(':');
						var code = result.substr(0, iColon);
						var message = result.substr(iColon + 1);
						switch(code){
							case '-4':
								//not login-linked
								//alert(message);
								eval(message);
								break;
							case '0':
							case '1':
								//alert(message);
								if(page == 'popup'){
									parent.location.reload(true);
								}else{
									parent.location.href = message;
								}
								break;
							default:
								//alert('error ' + result);
								break;
						}
					},
					parameters: { 
						"PlatformType": 1, 
						"PlatformLogin": platformLogin,
						"From": 'popup',
						"AfterLogin": afterLogin
					}
				});
				//end ajax lookup
			}, null );
		});
	}
	
/********************** Find Friends Tabbed toolbar ******************************************/

	var currentActiveFriendTab = "fbc_pane";
	function ActivateTabSection(activeTab, tabGroupName)
	{
		//set tab bar background to on
		$('findFriendsTabs').className = "friendsTabsActive";

		//show the panes in case we were showing the compact bar
		if ($('divPanes').visible() == false) $('divPanes').show();
		
		var lastActiveFriendTab = currentActiveFriendTab
		currentActiveFriendTab = activeTab;
		
		//set tabs to correct on/off states
		var list = $(tabGroupName);
		var listItems = list.getElementsByTagName("a");
		//loop through each list item link and change their classes
		for (i=0; i<listItems.length; i++){
			if(listItems[i].parentNode.className.split("_")[0] + "_pane" == activeTab){
				listItems[i].className = "activeTab";
				}
			else{
				listItems[i].className = "inactiveTab";
			}
		}
		//hide previous active pand and show new active pane
		$(lastActiveFriendTab).hide();
		$(currentActiveFriendTab).show();
		
		//reset friends container width
		if ($('findFriends')) {$('findFriends').className='friendsContainer';}
		
    }
    
    function setWidePane(){
		
		if ($('emailHarvest_pane').visible()){
			if ($('frmMultiEmailImport') && frmMultiEmailImport.showWidePane == 'true') {
				$('frmMultiEmailImport').width='840px';
				$('frmMultiEmailImport').height='440px';
				$('findFriends').className='friendsContainerWide';
				$('findFriendsTabs').className='friendsTabsWideActive';
				$('emailHarvest_pane').firstDescendant().className='grnRoundedBoxWide';
			} else if ($('emailHarvest_pane').visible() && $('frmMultiEmailImport')&& frmMultiEmailImport.showWidePane == 'false') {
				$('frmMultiEmailImport').height='615px';
			}
		} else if ($('outlook_pane').visible()){
			if ($('frmOutlookImport') && frmOutlookImport.showWidePane == 'true') {
				$('frmOutlookImport').width='840px';
				$('frmOutlookImport').height='440px';
				$('findFriends').className='friendsContainerWide';
				$('findFriendsTabs').className='friendsTabsWideActive';
				$('outlook_pane').firstDescendant().className='grnRoundedBoxWide';
			} else if ($('outlook_pane').visible() && $('frmOutlookImport')&& frmOutlookImport.showWidePane == 'false') {
				$('frmOutlookImport').height='615px';
			}			
		}
      }
      function resetIframeTabSizeOnly(){
		parent.$('frmMultiEmailImport').height='215px';
		parent.$('frmOutlookImport').height='215px';
	}
	
	function sendFriendRequest(userId, username){
		new Ajax.Request(baseUrl + "AJAXSendFriendRequest.aspx", {
			onSuccess : function(resp) {var user = username; friendRequestSubmitted(resp, user);},
			parameters : "userid=" + userId + "&comments=" + escape($('txtFriendMessage').value.replace("enter a message to this user ...", ""))
		});
	}

	function friendRequestSubmitted(response, username){
		if(response.responseText == 'success'){
			$('divRespMessage').innerHTML = "<br><span class='pageAlertTextColorGreen'><img src='/images/alert_greencheck.gif' height='16' width='16' style='float:left;margin:0 5px 10px 0;'> " + username + " has been sent a friend request</span>";
			$('divForm').hide();
			if ($('divFriendRequestLink')) {$('divFriendRequestLink').innerHTML = "<span class='requestPendingBox'>friend request pending</span>";}
						
		} else {
			$('divRespMessage').innerHTML = "<br><span class='pageAlertTextColorRed'>an error occured while sending your friend request. please try again later.</span>";
			$('divForm').hide();
		}
	}
	
/********************** Activity Feed Comment Box ******************************************/

	function getAllUserActionItems(userActionId, stids){
		if ($('divItems' + userActionId).visible()){
			Effect.BlindUp($('divItems' + userActionId), {duration:0.6});
			return;
		}
		new Ajax.Request(baseUrl + 'AJAXGetAllUserActionItems.aspx', 
						{ method: 'post', 
							onSuccess : function(resp) { if(resp.responseText != "") { $('divItems' + userActionId).innerHTML = resp.responseText; Effect.BlindDown($('divItems' + userActionId), {duration:0.6}); } },
							parameters : "stids=" + stids + "&cb=" + Math.random()
						});
	}
		
	function getAdditionalInfo(userActionId, itemId, type){
		new Ajax.Request(baseUrl + 'AJAXGetActionAdditionalInfo.aspx', 
			{ method: 'post', 
				onSuccess : function(resp) { 
								if(resp.responseText != "") { 
									$('divItemText'+userActionId).innerHTML = resp.responseText; 
								}
							},
				parameters : "type=" + type + "&itemId=" + itemId + "&cb=" + Math.random()
			});
	}
	
	function secureAjaxRequest(obj, page, params, showLogin, loginMsg, onSuccess, onFailure){
		new Ajax.Request(baseUrl + page, 
			{	method: 'post', 
				onSuccess : function(response) { 								
								if(response.responseText.replace(/^\s+|\s+$/g,"") == 'login'){
									if(showLogin){
										document.observe('lightview:hidden', function(event) {
											secureAjaxRequest(obj, page, params, false, loginMsg, onSuccess, onFailure);
										});
										openLightView(baseUrl + 'WebFrmSecureLogin.aspx?OnlyHide=1', 274, 260, "member login", loginMsg);
									} else {
										document.stopObserving('lightview:hidden');
									}
								}	
								else if(response.responseText != "failed") {
									document.stopObserving('lightview:hidden');
									onSuccess(params, response.responseText, obj);								
								} else {
									document.stopObserving('lightview:hidden');
									onFailure(params);
								}
							},
				parameters : params + "&cb=" + Math.random()
			});
	}
	
	function onShowMoreFeedSuccess(params, responseText, eventObject){
		if(responseText == ''){
			$('FriendFeedList').insert("No more activities");
			return;
		}
		
		var feedType = params.match(/ftype=([a-zA-Z]+)&/i);
		var display = (feedType[1] == 'comment') ? 'dynamicRolledUp' : 'dynamic';
		
		var activities = new Element("div").update(responseText);
		activities.hide();
		$('FriendFeedList').insert(activities);
		
		SwapComment.bindOnClick(activities, {displayType: display});
		
		activities.show();							 
		eventObject.up(0).hide();
	}
	
	function onShowMoreFeedFailure(params){
		$('FriendFeedList').insert("an error occured while getting more activities. please try again later.");
	}
			
	/********************** Rate/Review Rollover *************************************/
	
	// need logic so the rate review forces login at some point
	var isLabelVisible = false;
	var label;
	var labelTimer;
	
	function showRateReview(stid,actionId){
		clearTimeout(labelTimer);
		if (isLabelVisible){
			return;
			}
		isLabelVisible = true;
		var label = "rateReviewLabel-" + stid + (actionId == undefined ?'': '-' + actionId);
				
		labelTimer = setTimeout(function(){hideActiveLabels();$(label).setStyle({display:'block',marginTop:'-18px'});$(label).show();$(label).addClassName('activeLabel');}, 600);
			
	}
	function hideRateReview(stid,actionId){
		var label = "rateReviewLabel-" + stid + (actionId == undefined ?'': '-' + actionId);
		if ($(label)){
			clearTimeout(labelTimer);
			labelTimer = setTimeout(function(){$(label).hide();}, 100);
			isLabelVisible = false;		
		}
	}
	
	function hideActiveLabels(){
		var activeLabels = $$('div.activeLabel');
			
		if (activeLabels && activeLabels.length > 0){
			for (i=0;i<=activeLabels.length - 1;i++)
			{
				$(activeLabels[i]).hide();		
			}
		}
	}
		
	/********************** User Scroller ******************************************/
	
Scroller = Class.create({
initialize: function(box, innerBox, el_left, el_right, step) {
var scroller = this;

this.box = $(box);
this.handle = $(innerBox);
this.el_left = $(el_left);
this.el_right = $(el_right);
this.step = step;
this.currentOffsetLeft = 0;

this.eventLeftScrollOnClick = this.ScrollLeft.bindAsEventListener(this);
this.eventRightScrollOnClick = this.ScrollRight.bindAsEventListener(this);

this.el_left.observe("click", this.eventLeftScrollOnClick);
this.el_right.observe("click", this.eventRightScrollOnClick);

this.initialized = true;
},
ScrollLeft: function(event){

offset_left = this.currentOffsetLeft

if(!offset_left || offset_left>= 0)
return;

this.currentOffsetLeft += this.step;
new Effect.Move(this.handle, { x: this.step, y: 0, transition: Effect.Transitions.sinoidal, queue: 'end'});
Event.stop(event);

},
ScrollRight: function(event){

box_width = this.getObjStyleProperty(this.box, 'width');
innerBox_width = this.getObjStyleProperty(this.handle, 'width');

if(box_width>=(this.currentOffsetLeft)+innerBox_width)
return;

this.currentOffsetLeft -= this.step;
new Effect.Move(this.handle, { x: -this.step, y: 0, transition: Effect.Transitions.sinoidal, queue: 'end'});
Event.stop(event);

},
getObjStyleProperty: function(obj, property){
offset_left = obj.getStyle(property);
if(!offset_left)
return;
return parseInt(offset_left.replace('px', ''));
}
});

function loginSubmit(authType,showLogin,onSuccess,onFailure){
	new Ajax.Request(baseUrl + 'AjaxAuthenticateUser.aspx', 
	{	method: 'post', 
		onSuccess : function(resp) { 
						if(resp.responseText.indexOf("login") > -1) { 
							if(showLogin){
								document.observe('lightview:hidden', function(event) {
									loginSubmit(authType, false, onSuccess, onFailure);									
								});
								openLightView(baseUrl + 'WebFrmSecureLogin.aspx?OnlyHide=1', 274, 260, "member login", "please log in to submit a comment");
							} else {
								document.stopObserving('lightview:hidden');
								onFailure('failed');
							}									
						} else if(resp.responseText != "failed") {
							document.stopObserving('lightview:hidden');
							onSuccess(resp);
						} else {
							document.stopObserving('lightview:hidden');
							onFailure('failed');
						}							
					},
		parameters : "at=" + authType + "&cb=" + Math.random()
	});
}

// global variable that is set to 1 only after the page has loaded
// used to not show item balloons until page has loaded
var g_pageLoaded = 0;
document.observe("dom:loaded", function() {
  g_pageLoaded = 1;
});

