
// instance vars
var highlighted_vo = new Object();
var non_highlighted_vos = new Array();

//global variable to find out calling flow
var called_from = null;

//adding global variables to save offer
var selected_vo_id;
var selected_service_id;
var selected_offer_id = null;
var selected_offer_value;
var selected_offer_category;
var selected_offer_type;
var selected_offer_url;
var selected_service_name;
var selected_ratings_id = null;
var selected_convenience_rating = null;
var selected_price_estimate= null;
var selected_uuid = null;
var new_user = true;
var survey_submitted = false;

// global bit.ly url vars
var bitly_generated = false;
var bitly_url = "http://bit.ly/bWcUFx";

// Standard messages
var gazelleCarbonFree = "Yes, plus Gazelle will offset the carbon impact of shipping your item for Earth Month!";

// comparison matrix json loaded via ajax when requested
var comparison_matrix_json;
function getComparisonMatrix(highlight_service_id, offer_value, offer_type) {
	$.ajax({
		   type: "POST",
		   url: "/client/comparisonMatrix.htm",
		   dataType:"json",
		   success: function (data) {
				comparison_matrix_json = data;
				compareServices(highlight_service_id, offer_value, offer_type);
		   },
		   error:function (xhr, ajaxOptions, thrownError){ 

			} 
		   });
}

/**
*  Construct Service Comp Matrix from global result vos with the passed service in highlighted column of the table
*  @param {int}	highlight_service_id
*/
function compareServices(highlight_service_id, offer_value, offer_type) {
	
	// request JSON for comparison matrix if not yet set
	if (comparison_matrix_json == null) {
		getComparisonMatrix(highlight_service_id, offer_value, offer_type);
		return;
	}
	
	// Clear matrix divs of any previously displayed items
	var ul1 = $("<ul></ul>");
	var ul2 = $("<ul></ul>");
	$('#matrix_buttons').empty();
	$('#matrix_table > .left_container').empty().append(ul1);
	$('#matrix_table > .right_container > .scroll_container').empty().append(ul2);
	
	// Make overlay divs visible
	$('#overlay_mask').show();
	$('#overlay_container').show();
	$('#overlay_container').css('width','957px');
	$('#service_comp_matrix').show();
	
	makeQuestionColumn();
	
	// Find highlighted service by id (and hold on to all others in array)
	non_highlighted_vos = new Array();
	$.each(currentResultVOs, function(i, _vo) {
		if (_vo.service_id == highlight_service_id && _vo.offer_value == offer_value && _vo.offer_type == offer_type) {
			highlighted_vo = _vo;
		} else {
			if (_vo.offer_category.toUpperCase() != "RECYCLING" && _vo.offer_category.toUpperCase() != "DONATION")
				non_highlighted_vos.push(_vo);
		}
	});
	
	makeHighlightedColumn(highlighted_vo);
	makeComparisonColumns(non_highlighted_vos);
	
	// Set headline based on service name
	$("#compare_headline").html('Compare the offer from ' + highlighted_vo.service_name + ' with other websites.');
	
	// Set next / prev text
	if (non_highlighted_vos.length > 4) {
		var compText = $('<p></p>').html('Comparing 3 of ' + non_highlighted_vos.length + " offers");
		var prevBtn = $('<a id="matrix_prev" href="#"></a>').addClass('prev').html('<span class="hide_text">Previous Offer</span>');
		var nextBtn = $('<a id="matrix_next" href="#"></a>').addClass('next').html('<span class="hide_text">Next Offer</span>');
		$('#matrix_buttons').append(nextBtn);
		$('#matrix_buttons').append(compText);
		$('#matrix_buttons').append(prevBtn);
	}
	
	// Finally, enable scrolling on matrix table
	enableMatrixScrollPlugin();
	
	// Scroll window so overlay will fit
	scrollWindowToResults();
	
	// Tracking
	virtualPageView('virtual/CompareServicesMatrix');
}

/**
*  Close all overlay divs (set them to display:none)
* 
*/
function closeOverlay() {
	$('#overlay_mask').hide();
	$('#overlay_container').hide();
	$('#overlay_container .overlay').hide();
	$('#survey_overlay').hide();
	
	if (clipboard != null) {
		clipboard.destroy();
	}
}

/**
*  Construct HTML for left question column of service comp matrix
*  
*/
function makeQuestionColumn() {
	
	var column = $("<div></div>").addClass("question_column");
	var cnt=1;
	
	var head_row = $("<div></div>").addClass("header_row");
	column.append(head_row);
	
	$.each(comparison_matrix_json.questions, function(i, _q) {
		var whichRow = (cnt%2==0) ? "even_row" : "odd_row";
		var row = $("<div></div>").addClass(whichRow).addClass(i).addClass("question_row");
		
		var text = $("<div></div>").css("padding", "5px").html("<div class='question_text'>" + _q + "</div>");
		row.append(text);
		column.append(row);
		cnt++;
	});
	
	var whichRow = (cnt%2==0) ? "even_row" : "odd_row";
	var row = $("<div></div>").addClass(whichRow).addClass(i).addClass("question_row");
	
	var text = $("<div></div>").css("padding", "5px").html("<div class='question_text'>Offer Value</div>");
	row.append(text);
	column.append(row);
	
	//var select_row = $("<div></div>").addClass("select_btn_row");
	//column.append(select_row);
	
	var foot_row = $("<div></div>").addClass("foot_row");
	column.append(foot_row);
	
	var li = $('<li></li>').append(column);
	$('#matrix_table > .left_container ul').append(li);
	
}

