/* This is the core Javascript file for all pages. */

(function() {
	
function getBody() {
	return document.getElementsByTagName("body")[0];
}

function setOverlayMask(visible) {
	if (visible) {
		$("#overlay-mask").show();
	} else {
		$("#overlay-mask").hide();
	}
}

function isOverlayVisible(name) {
	return $("#" + name).is(':visible'); 
}
function beginsWith(string, text) {
	var pos = string.indexOf(text);
	if (pos === 0) {
	  return true;
	} else {
	  return false;
	}
}

var activeOverlay_ = null;

function setActiveOverlay(overlay) {
	if (activeOverlay_) {
		hide(activeOverlay_);
	}
	show(overlay);
	activeOverlay_ = overlay;
}

function show_popup(popup_id, check_login) {
	popup_id = "#" + popup_id;
	if(check_login === true || check_login === undefined) {
		ensure_logged_in();
	}
	clearPopupError(popup_id);
	offset=$(window).scrollTop();
	$(popup_id).css('margin-top', 70+offset);
	$('#popup-overlay-mask').fadeIn('fast');
	$(popup_id).fadeIn('fast');
	//centerPopup(popup_id);
	
	$(popup_id + " .first-focus").focus();
	return false;
}
function close_popup() {
	$('#popup-overlay-mask').fadeOut('fast');
	$(".overlay").hide();
}

function _closeOverlay() {
	setOverlayMask(false);
	$("body").removeClass("show-overlay");
	//removeclass(getBody(), "show-overlay");
	close_popup();
}

function closeOverlay(delay) {
	if(delay) {
		window.setTimeout(function() {
			_closeOverlay();
		}, delay);
	} else {
		_closeOverlay();
	}
	
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays===null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name) {
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end === -1) {
				c_end=document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start,c_end));
		}
	  }
	return "0";
}

function isPopupVisible() {
	return $('#popup-overlay-mask').is(":visible");
}


function _show_flash_message(msg, msg_class, msg_timeout) {
	if($(window).scrollTop()>114) {
		$("#flash-message-box").css('position', 'fixed');
		$("#flash-message-box").css('top', "0");
	}

	$("#flash-message-box").show("fast");
	$("#flash-message").attr('class', msg_class);
	$("#flash-message").attr('innerHTML', msg);

	window.setTimeout(function() {
		$("#flash-message-box").hide("fast");
	}, msg_timeout);

}


function flash_success_message(msg) {
	_show_flash_message(msg, 'flash-message-contents', 3500);

}
function flash_error_message(msg) {
	_show_flash_message(msg, 'flash-error-contents', 10000);
}
function showPopupError(message, form_id) {
	if(isPopupVisible()) {
		var filter="#popup-overlay-mask .error-messages, #popup-overlay-mask .flash-messages";
		if($(filter).length>0) {
			$(filter).attr('innerHTML', message);
			$(filter).removeClass('success-message');
			$(filter).addClass('error-message');
			$(filter).show();
		} else {
			alert(message);
		}
	} else if(form_id) {
		var fe = "#" + form_id + "_div .error-messages";
		if($(fe).length) {
			$(fe).attr("innerHTML", message);
			$(fe).show();
		} else {
			flash_error_message(message);
		}
	} else {
		flash_error_message(message);
		//alert(message);
	}
}
function showPopupSuccess(message, form_id) {
	if(isPopupVisible()) {
		var filter="#dynamic-popup-container .flash-messages";
		if($(filter).length>0) {
			$(filter).attr('innerHTML', message);
			$(filter).removeClass('error-message');
			$(filter).addClass('success-message');
			$(filter).show();
		} else {
			flash_success_message(message);
		}
	} else {
		flash_success_message(message);
	}
}

function clearPopupError(form_id) {
	if(typeof(form_id) != "string") {
		return false;
	}
	var filter=form_id + " .error-messages";

	if($(filter).attr('innerHTML')) {
		$(filter).attr('innerHTML', '');
		$(filter).hide();
	}

	filter=form_id + " .flash-messages";
	if($(filter).attr('innerHTML')) {
		$(filter).attr('innerHTML', '');
		$(filter).hide();
	}
	
	filter=form_id + " .error-message";
	if($(filter).attr('innerHTML')) {
		$(filter).attr('innerHTML', '');
		$(filter).hide();
	}
}