/**
*  Construct HTML for highlighted column of matrix
*  {Object} _hVO - ResultVO object is passed in for display
*/
function makeHighlightedColumn(_hVO) {
	
	var column = $("<div id='serviceColumn" + _hVO.service_id + _hVO.offer_value + _hVO.offer_type + "'></div>").addClass("highlight_column").addClass('column');
	
	// Fix alignment issue in IE
	if($.browser.msie){
		var userAgent = $.browser.version;
		if (userAgent != "8.0")
			column.css('margin-top','-16px');
	}
	
	var cnt=1;
	$.each(comparison_matrix_json.services, function(i, _s) {
		if (_hVO.service_id == _s.service_id) {
			var head_row = $("<div></div>").addClass("header_row").addClass("service_name");
			head_row.html("<p>" + _hVO.service_name + "</p>");
			column.append(head_row);
			
			var answrCnt=0;
			$.each(_s.answers, function(j, _q) {

				var whichRow = (cnt%2==0) ? "even_row" : "odd_row";
				var whichCheckImg = (cnt%2==0) ? "checkmark_green_whiteBG.png" : "checkmark_green_blueBG.png";
				var row = $("<div></div>").addClass(whichRow).addClass(j).addClass("row");
				
				if (answrCnt==0 && _s.service_id==1) {
					var showQ = gazelleCarbonFree;
				} else {
					var showQ = (_q == "Yes") ? "<img src='../../images/service_comp/" + whichCheckImg + "' />" : _q;
					showQ = (_q == "No") ? " " : showQ;
				}
				
				var text = $("<div></div>").css("padding", "5px").html(showQ);
				row.append(text);
				column.append(row);
				cnt++;
				answrCnt++;
			});

			var whichRow = (cnt%2==0) ? "even_row" : "odd_row";
			var row = $("<div></div>").addClass(whichRow).addClass("row");
			var showVal = '<div class="value_main">' + _hVO.offer_value + '</div>';
			showVal +=	  '<div class="value_detail">' + _hVO.offer_type + '</div>';
			var text = $("<div></div>").css("padding", "5px").html(showVal);
			row.append(text);
			column.append(row);
			
			//var select_row = $("<div></div>").addClass("select_btn_row");
			//select_row.html('<a target="_blank" href="/client/redirect/tradeInRedirect.htm?service_id=' + _hVO.service_id + '&offer_url=' + escape(_hVO.offer_url) + '&offer_category=' + _hVO.offer_category + '&page=comparisonMatrix' + '" onclick="javascript:virtualPageView(\'virtual/ServiceRedirect\')"><img src="../../images/result_select_btn.jpg" onclick="javascript:saveOffer(\''+  _hVO.service_id + '\',\'' + _hVO.offer_value + '\',\'' + _hVO.offer_category + '\',\'' + _hVO.offer_type + '\',\'' + escape(_hVO.offer_url) + '\',\'' + _hVO.uuid + '\');"/></a>');
			//column.append(select_row);
			
			var foot_row = $("<div></div>").addClass("foot_row");
			column.append(foot_row);
			
			// break out of this .each() cuz we found who we're looking for
			return;
		}
		
	});
	
	var li = $('<li></li>').append(column);
	$('#matrix_table > .left_container ul').append(li);
	
}

/**
*  Construct HTML for other non-highlighted service columns of service comp matrix
*  {Array} _nonhighlight_vos - array of vos that aren't displayed as highlighted 
*/
function makeComparisonColumns(_nonhighlight_vos) {
	
	// 1. Iterate through _nonhighlight_vos
	$.each(_nonhighlight_vos, function(i, _vo) {
		
		var column = $("<div id='serviceColumn" + _vo.service_id + _vo.offer_value + _vo.offer_type + "'></div>").addClass('column');
		
		// 2. Iterate through service_comp_answers to find details for this vo
		var showCnt = 0;
		var cnt=1;
		$.each(comparison_matrix_json.services, function(j, _s) {
			if (_vo.service_id == _s.service_id) {
				var head_row = $("<div></div>").addClass("header_row").addClass("service_name");
				head_row.html("<p>" + _vo.service_name + "</p>");
				column.append(head_row);
				
				var answrCnt=0;
				$.each(_s.answers, function(k, _q) {
					
					var whichRow = (cnt%2==0) ? "even_row" : "odd_row";
					var whichCheckImg = (cnt%2==0) ? "checkmark_green_whiteBG.png" : "checkmark_green_blueBG.png";
					var row = $("<div></div>").addClass(whichRow).addClass(k).addClass("row");
					
					if (answrCnt==0 && _s.service_id==1) {
						var showQ = gazelleCarbonFree;
					} else {
						var showQ = (_q == "Yes") ? "<img src='../../images/service_comp/" + whichCheckImg + "' />" : _q;
						showQ = (_q == "No") ? " " : showQ;
					}
					
					var text = $("<div></div>").css("padding", "5px").html(showQ);
					row.append(text);
					column.append(row);
					cnt++;
					answrCnt++;
				});
				
				var whichRow = (cnt%2==0) ? "even_row" : "odd_row";
				var row = $("<div></div>").addClass(whichRow).addClass("row");
				var showVal = '<div class="value_main">' + _vo.offer_value + '</div>';
				showVal +=	  '<div class="value_detail">' + _vo.offer_type + '</div>';
				var text = $("<div></div>").css("padding", "5px").html(showVal);
				row.append(text);
				column.append(row);
				
				//var select_row = $("<div></div>").addClass("select_btn_row");
				//select_row.html('<a target="_blank" href="/client/redirect/tradeInRedirect.htm?service_id=' + _vo.service_id + '&offer_url=' + escape(_vo.offer_url) + '&offer_category=' + _vo.offer_category + '&page=comparisonMatrix' + '" onclick="javascript:virtualPageView(\'virtual/ServiceRedirect\')"><img src="../../images/result_select_btn.jpg" onclick="javascript:saveOffer(\''+  _vo.service_id + '\',\'' +_vo.offer_value + '\',\'' + _vo.offer_category + '\',\'' + _vo.offer_type + '\',\'' + escape(_vo.offer_url) + '\',\'' + _vo.uuid + '\');"/></a>');
				//column.append(select_row);
				
				var foot_row = $("<div></div>").addClass("foot_row");
				column.append(foot_row);
				
				if (showCnt == 3)
				{
					column.addClass('hidden');
				}
				showCnt++;
				
				
				// break out of this .each() cuz we found who we're looking for
				return;
			}
			
		}); // END 2. Iterate through service_comp_answers to find details for this vo
		
		var li = $('<li></li>').append(column);
		$('#scroll_matrix ul').append(li);
	
	}); // END 1. Iterate through _nonhighlight_vos
	
}

function getTooltip(el) {
	// Grab the title attribute's value and assign it to a variable
	var tip = $(el).attr('tooltip');	
		
	// Append the tooltip template and its value
	$(el).append('<div id="small_tooltip"><div>' + tip + '</div></div>');		
	$('#small_tooltip').show();
		
	$(el).mouseout(function() {
		$(this).children('div#small_tooltip').remove();
	});
}

//*******************************************************************************************
// User Ratings
//*******************************************************************************************

function showUserRatingOverlay(vo_id, service_id,offer_value,offer_category,offer_type,offer_url, service_name, rating_id, convenienceRating, priceEstimate) {
	//setting values of global variables
	
	$.each(currentResultVOs, function(i, _vo) {
		if (_vo.service_id == service_id && _vo.offer_value == offer_value && _vo.offer_type == offer_type) {
			selected_uuid = _vo.uuid;
		} 
	});
	selected_vo_id = vo_id;
	selected_service_id = service_id;
	selected_offer_value = offer_value;
	selected_offer_category = offer_category;
	selected_offer_type = offer_type;
	selected_offer_url = offer_url;
	selected_service_name = service_name;
	selected_ratings_id = null;
	called_from = null;
	if(rating_id){
		selected_ratings_id = rating_id;
		selected_convenience_rating = convenienceRating;
		selected_price_estimate = priceEstimate;
	}
	// Make overlay divs visible
	
	$('#overlay_mask').show();
	$('#overlay_container').show();
	$('#user_rating_overlay').show();
	$('#overlay_container').css('width','615px');
	$('#success_message').hide();
	// make ajax call to get dynamic ratings UI
	loadRatingsUI(service_id);
	
	// Scroll window so overlay will fit
	scrollWindowToResults();
	
	// Tracking
	virtualPageView('virtual/UserRatingOverlay');
}