function centerPopup(popup_id){
	popup_id = '#' + popup_id;
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $(popup_id).height();
	var popupWidth = $(popup_id).width();
	plog('height ' + popupHeight);

	if(popupHeight<10 || popupWidth<10) {
		return;
	}
	if(popupHeight < 400) {
		popupHeight = 400;
	}
		
	var top = windowHeight/2-popupHeight/2;
	if(top + popupHeight > windowHeight) {
		plog("window " + windowHeight + " too small.." + (top + popupHeight)); 
		top=windowHeight - popupHeight;
	}
	if(top < 0) {
		top = 10;
	}
	plog("top: " + top);
	//centering
	$(popup_id).css({
		"position": "absolute",
		"top": top,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	$("#popup-overlay-mask").css({
		"height": windowHeight
	});

}

function login_redirect(url) {
	ensure_logged_in();
	window.location = url;
}

function ensure_logged_in() {
	if(is_logged_in !== true) {
		
		show_popup('signin-popup', check_login=false);
		$('#signin_form .yellow-box').attr('innerHTML', 'Please login to access this feature');
		$('#signin_form .yellow-box').show();
		
		throw "Login Required";
	}
}

function removeActivityFeedItem(eid) {
	registerAJAXLoadingPopup();
	ensure_logged_in();

	url = '/activity_feed/delete';
	data = 'eid='+ eid;
	$.ajax({
		url:url, 
		type:"POST", 
		dataType: 'json',
		error: ajaxError,
		data:data,
		success:function(data, textStatus) {
				$("#af_" + eid).hide('fast');
			}
	});
	return false;
} 

function removeMessageSingle(msg_this, msg_eid) {
	registerAJAXLoadingPopup();
	ensure_logged_in();

	url = '/message/delete';
	data = 'message_ids=' + msg_eid;
	$.ajax({
		url:url, 
		type:"POST", 
		dataType: 'json',
		error: ajaxError,
		data:data,
		success:function(data, textStatus) {
		 		$(msg_this).parents(".message-entry").hide('fast');
			}
	});
	return false;
} 

function removeMessageThread(msg_this, eid) {
	registerAJAXLoadingPopup();
	ensure_logged_in();
	

	url = '/message/delete_thread';
	data = 'message_id=' + eid;
	$.ajax({
		url:url, 
		type:"POST", 
		dataType: 'json',
		error: ajaxError,
		data:data,
		success:function(data, textStatus) {
				if(msg_this) {
					$(msg_this).parents('.conversation').hide();
				} else {
					document.location="/message/conversations";
				}
			}
	});
	return false;
} 



function reportMessageSpam(eid) {
	registerAJAXLoadingPopup();
	ensure_logged_in();

	url = '/message/report_spam';
	data = 'eid=' + eid;
	$.ajax({
		url:url, 
		type:"POST", 
		dataType: 'json',
		error: ajaxError,
		data:data,
		success:ajaxSuccess
	});
	return false;
} 

function callPublish(msg, attachment, action_link) {
  FB.ensureInit(function () {
    FB.Connect.streamPublish('', attachment, action_link);
  });
}


function XXsubmitCommentSuccess(data, textStatus, form_id) {
	function callPublish(msg, attachment, action_link) {
	  FB.ensureInit(function () {
	    FB.Connect.streamPublish('', attachment, action_link);
	  });
	}

	$('#comments_form_div').attr('innerHTML', 'Comment posted.');
	
	var fbPublish = getCookie("fb_publish");
	if(fbPublish == "") {
		fbPublish = 0;
	}
	
	if(fbPublish % 1 === 0) {
		var title = data.title;
		var href = data.href;
		var description = data.description;
		var img = data.img;
		callPublish('',{'name':title,'href':href,'description':description,'media':[{'type':'image','src':img,'href':img}]},null);
	}
	fbPublish++;
	setCookie("fb_publish", fbPublish);

	return false;
}

function submitComment() {
	registerAJAXLoadingPopup();
	try {
		ensure_logged_in();
		submitAJAXForm('comments_form', '', submitCommentSuccess);
		return false;
	} catch (ex) {
		return false;
	}
}


function submitCommentSuccess(data, textStatus, form_id) {

	$("#" +form_id).parent().attr('innerHTML', '<div class="overlay-tooltip-highlight-msg">Note posted</div>');
}
function removeCommentItem(eid, comment_this) {
	// Used for profile favorite comments
	registerAJAXLoadingPopup();
	ensure_logged_in();

	url = '/comments/do_delete';
	data = 'eid='+ eid;
	$.ajax({
		url:url, 
		type:"POST", 
		dataType: 'json',
		error: ajaxError,
		data:data,
		success:function(data, textStatus) {
				$(comment_this).closest(".comment-entry").hide('fast');
			}
	});
	return false;
} 


function removeInterestItem(eid) {
	registerAJAXLoadingPopup();
	ensure_logged_in();

	url = '/change_interests/delete';
	data = 'eid='+ eid;
	$.ajax({
		url:url, 
		type:"POST", 
		dataType: 'json',
		error: ajaxError,
		data:data,
		success:function(data, textStatus) {
				$("#ii_" + eid).hide('fast');
			}
		});
	return false;
}

function saveInterestChanges() {
	registerAJAXLoadingPopup();
	new_order = $("#sortable").sortable("toArray");
	for (var i=0; i<new_order.length; i++) {
		/* Trim the ii_ part  */
		new_order[i] = new_order[i].substring(3);
	}

	url = '/change_interests/do_edit';
	var fdata={};
	fdata.new_order = new_order;
	
	$.ajax({
		url:url, 
		type:"POST", 
		dataType: 'json',
		data:fdata,
		error: ajaxError,
		success:ajaxSuccess
		});
	return false;

}

function addToFavorites(eid, bthis) {
	registerAJAXLoadingPopup();
	ensure_logged_in();
	
	disableFormID(bthis);
	
	url = '/change_interests/add_interest_eid';
	data = 'eid='+ eid;

	$.ajax({
		url:url, 
		type:"GET", 
		dataType: 'json',
		data:data,
		error: function(XMLHttpRequest, textStatus, errorThrown) {
				ajaxError(XMLHttpRequest, textStatus, errorThrown);
				enableFormID(bthis);
			},
		success:function(data, textStatus) {
				ajaxSuccess(data, textStatus);
				$(bthis).attr('innerHTML', ' Favorite Added.'); 
			}
	});
} 


function showEUIDPopup(popup_id, euid, max_popup_count) {
	max_popup_count = max_popup_count || 0;
	if(max_popup_count > 0) {
	
		popup_count = getCookie(popup_id);
		if(popup_count != '' && popup_count > max_popup_count) {
			show_popup(popup_id);
			$('#' + popup_id + ' :form .user-euid').attr('value', euid);
			$('#' + popup_id + ' :form').submit();
		} else {
			if(popup_count=='') {
				popup_count=0;
			} else {
				popup_count++;
			}
			setCookie(popup_id, popup_count);
		}
	}
	show_popup(popup_id);
	$('#' + popup_id + ' :form .user-euid').attr('value', euid);
}

function disableFormID(form_id) {
	if($(form_id).is('button')) {
		$(form_id).attr('disabled', 'disabled');
	
	} else {	
		var formobj;
		if(typeof(form_id)=="string") {
			formobj = $("#" + form_id) 
		} else{
			formobj = $(form_id); 
		} 
		formobj.children('input:button, input:submit').attr('disabled', 'disabled')
	}
}
function enableFormID(form_id) {
	
	if($(form_id).is('button')) {
		$(form_id).removeAttr('disabled');
	} else {
		var filter=form_id + " :button" + ",#" + form_id + " :submit";
		$(filter).removeAttr('disabled');
	}
}

function ajaxError(XMLHttpRequest, textStatus, errorThrown, form_id) {
	//alert('error: '  + XMLHttpRequest.status + ": " + XMLHttpRequest.getResponseHeader("Content-Type"));
	//alert(XMLHttpRequest.responseText);
	//alert(XMLHttpRequest.getResponseHeader("Content-Type"));
	
	hideLoadingPopup();
	
	if(XMLHttpRequest.status == 500) {
		showPopupError("A server error occured. Please refresh the page and try again.");
	}
	if( XMLHttpRequest.getResponseHeader("Content-Type").indexOf('text/html')>=0 ) {
		$("#" + form_id + "_div").attr('innerHTML',XMLHttpRequest.responseText);
	} else if(XMLHttpRequest.getResponseHeader("Content-Type").indexOf("application/json")>=0){
		try {
			var jr = eval("(" + XMLHttpRequest.responseText + ")");
			if(jr.errorMessage !== undefined) {
				showPopupError(jr.errorMessage, form_id);
			} else {
				showPopupError("An error occured while processing your request", form_id);
			}

		} catch (err) {
			alert("Invalid response received from server.");
			console.log(XMLHttpRequest.responseText);
		}
	} else {
		showPopupError(XMLHttpRequest.responseText, form_id);
	}
	enableFormID(form_id);
}


function ajaxSuccess(data, textStatus, form_id) {
	//alert("success: " + data);
	hideLoadingPopup();
	var autoHidePopup = true;
	
	if(typeof data === "string" && data != '') {
		showPopupSuccess(data, form_id);
	} else if (typeof data === "object") {
		if(data.successMessage !== undefined) {
			showPopupSuccess(data.successMessage, form_id);
		} else if(data.errorMessage !== undefined) {
			alert('Internal Error: ' + data.errorMessage);
		} else if(data.popupHtml !== undefined) {
			autoHidePopup = false;
			$("#dynamic-popup-container").attr("innerHTML", data.popupHtml);
			show_popup('dynamic-popup-container', check_login=false);
		}
		if(data.redirect) {
			window.location = data.redirect;
		} else if(data.reload) {
			window.location.reload();
		}
	}

	if(autoHidePopup && isPopupVisible()) {
		closeOverlay(1500);
	}		
	//enableFormID(form_id);
}

function ajaxCallback(responseText, textStatus, XMLHttpRequest) {
	if(textStatus!='success') {
		alert("Error: " + responseText);
	}
}

function load_dynamic_popup(url, data) {
	$("#dynamic-popup-container").load(url, data);
	show_popup('dynamic-popup-container', check_login=false);
	return false;
}

function fetchAJAXFormResponse(data, textStatus, onLoad) {
	if(data.html) {
		show_popup('dynamic-popup-container', check_login=false);
		$("#dynamic-popup-container").attr('innerHTML', data.html);
		if(onLoad) {
			onLoad();
		}
		$("#dynamic-popup-container .first-focus").focus();
	}
}
function fetchEditProfileForm(url, div_id) {
	registerAJAXLoadingPopup();
	$.ajax({
		url:url, 
		type:"GET", 
		dataType: 'json',
		error: ajaxError,
		success:function(data, textStatus) {
				if(data.html){
					$("#"+div_id).attr("innerHTML",data.html);
					$('#about_me_textarea').maxChar(400);
				} else {
					alert("Invalid response from server, does not contain html.");
				}
				
			}
	});
	return false;	
}

function showLoadingPopup() {
	$('#loading-popup-overlay-mask').show();
	$('#loading-popup').show();
}
function hideLoadingPopup() {
	$('#loading-popup-overlay-mask').hide();
	$("#loading-popup").hide();
}

function registerAJAXLoadingPopup() {
	$("#loading-popup").ajaxStart(function() {
		//showLoadingPopup();
		centerPopup("loading-popup");
		$("#loading-popup").show();
	});
	$("#loading-popup").ajaxStop(function() {
		//hideLoadingPopup();
		$("#loading-popup").hide();
		$("#loading-popup").unbind("ajaxStart");
	});
}

function fetchAJAXPopup(url, onLoad) {
	ensure_logged_in();
	registerAJAXLoadingPopup();
	$.ajax({
		url:url, 
		type:"GET", 
		dataType: 'json',
		error:function(XMLHttpRequest, textStatus, errorThrown) {
					alert("An error occured while performing this action. Please reload the page and try again.");
					closeOverlay(); 
				},
		success:function(data, textStatus) { 
					fetchAJAXFormResponse(data, textStatus, onLoad);
					registerDynamicTooltip();
				}
		}); 
	
	return false;
}

function load_with_indicator(id, url) {
	registerAJAXLoadingPopup();
	$(id).load(url);
	return false;
}

function submitAJAXForm(form_id, url, onSuccess) {
	if(typeof form_id == "string") {
		var sform=$("#"+form_id);
	} else {
		var sform=$(form_id)
	}

	registerAJAXLoadingPopup();
	clearPopupError(form_id);
	disableFormID(form_id);

	if(!url) {
	 url = sform.attr("action");
	}
	
	$.ajax({
		url:url, 
		type:"POST", 
		dataType: 'json',
		data:sform.serialize(),
		error:function(XMLHttpRequest, textStatus, errorThrown) {
					ajaxError(XMLHttpRequest, textStatus, errorThrown, form_id);
				},
		success:function(data, textStatus) {
					if(onSuccess) {
						onSuccess(data, textStatus, form_id);
					} else {
						ajaxSuccess(data, textStatus, form_id);
					}
				}
		});
	return false;
}


function initWebcam() {
	//alert('initWebcam');
	webcam.set_api_url( '/change_thumbnail/do_webcam' );
	webcam.set_quality( 90 ); // JPEG quality (1 - 100)
	webcam.set_shutter_sound( true, "/swf/shutter.mp3" ); // play shutter click sound
	webcam.set_swf_url('/swf/webcam.swf')
	webcam.set_hook('onError', 'webcamError' )
	webcam.set_hook('onLoad', 'webcamLoaded' )
	webcam.set_hook( 'onComplete', 'uploadWebcamComplete' );
}

function loadWebcam() {
	//alert("webcam loading");
	$("#webcam_component").attr('innerHTML', webcam.get_html(320, 240) );
}

function uploadWebcam() {
	// upload to server
	$('#webcam_status').attr('innerHTML', '<h2><img src="/img/loading.gif" style="height: 25px; vertical-align: middle;" />&nbsp;Uploading...</h2>');
	webcam.upload();
}

function uploadWebcamComplete(msg) {
	document.location="/profile"
}

function webcamError(msg) {
	alert("Error: " + msg);
}
function webcamLoaded(msg) {
	$("#capturebtn").removeAttr('disabled')
}

/* PHOTO VIEWER START */

function showPhotoOverlay(username, euid, image_url, image_id) {
	show_popup("photo-overlay", false);
	
	$("#photo-overlay-username").text(username);
	$("#photo-overlay-image").attr("src", image_url);
	$("#photo-overlay-flag-info").hide();
	
	//setActiveOverlay(gel("photo-overlay"));
	
	
	//setOverlayMask(true);
	//show_popup("photo-overlay", false);
	
	var data_map={'euid':euid, 'current_image_id':image_id};
	$("#photo-overlay-nav").load("/photos/overlay_nav", jQuery.param(data_map), ajaxCallback);
}


function showPhoto(index) {
	image_index = index;
	image_url = getPhotoURL(photo_ids[index]);
	$("#photo-overlay-image").attr("src", image_url);
	printPhotoInfo(image_index, euid, photo_ids);
}

function printPhotoInfo() {	
	$("#photo-nav-info-box").text('(' + (image_index+1) + " of " + photo_ids.length + ')');
	curr_photo = photo_ids[image_index];
	
	if(is_logged_in && logged_in_euid == euid) {
		if(image_index>0) {
			$("#manage_photo_form_iid").attr("value", curr_photo);
			
			$("#flag_user_form_div").hide();
			$("#manage_photo_form").show();
			$("#photo_is_thumbnail").hide();
		} else {
			$("#flag_user_form_div").hide();
			$("#manage_photo_form").hide();
			$("#photo_is_thumbnail").show();
		} 
	} else {
		$("#manage_photo_form").hide();
		$("#flag_user_form_div").show();
		$("#photo_is_thumbnail").hide();
		
		$("#flag_photo_form_euid").attr("value", euid);
		$("#flag_photo_form_iid").attr("value", curr_photo);
		
	}
}

function peekIndex(incr_val) {
	var ii=image_index + incr_val;
	if(ii >= photo_ids.length) {
		ii = 0;
	}
	if(ii < 0) {
		ii = photo_ids.length-1;
	}
	return ii;
}

function preLoadPhoto(index) {
	$.get(getPhotoURL(photo_ids[index]));
}

function getPhotoURL(photo_id) {
	var id_str="";
	if(photo_id === 0 || photo_id === "0") {
		id_str = "";
	} else {
		id_str = "_" + photo_id;
	}
	
	var image_url = img_base + "/" + euid + "/m" + id_str + ".jpg";
	return image_url;
}
	
function showNextPhoto() {
	showPhoto(peekIndex(1));
	preLoadPhoto(peekIndex(1));
}

function showPrevPhoto() {
	showPhoto(peekIndex(-1));
	preLoadPhoto(peekIndex(-1));
}

/* PHOTO VIEWER END */
function keyHandler(e) {
	if (e.keyCode == 37) {
		// left
		if(isOverlayVisible('photo-overlay')) {
			showPrevPhoto();
		} 
	} else if (e.keyCode == 39) {
		// right
		if(isOverlayVisible('photo-overlay')) {
			showNextPhoto();
		}
	} else if (e.keyCode == 27) {
		closeOverlay();
	}
}

function toggleTab(tab, card) {
	var tabNode = gel(tab);
	var cardNode = gel(card);

	var tabNodeRoot = tabNode.parentNode;
	for (var i = 0; i < tabNodeRoot.childNodes.length; i++) {
		var tempTabNode = tabNodeRoot.childNodes[i];
		if (tempTabNode.nodeType == 1 /* Element */) {
			if (!hasclass(tempTabNode, "fill")) {
				setclasses(tempTabNode, ["tab"]);
			}
		}
	}
	setclasses(tabNode, ["tab-selected"]);
	
	var cardNodeRoot = cardNode.parentNode;
	for (i = 0; i < cardNodeRoot.childNodes.length; i++) {
		var tempCardNode = cardNodeRoot.childNodes[i];
		if (tempCardNode.nodeType == 1 /* Element */) {
			hide(tempCardNode);
		}
	}
	show(cardNode);

	return false;
}


function CheckAll(chk)
{
	for (i = 0; i < chk.length; i++) {
		chk[i].checked = true ;
	}
}

function UnCheckAll(chk)
{
	for (i = 0; i < chk.length; i++) {
		chk[i].checked = false ;
	}
}


function fb_to_pv_type(dtype) {
	if(dtype.id.indexOf('/tv')>=0) {
		return 'T';
	} else if(dtype.id.indexOf('/music')>=0 || 
			dtype.id.indexOf('musician')>=0 ||
			dtype.id.indexOf('pianist')>=0 ||
			dtype.id.indexOf('singer')>=0) {
		return 'S'; 
	} else if(dtype.id.indexOf('/film')>=0 || 
			dtype.id.indexOf('/actor')>=0) {
		return 'M';
	} else if(dtype.id.indexOf('/book')>=0) {
		return 'B';
	} else if(dtype.id.indexOf('/restaurant')>=0 || 
			dtype.id.indexOf('/food')>=0 ||
			dtype.id.indexOf('/biology')>=0 ||
			dtype.id.indexOf('/business')>=0) {
		return 'F';
	}
	
	//alert("Unknown type " + dtype.id + ", please select one.");
	console.log("Unknown type " + dtype.id);
	return '';
}


function _doScroll(div_id, offset) {
	div_id = "#" + div_id;
	var pos = $(div_id).scrollLeft() + offset;
	
	if(pos < 0) {
		pos = 0;
		stopScrollContinuous();
	}
	
	var max_width = $(div_id + " .scroll-content").width();
	if(pos > max_width) { 
		pos = max_width;
		stopScrollContinuous();
	}
		
	//console.log("div: " + div_id + ", width: " + $(div_id + " .scroll-content").width() + ", offset: " + offset + ", pos: " + pos);			
	$(div_id).animate({scrollLeft: pos}, 200);
}
function doScrollRight(div_id) {
	var offset = offset || 550;
	_doScroll(div_id, offset);
	return false;
}
function doScrollLeft(div_id) {
	var offset = offset || -550;
	_doScroll(div_id, offset);
	return false;
}

var scrolling = false;
function _doScrollLeftContinuous(div_id) {
	if(scrolling) {
		doScrollLeft(div_id);
		setTimeout(function() {_doScrollLeftContinuous(div_id);}, 210);
	}
}
function _doScrollRightContinuous(div_id) {
	if(scrolling) {
		doScrollRight(div_id);
		setTimeout(function() {_doScrollRightContinuous(div_id);}, 210);
	}
}

function doScrollLeftContinuous(div_id) {
	scrolling = true;
	_doScrollLeftContinuous(div_id);
	return false;
	
}
function doScrollRightContinuous(div_id) {
	scrolling = true;
	_doScrollRightContinuous(div_id);
	return false;
}
function stopScrollContinuous() {
	scrolling = false;
}

function registerDynamicTooltip() {
	$('.dynamic-tooltip').each(function() {
		var tturl = $(this).attr('tturl');
		if(!tturl) 
			return;
		
		$(this).btToolTip({
			ajaxPath: ["$(this).attr('tturl')"],
			  width: 320,
			  shrinkToFit: true,
			  fill: '#F7F7F7', 
			  strokeStyle: '#B7B7B7', 
			  spikeLength: 10, 
			  spikeGirth: 10,
			  closeWhenOthersOpen: true,
			  padding: "4px",
			  offsetParent: "body",
			  killTitle: true
			});		
	});

}


$.fn.btToolTip = function(content, options) {
    var postShow = function(box) {
        var tipsource = $(this);
        var monitor = tipsource.add($(box));
        var timer;

        tipsource.data("btdelay.hover", true).data("btdelay.delay", 0);

        var checkRemove = function() {
            var hovered = tipsource.data("btdelay.hover");

            if (hovered) {
                tipsource.data("btdelay.delay", 0);
            } else {
                var delay = tipsource.data("btdelay.delay");
                if (delay<5) {
                    tipsource.data("btdelay.delay", delay+1);
                } else {
                    clearInterval(timer);
                    tipsource.unbind(".btdelay");
                    tipsource.btOff();
                }
            }
        }

        monitor.bind("mouseover.btdelay", function() { tipsource.data("btdelay.hover", true); })
               .bind("mouseleave.btdelay", function() { tipsource.data("btdelay.hover", false); });
        timer=setInterval(checkRemove, 100);
    };

    var opt = (typeof content == "string") ? options : content;
    opt = jQuery.extend(opt, {trigger: "none", postShow: postShow});
    
    return this.each(function(index) {
        var hoverOpts = {
        		interval: 700,
                over : function() { $(this).btOn(); },
                out : function() { }
                };
    
        $(this).bt(content, opt).hoverIntent(hoverOpts);
    });
    
};


/* TOOLTIP SECTION END */



	
function submitPoll() {
	registerAJAXLoadingPopup();
	
	if(!$("#poll-form input[@name='vote']:checked").val()) {
		return false;
	}
	
	$.ajax({
		url:'/poll/do_vote', 
		type:"POST", 
		dataType: 'json',
		data:$("#poll-form").serialize(),
		error:function(XMLHttpRequest, textStatus, errorThrown) {
					ajaxError(XMLHttpRequest, textStatus, errorThrown, "poll-form"); 
				},
		success:function(data, textStatus) { 
					showPollResults(data.epid); 
				}
		}); 
	return false;
}
function showPollResults(epid) {
	load_with_indicator('#poll-box', '/poll/results?epid='+epid);
	return false;
}
	

function submitSearch() {
	var form_items = $('#search-form').find('input,select');
	
	var qstr="";
	for(var i=0; i<form_items.length; i++) {
		var val = form_items[i].value;
		var name = form_items[i].name;
		if(!val || val == "") { continue; }
		if(name == 'submit')  { continue; }
		if(name == 'zipcode' && val == 'Zip Code')  { continue; }
		if(name == 'interest' && (val== "${g.DEFAULT_FAVORITE_TEXT[0]}" || val == "${g.DEFAULT_FAVORITE_TEXT[1]}")) { continue; }
		if(name == 'age' && val == 'Z')  { continue; }
		
		qstr = qstr + "&" + form_items[i].name + "=" + form_items[i].value;
	}

	var filters = $('#search-filters').find('select');
	
	for(var i=0; i<filters.length; i++) {
		var val = filters[i].value;
		var name = filters[i].name;
		if(!val || val == "" || val=="-") { continue; }
		qstr = qstr + "&" + filters[i].name + "=" + filters[i].value;
	}
	
	loc= "/search/do_search?"+qstr;
	window.location=loc;
	return false;
}

function plog(sval) {
	console.log(sval);
}

$(window).load(function() {
	$(document).keydown(keyHandler);
});

window["submitPoll"] = submitPoll;
window["showPollResults"] = showPollResults;


window["printPhotoInfo"] = printPhotoInfo;
window["showNextPhoto"] = showNextPhoto;
window["showPrevPhoto"] = showPrevPhoto;
window["showPhotoOverlay"] = showPhotoOverlay;

window["closeOverlay"] = closeOverlay;
window["fetchAJAXPopup"] = fetchAJAXPopup;
window["submitAJAXForm"] = submitAJAXForm;
window["showPopupError"] = showPopupError;
window["load_dynamic_popup"] = load_dynamic_popup;
window["show_popup"] = show_popup;
window["close_popup"] = close_popup;
window["toggleTab"] = toggleTab;
window["addToFavorites"] = addToFavorites;
window["removeActivityFeedItem"] = removeActivityFeedItem;
window["submitComment"] = submitComment;
window["submitCommentSuccess"] = submitCommentSuccess;
window["removeCommentItem"] = removeCommentItem;
window["removeInterestItem"] = removeInterestItem;

window["initWebcam"] = initWebcam;
window["uploadWebcamComplete"] = uploadWebcamComplete;
window["loadWebcam"] = loadWebcam;
window["uploadWebcam"] = uploadWebcam;
window["webcamLoaded"] = webcamLoaded;
window["webcamError"] = webcamError;

window["removeMessageSingle"] = removeMessageSingle;
window["removeMessageThread"] = removeMessageThread;
window["reportMessageSpam"] = reportMessageSpam;

window["saveInterestChanges"] = saveInterestChanges;
window["ensure_logged_in"] = ensure_logged_in;
window["CheckAll"] = CheckAll;
window["UnCheckAll"] = UnCheckAll;
window["beginsWith"] = beginsWith;
window["fb_to_pv_type"] = fb_to_pv_type;
window["submitSearch"] = submitSearch;
window["login_redirect"] = login_redirect;

window["registerAJAXLoadingPopup"] = registerAJAXLoadingPopup;
window["doScrollRight"] = doScrollRight;
window["doScrollLeft"] = doScrollLeft;
window["doScrollLeftContinuous"] = doScrollLeftContinuous;
window["doScrollRightContinuous"] = doScrollRightContinuous;
window["stopScrollContinuous"] = stopScrollContinuous;

window["showEUIDPopup"] = showEUIDPopup;
window["registerDynamicTooltip"] = registerDynamicTooltip;
window["fetchEditProfileForm"] = fetchEditProfileForm;
window["load_with_indicator"] = load_with_indicator;

})();