/**
*  loadRatingsUI() function
*  @param {int} service_id Service Id to call (i.e. 1 is Gazelle)
*/
function loadRatingsUI(service_id) {
	// Make ajax call and setup callback
	$.ajax({
	   type: "POST",
	   url: "/client/async/user_ratings.jsp",
	   dataType:"html",
	   data: service_id,
	   success: loadRatingsUICallback,
	   error:function (xhr, ajaxOptions, thrownError){ 

		} 
	   });
}

function loadRatingsUICallback(data) {
	$('#user_rating_overlay').empty();
	$('#user_rating_overlay').html(data);
	$('#rate_headline').html('Rate your experience with ' + selected_service_name);
	if(selected_vo_id==null){
		called_from = "my_account";
		$('#user_rating_form').show();
		$('#rate_subhead').show();
		$('#rate_headline').show();
		$('#rate_headline').empty();
		$('#rate_headline').html('Rate your experience with ' + selected_service_name);
		if(selected_ratings_id!=null){
			starGroupClick('#star_group_'+selected_convenience_rating, '#convenience_group',selected_convenience_rating)
			$("#review_comments").val($("#review_comments_"  + selected_ratings_id).val());
			if (selected_price_estimate!=0) {
				$('#price_estimate_group').show();
				if(selected_price_estimate==2){
					$('#less_estimate').attr('checked', true);
				}
				else if(selected_price_estimate==3){
					$('#near_estimate').attr('checked', true);
				}
				else if(selected_price_estimate==4){
					$('#more_estimate').attr('checked', true);
				}
			}	
		}
		else if(selected_offer_category=='trade-in'){
			$('#price_estimate_group').show();
		}
		$('#ask_user_if_rated').hide();
		$('#ask_user_for_later').hide();
		$('#confirm_reminder').hide();
		$('#needs_to_login_to_rate').hide();
	}
}
/**
 * This function will check if the language entered in the comments is acceptable
 * @return
 */
function checkLanguage(element) {
	var success = false;  
	$.ajax({
		   type: "POST",
		   url: "/client/checkAgainstBlacklist.htm",
		   dataType:"json",
		   async: false,
		   data: "text=" + escape($(element).val()),
		   success: function(data){
				if (data.status && data.status == 'accepted') {
				success = true;
				} else {
					//bad language!
					$("#invalidcomment").html('');
					$(element).after("<span id ='invalidcomment' class='ValidationErrors'>Please edit your review so that it doesn't contain any language that could be deemed offensive by others.</span>");
					$(element).click(function() {
						$('.ValidationErrors').remove();
					});
				}
			},
		   error:function (xhr, ajaxOptions, thrownError){
			 //alert('debug: ' + xhr.status);
			 //alert('debug: ' + thrownError);
			} 
		   });
	return success;
}


//save selected offer
function saveRating(){
	//first check the language
	if (!checkLanguage("#review_comments")) return false;
	
	var loginRequired = true;
	if ($("#loggedIn").val() == 'true') {
		loginRequired = false;
	}
	if (loginRequired) {
		$('#user_rating_form').hide();
		var reminderSignInContents = $("#needs_to_login_to_get_reminder").html();
		var rateSignInContents = $("#needs_to_login_to_rate").html();
		if (reminderSignInContents != '' && rateSignInContents == '') {
			document.getElementById('needs_to_login_to_rate').innerHTML = reminderSignInContents;
			document.getElementById('needs_to_login_to_get_reminder').innerHTML = '';
		}	
		setupSignInWidgetForm();
		$("#needs_to_login_to_rate").show();
		$("#needs_to_login_disclaimer").show();
		
	} else {
		if(selected_ratings_id==null){
			saveRatings(selected_service_id, true);
			updateToolBar();
			if(called_from==null){
				showRatingsSuccessScreen();
				scrollWindowToResults();
				refreshResultItemRatings();
			}
			else if(called_from=='my_account'){
				closeOverlay();
				window.location.reload();
			}
			else if(called_from=='service_profile'){
				called_from = null;
				refreshResults();
			}
			else if(called_from=='results'){
				refreshResults();
				refreshResultItemRatings();
			}
		}
		else{
			updateRatings(selected_ratings_id);
		}
	}
	//show user a success screen, this can be done even before the ajax call to save ratings returns
	return false;
}

function updateRatings(rating_id){
	var convenience_rating = $("#convenience_group").children('input').val();
	var price_estimate = getPriceEstimate(document.getElementsByName("price_estimate"));
	if(price_estimate == undefined)
		price_estimate = "";
	var review_comments = $("#review_comments").val();
	
	var dataStr = "rating_id=" + rating_id + "&" + 
				  "convenience_rating=" + convenience_rating  + "&" + 
				  "price_estimate=" + price_estimate  + "&" +
				  "review_comments=" + escape(review_comments);
	
	
	$.ajax({
		type: "POST",
		url: "/client/updateSelectedRatings.htm",
		dataType:"html",
		data: dataStr,
		success: updateRatingsCallback,
		error:function (xhr, ajaxOptions, thrownError){
		 //alert('debug: ' + xhr.status);
		 //alert('debug: ' + thrownError);
			} 
		   });
}

function updateRatingsCallback(data) {
	closeOverlay();
	showRatingsCallBack(data);
}

function reminderRequest() {
	saveOfferWithReminder(selected_service_id,selected_offer_value,selected_offer_category,selected_offer_type,selected_offer_url,uuid);
	showReminderSuccessScreen();
	return false;
}


function showReminderSuccessScreen() {
	//close all divs
	$('#ask_user_if_rated').hide();
	$('#user_rating_form').hide();
	$('#ask_user_for_later').hide();
	$('#confirm_reminder').hide();
	$('#needs_to_login_to_rate').hide();
	$('#needs_to_login_to_get_reminder').hide();
	
	var successPage = "<div id='rating_reminder_success'><p>Thanks! We'll send you an email in the coming weeks<br /> to come back and rate this service.</p><p>By then, you will have successfully completed your transaction, and you can come back and share your experience with the EcoSquid community.</p></div>";
	$('#success_message').empty();
	$('#success_message').append(successPage);
	$('#success_message').show();
	scrollWindowToResults();
}


function refreshResultItemRatings() {
	// Update rating num for result_item
	var targItem = "#result" + selected_vo_id + " .ratings_count";
	var old_num = 0;
	var new_num = 0;
	var user_ratings = 0;
	var targetResult = null;
	var len = allResultVOs.length;
	for (var i=0; i<len; i++) {
		if (allResultVOs[i].id == selected_vo_id) {
			old_num = parseInt(allResultVOs[i].num_ratings);
			new_num = old_num+1;
			allResultVOs[i].num_ratings = new_num;
			targetResult = allResultVOs[i];
			//now use target result vo to come up with an algo to see stars in the day
			var user_ratings = old_num * parseFloat(targetResult.user_rating);
			user_ratings += parseInt($("#convenience_group").children('input').val());
			user_ratings = user_ratings / new_num;
			user_ratings = user_ratings.toFixed(2);
			allResultVOs[i].user_rating = user_ratings;
			break;
		}
	}
	;
	var new_ratings_html = '<a href="javascript:showServiceProfileOverlay(\'' + selected_vo_id + '\',\'' + selected_service_id + '\',\'' + selected_offer_category + '\',\'' + selected_offer_type + '\',\'' + selected_offer_url + '\',\'' + selected_service_name + '\')">' + new_num + ' ratings</a>';
	$(targItem).html(new_ratings_html);
	
	// Update stars display
	//TODO move to a method in results.js
	var targStars = "#result" + selected_vo_id + " .rating_stars";
	var noOfSolidStars = parseInt(user_ratings);
	var fractionStarNo = parseInt((user_ratings % 1) * 10);
	html_str = '';
		var i = 0 ;
		for (i = 0; i < noOfSolidStars; i ++) {
			html_str +=							'<div class="star4"></div> <!--1st star-->';
		}
		if (fractionStarNo > 0 && fractionStarNo < 3) {
			i ++;
			html_str +=							'<div class="star1"></div> <!--5th star-->';
		} else if (fractionStarNo > 0 && fractionStarNo  < 6) {
			i ++;
			html_str +=							'<div class="star2"></div> <!--5th star-->';
		} else if (fractionStarNo > 0 && fractionStarNo  < 9) {
			i ++;
			html_str +=							'<div class="star3"></div> <!--5th star-->';
		} else if (fractionStarNo > 0) {
			i ++;
			html_str +=							'<div class="star4"></div> <!--5th star-->';
		}
		for (; i < 5; i ++) {
			html_str +=							'<div class="star0"></div> <!--5th star-->';
		}
	$(targStars).html(html_str);
}


function signInWidgetResponse(jsonresponse, status, email) {
	if (jsonresponse.status == 'success') {
		//for some strange reason this response call back is being called twice!! added a fix
		if($('#success_message').css("display") == 'block') {
			return;
		}
		$("#loggedIn").val('true');
		if (called_from != null) {
			saveRatings(selected_service_id, true);
			if(called_from=='service_profile'){
				called_from = null;
			}
			refreshResults();
			refreshResultItemRatings();
		}
		
		if ($('#ask_user_if_rated_check').attr('checked') == true) {
				saveRatings(selected_service_id, true);
				showRatingsSuccessScreen();
				scrollWindowToResults();
				refreshResultItemRatings();
			
		} else if ($('#ask_user_for_later_check').attr('checked') == true) {
			
			$("#needs_to_login_to_get_reminder").hide();
			$('#confirm_reminder').show();
			$('#service_name').html(selected_service_name);
			
			if ($('#email_login_widget').val() != "") {
				$('#user_email_id').html($('#email_login_widget').val());	
			} else 
			if (email != undefined && email != '') {
				$('#user_email_id').html(email);	
			} 
			 
		}
		fixFooterAndHeaderOnLogin();
		updateToolBar();
	}
	
	if (jsonresponse.status == 'failure') {
		jQuery("#invalidemail").html('');
	    jQuery("#signin_generic_error_widget").after('<span id="invalidemail" class="ValidationErrors">&nbsp;&nbsp;Invalid username / email / password</span>');
	    jQuery("#signin_generic_error_widget").addClass("ErrorField");
		called = 'false';
	}
}

function errorSignInWidgetResponse() {
	jQuery("#invalidemail").html('');
    jQuery("#signin_generic_error_widget").after('<span id="invalidemail" class="ValidationErrors">&nbsp;&nbsp;Oops.. EcoSquid is experiencing some technical problems, please try again later</span>');
    jQuery("#signin_generic_error_widget").addClass("ErrorField");
}

function showSignUpWidget() {
	setUpSignUpWidgetForm();
	$("#duplicate_email_error_widget").hide();
	$("#signin_form_div").hide();
	$("#show_sign_up_widget_link").hide();
	$("#register_form_div").show();
}

function saveRatingsAfterRegistration(){
	if($('#success_message').css("display") == 'block') {
		return;
	}
	$("#loggedIn").val('true');
	if (called_from != null) {
		saveRatings(selected_service_id, true);
		if(called_from=='service_profile'){
			called_from = null;
		}
		refreshResults();
		refreshResultItemRatings();
		//return;
	}
	if ($('#ask_user_if_rated_check').attr('checked') == true) {
			saveRatings(selected_service_id, true);
			showRatingsSuccessScreen();
			scrollWindowToResults();
			refreshResultItemRatings();
	} else if ($('#ask_user_for_later_check').attr('checked') == true) {
		$("#needs_to_login_to_get_reminder").hide();
		$('#confirm_reminder').show();
		$('#service_name').html(selected_service_name);
		if ($('#email_address').val() != '') {
			$('#user_email_id').html($('#email_address').val());	
		}
	}
	fixFooterAndHeaderOnLogin();
	updateToolBar();
}

function saveOfferWithReminder(service_id,offer_value,offer_category,offer_type,offer_url,uuid){
	saveOffer(service_id,offer_value,offer_category,offer_type,offer_url,uuid,'true');
}

function saveRatingOfferCallback(data){
	//saveRatings(data.offer_Id, false);
}

function getPriceEstimate(radioGroup) {
	for (var i=0; i < radioGroup.length; i++) {
	   if (radioGroup[i].checked) {
		  return  radioGroup[i].value;
	   }
	}
}

function showRatingsSuccessScreen() {
	//get the ratings entered by the user
	var convenience_rating = $("#convenience_group").children('input').val();
	var price_estimate = getPriceEstimate(document.getElementsByName("price_estimate"));
	if(price_estimate == undefined)
		price_estimate = "";
	
	var review_comments = $("#review_comments").val();
	//close all divs
	$('#ask_user_if_rated').hide();
	$('#user_rating_form').hide();
	$('#ask_user_for_later').hide();
	$('#confirm_reminder').hide();
	$('#rate_subhead').empty();
	$('#needs_to_login_to_rate').hide();
	
	var convenience_desc = "";
	var stars_div = "";
	if(convenience_rating==1){
		convenience_desc = "Very poor";
		stars_div = "<div class='stars'><div class='star4'></div><div class='star0'></div><div class='star0'></div><div class='star0'></div><div class='star0'></div></div>";
	}
	else if(convenience_rating==2){
		convenience_desc = "Poor";
		stars_div = "<div class='stars'><div class='star4'></div><div class='star4'></div><div class='star0'></div><div class='star0'></div><div class='star0'></div></div>";
	}
	else if(convenience_rating==3){
		convenience_desc = "Average";
		stars_div = "<div class='stars'><div class='star4'></div><div class='star4'></div><div class='star4'></div><div class='star0'></div><div class='star0'></div></div>";
	}
	else if(convenience_rating==4){
		convenience_desc = "Good";
		stars_div = "<div class='stars'><div class='star4'></div><div class='star4'></div><div class='star4'></div><div class='star4'></div><div class='star0'></div></div>";
	}
	else if(convenience_rating==5){
		convenience_desc = "Excellent";
		stars_div = "<div class='stars'><div class='star4'></div><div class='star4'></div><div class='star4'></div><div class='star4'></div><div class='star4'></div></div>";
	}
	
	var price_estimate_desc = "";
	if(price_estimate==2){
		price_estimate_desc = "Less than estimate";
	}
	else if(price_estimate==3){
		price_estimate_desc = "Near estimate";
	}
	else if(price_estimate==4){
		price_estimate_desc = "More than estimate";
	}
	var successPage = "<div id='thanks_for_rating'><h2>Thanks for contributing your rating to the community!</h2></div>" +
			"<p class='pthanks_for_rating'><strong>Your rating:</strong></p><div class='star_group' style='margin:0px auto;position:relative;'><div class='star_label' style='margin-left: 10px;width: 60px;font-weight:bold;'>" + convenience_desc + "</div>" + stars_div + "</div>";
	if (price_estimate_desc != "") {
		successPage += "<p class='pthanks_for_rating' style='margin-top: 15px;'><strong>Trade-in price accuracy:</strong></p><p class='pthanks_for_rating' style='margin-top:10px;font-weight: bold; color: #313131; font-size: 12px;'>" + price_estimate_desc + "</p>";
	}
	successPage += "<p class='pthanks_for_rating' style='margin-top: 25px; font-size: 12px;'>Your rating has been saved <a href='/client/myAccount.htm'>on your accounts page &raquo;</a></p>";
	$('#success_message').empty();
	$('#success_message').append(successPage);
	$('#success_message').show();

	
}