(function($) {
	$.fn.clearOnFocus = function() {
		
		function clearOnFocusFocus(event)
		{
			if($(this).val() == $(this).data('clearOnFocus'))
			{
				$(this).val('');
			}
		}
		
		function clearOnFocusBlur(event)
		{
			if($.trim($(this).val()) == '')
			{
				$(this).val($(this).data('clearOnFocus'));
			}
		}
		
		return this.each(function()
			{
				$(this).data('clearOnFocus', $(this).attr('value'));
				
				//	unbind any previous listeners
				$(this).unbind('focus', clearOnFocusFocus);
				$(this).unbind('blur', clearOnFocusBlur);
				
				//	bind listeners to the functions
				$(this).bind('focus', clearOnFocusFocus);
				$(this).bind('blur', clearOnFocusBlur);
			}
		);
	};
})(jQuery);



(function($) {

	function validateFavoriteForm(maindiv) {
		var n = $(maindiv).find("input:radio:checked").length;
		var f = $(maindiv).find(".suggest-text").val();

		console.log("n=" + n + "f=" + f)
		if(n>=1 && f!=null && f.length>0) {
			$(maindiv).find(".add_submit_button").removeAttr('disabled');
			console.log('validatng')
			return true;
			
		} else {
			console.log('not validatng');
			
			$(maindiv).find(".add_submit_button").attr('disabled', 'disabled');
		  	$(maindiv).find(".add-favorite-radios").show();
			$(maindiv).find(".add_submit_button").show();
		}
		return false;

	}
	function validateAndSubmitFavoriteForm(maindiv) {
		if(validateFavoriteForm(maindiv)) {
			$(maindiv).find(".add-favorite-form").submit();
		}
	}

	function registerSuggestBox(maindiv) {

		$(maindiv).find('.suggest-text').suggest(suggest_types)
		  	.bind("fb-select", function(e, data) 
		  		{
	  				console.log('fb-select');
		  			var ptype = fb_to_pv_type(data['n:type']);
		  			console.log("selected type " + ptype)
		  			
		 			$(maindiv).find(".radio_" + ptype).attr('checked', 'checked');
		  			$(maindiv).find(".fav_external_key").attr('value', data.guid);
		  			validateAndSubmitFavoriteForm(maindiv);
		  		})
		  	.bind("fb-required", function(e, data) 
		  		{
		  			console.log('fb-required ');
		  			validateFavoriteForm(maindiv);
		  		})
			.bind("fb-select-new", function(e, data) 
				{
	  			console.log('fb-select-new');
	  			$(maindiv).find(".fav_external_key").attr('value', "");
	  			$(maindiv).find(".add-favorite-radios").show();
	  			validateAndSubmitFavoriteForm(maindiv);
	  		});
	  	
	  	$(maindiv).find('input:radio').bind("click", function() {validateFavoriteForm(maindiv)});
	}
	
	$.fn.registerFavoriteForm = function() {
		return this.each(function() {
			
			registerSuggestBox(this);
			$(this).find('form').bind('submit', function() {
					validateAndSubmitFavoriteForm(this);
					});
		});
	};
})(jQuery);