function saveRatings(service_id, blocking){
	var convenience_rating = $("#convenience_group").children('input').val();
	var price_estimate = getPriceEstimate(document.getElementsByName("price_estimate"));
	if(price_estimate == undefined)
		price_estimate = "";
	var review_comments = $("#review_comments").val();
	
	var dataStr = "partner_id=" + service_id + "&" + 
				  "convenience_rating=" + convenience_rating  + "&" + 
				  "price_estimate=" + price_estimate  + "&" +
				  "review_comments=" + escape(review_comments);
					
	if (blocking == true) {
		$.ajax({
			type: "POST",
			url: "/client/saveSelectedRatings.htm",
			dataType:"json",
			async: false,
			data: dataStr,
			success: saveRatingsCallback,
			error:function (xhr, ajaxOptions, thrownError){
			updateToolBar();
			//alert('debug: ' + xhr.status);
			 //alert('debug: ' + thrownError);
			} 
			});
	
	} else { 
		$.ajax({
		type: "POST",
		url: "/client/saveSelectedRatings.htm",
		dataType:"json",
		data: dataStr,
		success: saveRatingsCallback,
		error:function (xhr, ajaxOptions, thrownError){
			updateToolBar();
		 // alert('debug: ' + xhr.status);
		 //alert('debug: ' + thrownError);
		} 
		});
	}
}

function saveRatingsCallback(data){
	updateToolBar();
}

function askUserIfRatedClicked() {
	called = 'false';
	$("#duplicate_email_error_widget").hide();
	$("#duplicate_email_error_signup").hide();
	$('#ask_user_for_later_check').attr('checked', false);
	if (!$('#ask_user_if_rated_check').attr('checked')) {
		$('#ask_user_if_rated_check').attr('checked', true);
		if (selected_offer_category == 'trade-in') {
			$('#price_estimate_group').show();
		} else {
			$('#price_estimate_group').hide();
		}
		$('#register_form_div').hide();
		$('#signin_form_div').show();
		$("#show_sign_up_widget_link").show();
		$('#user_rating_form').show();
		$('#confirm_reminder').hide();
		$("#needs_to_login_to_get_reminder").hide();
	} else {
		$('#ask_user_if_rated_check').attr('checked', false);
		$('#user_rating_form').hide();
		$("#needs_to_login_to_rate").hide();
	}
}

function askUserForLaterClicked() {
	called = 'false';
	$("#duplicate_email_error_widget").hide();
	$("#duplicate_email_error_signup").hide();
	$('#ask_user_if_rated_check').attr('checked', false);
	if (!$('#ask_user_for_later_check').attr('checked')) {
		$('#ask_user_for_later_check').attr('checked', true);
		$('#user_rating_form').hide();
		$('#register_form_div').hide();
		$('#signin_form_div').show();
		$("#show_sign_up_widget_link").show();
		$("#needs_to_login_to_rate").hide();
		// CHECK IF LOGGED IN HERE -->
		// show if not logged in...
		var loginRequired = true;
		if ($("#loggedIn").val() == 'true') {
			loginRequired = false;
		}
		if (loginRequired) {
			var reminderSignInContents = $("#needs_to_login_to_get_reminder").html();
			var rateSignInContents = $("#needs_to_login_to_rate").html();
			if (reminderSignInContents == '' && rateSignInContents != '') {
				document.getElementById('needs_to_login_to_rate').innerHTML = '';
				document.getElementById('needs_to_login_to_get_reminder').innerHTML = rateSignInContents;
			}	
			setupSignInWidgetForm();
			$("#needs_to_login_to_get_reminder").show();
		} else {
			$('#confirm_reminder').show();
			$('#service_name').html(selected_service_name);
		}
	} else {
		$('#ask_user_for_later_check').attr('checked', false);
		$('#confirm_reminder').hide();
		$("#needs_to_login_to_get_reminder").hide();
	}
	
}
		

function starGroupMouseOver(el, _id) {
	
	var children =  $(_id).children('.star_group');
	var len = children.length;
	for (var i=0; i<len; i++) {
		var group = children[i];
		if (!$(group).hasClass('selected')) {
			$(group).css('border-color', '#ffffff');
		}
	}
	
	if (!$(el).hasClass('selected')) {
		$(el).css('border-color', '#397144');
	}	
}

function starGroupMouseOut(el) {
	if (!$(el).hasClass('selected')) {
		$(el).css('border-color', '#ffffff');
	}
}

/*
 * starGroupClick() - Handles rating choice on select
 * 
 * {Object} Dom element that was clicked
 * {String} Id string for group element
 * {int}	Value to set hidden input to
 */
function starGroupClick(_el, _id, _val) {
	$(_id).children('.star_group').css('border-color','#ffffff');
	$(_id).children('.star_group').removeClass('selected');
	$(_el).addClass('selected');
	$(_el).css('border-color','#19b338');
	$(_id).children('input').val(_val);
	validateRatingsForm();
}

/*
 * validates the user ratings form, to make sure ratings are entered before submit is enabled.
 */
function validateRatingsForm() {
	if($('#price_estimate_group').css("display") == 'block') {
		var price_estimate = getPriceEstimate(document.getElementsByName("price_estimate"));
		if(price_estimate != undefined && $('#selected_convenience_rating').val() != 0) {
			$('#submit_user_ratings').attr("disabled", "");
			$('#submit_user_ratings').removeClass("disabled");
		} else {
			$('#submit_user_ratings').attr("disabled", "disabled");
			$('#submit_user_ratings').addClass("disabled");
		}
	} else {
		if($('#selected_convenience_rating').val() != 0) {
			$('#submit_user_ratings').attr("disabled", "");
			$('#submit_user_ratings').removeClass("disabled");
		} else {
			$('#submit_user_ratings').attr("disabled", "disabled");
			$('#submit_user_ratings').addClass("disabled");
		}
	}
}




//*******************************************************************************************
// Service Ratings Profile
//*******************************************************************************************
function refreshResults(){
		var postVar = "partner_id=" + selected_service_id + "&offer_type=" + selected_offer_category;
		if(called_from!=null){
			postVar += "&called_from=" + called_from;
		}
		$.ajax({
		 type: "POST",
		 url: "/client/partnerProfile.htm",
		 dataType:"html",
		 data: postVar,
		 success: refreshResultsCallback,
		 error:function (xhr, ajaxOptions, thrownError){ 
		
			} 
		 });
}

function refreshResultsCallback(data){
	if(called_from==null){
		$('#service_profile_overlay').empty();
		$('#service_profile_overlay').html(data);
	}
	else{
		$('#ratings_for').empty();
		$('#ratings_for').html(data);
	}
	$('#ratings_interface').hide();
	//$("#profile_scrollbar").show();
	$("#service_items_container").show();
	$("#rate_service").show();
	$("#back_to_ratings_history").hide();
}


function showEBRratingOverlay() {
	
	$('#overlay_mask').show();
	$('#overlay_container').show();
	$('#overlay_container').css('margin-top','180px');
	$('#ebr_rating_overlay').show();
	$('#overlay_container').css('width','600px');
	$('#success_message').hide();
}

function getBitlyShortURL() {
	
	var postVar = "";
	var urlLocation = window.location.href;
	var urlLocation = window.location.href;
	if(urlLocation.indexOf("referral")>=0){
		urlLocation = urlLocation.substring(0,urlLocation.indexOf("referral"));
	}
	if (urlLocation.length > 0){
		postVar = "page_url="+urlLocation;
	}
	if($("#offer_search_id").val() != ''){
		postVar +=  "&search_id=" + $("#offer_search_id").val();
	}
	
	$.ajax({
		   type: "POST",
		   url: "/client/generateReferral.htm",
		   dataType:"json",
		   data: postVar,
		   success: bitlyURLCallback,
		   error:function (xhr, ajaxOptions, thrownError){ 
			} 
		   });
}

function bitlyURLCallback(data) {
	bitly_url = data.url;
	bitly_generated = true;
	//loadCallToActionUI();
}

function decideOverlayToShow(category_id,offer_value,offer_category,brand,model){
	callToActionObj.category_id = category_id;
	callToActionObj.offer_value = offer_value;
	callToActionObj.offer_category = offer_category;
	callToActionObj.brand = brand;
	callToActionObj.model = model;
	
	if(category_id==2){
		checkSurveySubmitted();
	}
	else if(survey_submitted == false){
		showCalltoActionBox(category_id, offer_value, offer_category, brand, model);
	}
}

function checkSurveySubmitted(){
	
	$.ajax({
		   type: "POST",
		   url: "/client/checkSurveySubmitted.htm",
		   dataType:"json",
		   data: "",
		   success: checkSurveySubmittedUICallback,
		   error:function (xhr, ajaxOptions, thrownError){ 
		 		//alert('debug: ' + xhr.status);
		 		//alert('debug: ' + thrownError);
			} 
		   });
}

function checkSurveySubmittedUICallback(data){
	if(data.submitted != 'submitted'){
		if(new_user == true){
			new_user = false;
			showSurveyOverlay();
		}
		else{
			showCalltoActionBox(callToActionObj.category_id,callToActionObj.offer_value, callToActionObj.offer_category, callToActionObj.brand, callToActionObj.model);
		}
	}
	else{
		showCalltoActionBox(callToActionObj.category_id,callToActionObj.offer_value, callToActionObj.offer_category, callToActionObj.brand, callToActionObj.model);
	}
}

function saveSurvey(){
	
	var sending_in = getRadioButtonValue(document.getElementsByName("sending_in"));
	var upgrade = getRadioButtonValue(document.getElementsByName("looking_to_upgrade"));
	var refer = getRadioButtonValue(document.getElementsByName("would_refer"));
	var dataStr =   "sending_in=" + sending_in + "&" + 
					"upgrade=" + upgrade + "&" +
					"refer=" + refer;
	if(sending_in=='no'){
		dataStr += "&little_money=" + $("#little_money").attr("checked");
		dataStr += "&hassle=" + $("#hassle").attr("checked");
		dataStr += "&trust=" + $("#trust").attr("checked");
		dataStr += "&personal_data=" + $("#personal_data").attr("checked");
		if($("#other_whynot").attr("checked")==true){
			dataStr += "&other=" + escape($("#why_no_other").val());
		}
	}
	if(refer=='no'){
		dataStr += "&why_no_refer_text=" + escape($("#why_no_refer_text").val());
	}
	
	$.ajax({
		   type: "POST",
		   url: "/client/saveSurvey.htm",
		   dataType:"json",
		   data: dataStr,
		   success: saveSurveyUICallback,
		   error:function (xhr, ajaxOptions, thrownError){ 
		 		//alert('debug: ' + xhr.status);
		 		//alert('debug: ' + thrownError);
			} 
		   });
}

function saveSurveyUICallback(data){
	$("#survey_form").hide();
	if(data.submitted == 'submitted'){
		$("#show_success_message").show();
	}
	else{
		$("#show_error_message").show();
	}
}

function showCalltoActionBox(category_id,offer_value,offer_category,brand,model) {
	
	
	var index1=offer_value.indexOf("-");
	if(index1>-1){
		offer_value=offer_value.substring(0,index1);
	}
	
	var offerValueIndex=offer_value.indexOf(".");
	if(offerValueIndex>-1){
		offer_value=offer_value.substring(0,offerValueIndex);
	}
	
	
	
	callToActionObj.category_id = category_id;
	callToActionObj.offer_value = offer_value;
	callToActionObj.offer_category = offer_category;
	callToActionObj.brand = brand;
	callToActionObj.model = model;
	
	$('#overlay_mask').show();
	$('#overlay_container').show();
	$('#call_to_action_overlay').show();
	$('#overlay_container').css('width','600px');
	$('#success_message').hide();
	
	//if (!bitly_generated) {
		//getBitlyShortURL();
	//} else {
		loadCallToActionUI();
	//}
}


//global object for loadCallToActionUI method
var callToActionObj = {
	category_id: 1,
	offer_value: "",
	offer_category: "",
	brand: "",
	model: ""
}

function loadCallToActionUI() {
	
	var postVar = "category_id=" + callToActionObj.category_id 
	  + "&offer_value=" + callToActionObj.offer_value + "&offer_category=" + callToActionObj.offer_category + "&brand=" + callToActionObj.brand + "&model=" + callToActionObj.model + "&email_id="+ optional_email_id; // optional_email_id is in results.js
	
	var urlLocation = window.location.href;
	if (urlLocation.length > 0)
		postVar += "&page_url="+urlLocation;
	
	$.ajax({
		   type: "POST",
		   url: "/client/callToAction.htm",
		   dataType:"html",
		   data: postVar,
		   success: loadCallToActionUICallback,
		   error:function (xhr, ajaxOptions, thrownError){ 
		 		//alert('debug: ' + xhr.status);
		 		//alert('debug: ' + thrownError);
			} 
		   });
}

function loadCallToActionUICallback(data) {
	
	$('#call_to_action_overlay').empty();
	$('#call_to_action_overlay').html(data);
	addthis.init();
	
}

function showSurveyOverlay() {
	$('#overlay_mask').show();
	$('#overlay_container').show();
	$('#survey_overlay').show();
	$('#overlay_container').css('width','600px');
	$('#success_message').hide();
	
	$.ajax({ url: "/client/async/survey.jsp",
			 success: loadSurveyCallback
		   });
}

function loadSurveyCallback(data) {
	$('#survey_overlay').empty();
	$('#survey_overlay').html(data);
}

var overlay = null;

function showPointsOverlay(pointsAwarded,loggedIn,offerSelected,overlayShown) {
	$('#overlay_mask').show();
	$('#overlay_container').show();
	$('#overlay_container').css('width','630px');
	$('#success_message').hide();
	if(loggedIn == 'true'){
		if(pointsAwarded == 'true'){
			overlay = '2a';
		}
		else if(overlayShown != 'true'){
			overlay = '2b';
		}
		else{
			overlay = null;
		}
	}
	else{
		if(offerSelected != 'true'){
			overlay = '1a';
		}
		else{
			overlay = '1b';
		}
	}
	$('#points_overlay').show();
	$.ajax({ url: "/client/async/points_overlay.jsp",
		 success: loadPointsCallback
	});
}

function loadPointsCallback(data) {
	$('#points_overlay').empty();
	$('#points_overlay').html(data);
	if(overlay == '1a'){
		$('#points_overlay').show();
		$("#points_talk_bubble_overlay_head").html('');
		var html = '<div>You just earned</div>';
		$("#points_talk_bubble_overlay_head").html(html);
		$("#initial_points").show();
		$("#potential_points").hide();
		$("#user_points").hide();
		
		$("#points_overlay_explanation_head").html('');
		html = 'Your green deeds can also earn you valuable rewards.';
		$("#points_overlay_explanation_head").html(html);
		$("#points_overlay_explanation_head").css('clear','both');
		$("#points_overlay_explanation_head").show();
		
		$("#points_overlay_explanation_text").html('');
		html = '<a href="/client/signup.jsp">Register a free account</a> on EcoSquid and start earning points for your actions on the site.' + 
			   'The points you gain go towards discount rewards and qualify you for giveaway contests.';
		$("#points_overlay_explanation_text").html(html);
		
		$("#points_overlay_green_explanation_head").hide();
		$("#points_overlay_bottom_strip").show();
		$("#points_overlay_share_widget").hide();
	}
	else if(overlay == '1b'){
		$('#points_overlay').show();
		$("#points_talk_bubble_overlay_head").html('');
		var html = '<div>You already have</div>';
		$("#points_talk_bubble_overlay_head").html(html);
		$("#initial_points").hide();
		$("#potential_points").show();
		$("#user_points").hide();
		
		$("#points_overlay_explanation_head").html('');
		html = 'Don\'t let the points you have earned go waste!';
		$("#points_overlay_explanation_head").html(html);
		$("#points_overlay_explanation_head").css('clear','both');
		$("#points_overlay_explanation_head").show();
		
		$("#points_overlay_explanation_text").html('');
		html = '<a href="/client/signup.jsp">Register a free account</a> on EcoSquid and start earning points for your actions on the site.' + 
			   'The points you gain go towards discount rewards and qualify you for giveaway contests.';
		$("#points_overlay_explanation_text").html(html);
		
		$("#points_overlay_green_explanation_head").hide();
		$("#points_overlay_bottom_strip").show();
		$("#points_overlay_share_widget").hide();
	}
	else if(overlay == '2a'){
		$('#points_overlay').show();
		$("#points_talk_bubble_overlay_head").html('');
		var html =  '<div>You now have</div>';
		$("#points_talk_bubble_overlay_head").html(html);
		$("#initial_points").hide();
		$("#potential_points").hide();
		$("#user_points").show();
		
		$("#points_overlay_explanation_head").html('');
		html = 'Congratulations, you just earned 200 points for selecting an offer!';
		$("#points_overlay_explanation_head").html(html);
		$("#points_overlay_explanation_head").css('width','270px');
		$("#points_overlay_explanation_head").show();
		
		$("#points_overlay_explanation_text").html('');
		html = 'Stay up to date with your point earning history on your account page.';
		$("#points_overlay_explanation_text").html(html);
		
		$("#points_overlay_green_explanation_head").show();
		$("#points_overlay_bottom_strip").hide();
		$("#points_overlay_share_widget").show();
	}
	else if(overlay == '2b'){
		$('#points_overlay').show();
		$("#points_talk_bubble_overlay_head").html('');
		var html =  '<div>You have</div>';
		$("#points_talk_bubble_overlay_head").html(html);
		$("#initial_points").hide();
		$("#potential_points").hide();
		$("#user_points").show();
		
		$("#points_overlay_explanation_head").hide();
		
		$("#points_overlay_explanation_text").html('');
		html = 'Looks like you were already awarded	points for selecting an offer this week, but not to worry! You can still earn points by referring friends. Learn how below:';
		$("#points_overlay_explanation_text").html(html);
		
		$("#points_overlay_green_explanation_head").show();
		$("#points_overlay_bottom_strip").hide();
		$("#points_overlay_share_widget").show();
	}
	else{
		$('#overlay_mask').hide();
		$('#overlay_container').hide();
	}
}

var clipboard = null;
function setupClipboardCopy() {
	
	if (!FlashDetect.installed) {
		return false;
	}
	
	var clip_bitly_link = jQuery("#bitly_share_link").html();
	ZeroClipboard.setMoviePath( 'http://ecosquidtest.virtual.vps-host.net/client/js/ZeroClipboard.swf' );
	clipboard = new ZeroClipboard.Client();
	
	clipboard.setHandCursor( true );
	clipboard.addEventListener('mouseOver', function (client) {
		// copy the text on mouse over
		clipboard.setText( clip_bitly_link );
	});
	clipboard.addEventListener('complete', function (client, text) {
		// alert("copied " + text);
	});
	clipboard.glue( "copy_click" );
}

function showReferralOverlay() {
	$('#overlay_mask').show();
	$('#overlay_container').show();
	$('#refer_points_overlay').show();
	$('#overlay_container').css('width','630px');
	$('#success_message').hide();
	
	$.ajax({ url: "/client/async/refer_points_overlay.jsp",
			 success: loadPointsCallbackRefer
		   });
	
}

function loadPointsCallbackRefer(data) {
	$('#refer_points_overlay').empty();
	$('#refer_points_overlay').html(data);
	setupClipboardCopy();
}

function showServiceProfileOverlay(vo_id, service_id, offer_category,offer_type,service_url, service_name) {
	//setting values of global variables
	selected_vo_id = vo_id;
	selected_service_id = service_id;
	selected_offer_category = offer_category;
	selected_offer_type = offer_type;
	selected_offer_url = service_url;
	selected_service_name = service_name;
	called_from = "results";
	// Make overlay divs visible
	
	$('#overlay_mask').show();
	$('#overlay_container').show();
	$('#service_profile_overlay').show();
	$('#overlay_container').css('width','775px');
	$('#success_message').hide();
	
	// make ajax call to get dynamic ratings UI
	loadServiceProfileUI(service_id,offer_category,offer_type,service_url, service_name, called_from);
	// Scroll window so overlay will fit
	scrollWindowToResults();
	
	// Tracking
	virtualPageView('virtual/ServiceRatingsProfile');
}

/**
*  loadServiceProfileUI() function
*  @param {int} service_id Service Id to call (i.e. 1 is Gazelle)
*/
function loadServiceProfileUI(service_id,offer_category,offer_type,service_url, service_name, called_from) {

	var postVar = "partner_id=" + service_id 
				  + "&offer_category=" + offer_category + "&offer_type=" + offer_type 
				  + "&service_url=" + service_url + "&service_name=" + service_name;
	
	if(called_from!=null){
		postVar += "&called_from=" + called_from;
	}
	
	// Make ajax call and setup callback
	$.ajax({
	   type: "POST",
	   url: "/client/partnerProfile.htm",
	   dataType:"html",
	   data: postVar,
	   success: loadServiceProfileUICallback,
	   error:function (xhr, ajaxOptions, thrownError){ 

		} 
	   });
	
}

function loadServiceProfileUICallback(data) {
	$('#user_rating_overlay').empty();
	$('#service_profile_overlay').empty();
	$('#service_profile_overlay').html(data);
	$('#ask_user_if_rated').hide();
	$('#user_rating_form').hide();
	$('#ask_user_for_later').hide();
	$('#confirm_reminder').hide();
	$('#rate_subhead').hide();
	$('#needs_to_login_to_rate').hide();
	$('#rate_headline').hide();
	$('#close_user_ratings').hide();
	makeCommentsExpandable();
}
/**
 * added for the service profile standalone page
 * @param serviceId
 * @param serviceName
 * @param offerId
 * @return
 */
function loadRatingsInterface(serviceId,serviceName,offerId,offerType, fromOverlay){
	if (fromOverlay != true) {
		if(called_from==null){
			called_from = "service_profile";
		}
		if(called_from == 'results'){
			$('#user_rating_form').css("margin", "0px");
			$('#review_comments').css("width", '450px');
			$('#needs_to_login_disclaimer').css('margin', '0px 0px 0px 0px');
			$('#needs_to_login_disclaimer').css('width', '425px');
			$('.services-you-rated').css('clear', 'both');
			$('.ratings_for_historic_item').css('clear', 'both');
			$('#signin_form_div').css('padding-left', '0px');
			$('#signin_form_div').css('width', '45%');
			$('.signin_field').css('width', '180px');
			$('#signup_div').css('padding-left', '0px');
			$('#sign_in_submit_button').css('width', '80px');
		}
		else{
			$('#review_comments').css("width", '440px');
			$('#signin_form_div').css('padding-left', '0px');
			$('#signin_form_div').css('width', '45%');
		}
		$('#register_form_div').hide();
		$('#signin_form_div').show();
		$('#show_sign_up_widget_link').show();
		$('#need_to_register').css('padding', '12px 0px 0px 12px');
		$('#need_to_register p').css('font-size', '12px');
		$('#user_rating_form').show();
		$('#rate_subhead').hide();
		$('#rate_headline').hide();
		$('#ask_user_if_rated').hide();
		$('#ask_user_for_later').hide();
		$('#confirm_reminder').hide();
		$('#needs_to_login_to_rate').hide();
		$('#close_user_ratings').hide();
		$('#rate_comp_head').hide();
		$('#user_rating_form form').css("width", '94%');
		$('#submit_rating_div').css("padding-right", '15px');
		$('#submit_rating_div').css("text-align", 'center');
		$('#sign_in_field').css('height', '70px');
		if(serviceId) {
			selected_service_id = serviceId;
		}
		if(serviceName) {
			selected_service_name = serviceName;
		}
		if(offerId){
			selected_offer_id = offerId;
		}
		if (offerType == 'trade-in') {
			selected_offer_category = offerType;
			$('#price_estimate_group').show();
		}
	}
}

function unblockRatingsInterface(fromOverlay, fromSiteMap) {
	if (fromOverlay != true && fromSiteMap != true) {
		$('#ratings_interface').show();
		$('#service_items_container').hide();
		$("#rate_service").hide();
		$("#back_to_ratings_history").show();
	}
}

function showRatingsInterface() {
	$("#duplicate_email_error_widget").hide();
	$("#duplicate_email_error_signup").hide();
	//$("#profile_scrollbar").hide();
	$("#service_items_container").hide();
	$("#rate_service").hide();
	$("#back_to_ratings_history").show();
	loadRatingsInterface(selected_service_id,selected_service_name,null,selected_offer_category, false);
	unblockRatingsInterface(false);
}

function hideRatingsInterface() {
	$("#rate_service").show();
	$("#back_to_ratings_history").hide();
	//$("#profile_scrollbar").show();
	$("#service_items_container").show();
	$("#ratings_interface").hide();
}

//*******************************************************************************************
// Scrolling Behavior
//*******************************************************************************************

function enableMatrixScrollPlugin() {
	
	var panels = $('#scroll_matrix ul li');
	var container = $('#scroll_matrix ul');
	
	container.css('width', panels[0].offsetWidth * panels.length);

	$('#scroll_matrix').serialScroll({
		items:'li',
		prev:'#matrix_table a.prev',
		next:'#matrix_table a.next',
		axis: 'x',
		offset: 0, //when scrolling to photo, stop 230 before reaching it (from the left)
		start:0, //as we are centering it, start at the 2nd
		duration: 300,
		force:true,
		stop:true,
		lock:false,
		cycle:false, //don't pull back once you reach the end
		easing:'easeOutQuart',
		jump: false // don't jump to item on click
	 }); 
	
}

//Easing equation, borrowed from jQuery easing plugin
jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
}; 


/**
 * disable text selection
 **/
(function($){if($.browser.mozilla){$.fn.disableTextSelect=function(){return this.each(function(){$(this).css({"MozUserSelect":"none"})})};$.fn.enableTextSelect=function(){return this.each(function(){$(this).css({"MozUserSelect":""})})}}else{if($.browser.msie){$.fn.disableTextSelect=function(){return this.each(function(){$(this).bind("selectstart.disableTextSelect",function(){return false})})};$.fn.enableTextSelect=function(){return this.each(function(){$(this).unbind("selectstart.disableTextSelect")})}}else{$.fn.disableTextSelect=function(){return this.each(function(){$(this).bind("mousedown.disableTextSelect",function(){return false})})};$.fn.enableTextSelect=function(){return this.each(function(){$(this).unbind("mousedown.disableTextSelect")})}}}})(jQuery)


