var error_fields;
var nav_call_in_progress = false;
var messageTabPeriodical;
var vipTabPeriodical;
var confirmationdialog;
var advanced_search_initialized = false;
var current_tab;

function nav(controller,action,params,historycall)
{
	if(nav_call_in_progress)
	{
		return false;
	}
	
	nav_call_in_progress = true;

	//Get rid of the help popup if it's showing
	removeHelpPopup(); 
	
	//Take care of tab highlighting
	var revClass = (current_tab == 'main_tab_subscribe')?'subscribe_tab':'main_tab';

	//New
	previous_tab = current_tab;
	previous_tab_old_classname = $(previous_tab).className;

	$(current_tab).className = revClass;
	
	var mainTabs = new Array();
	var tabDividers = $$('#mainnav .tab_divider');
	tabDividers.each(function(el, index)
	{ 
		if(index >= 1 && index <= (tabDividers.length - 2)) 
		{
			el.setProperty('src', '/images/mainnav_divider.gif');
		}
		else if(index == 0)
		{
			el.setProperty('src', '/images/mainnav_divider_left.gif');
			el.setStyle('width', '1px');
		}
		else
		{
			el.setProperty('src', '/images/mainnav_divider_right.gif');
			el.setStyle('width', '1px');
		}
	});
	
	var prevDivider = $('main_tab_'+controller).getPrevious();
	var nextDivider = $('main_tab_'+controller).getNext();
	if(controller == 'home')
	{
		prevDivider.setProperty('src', '/images/mainnav_leftcap_home.gif');
		prevDivider.setStyle('display', '');
		prevDivider.setStyle('width', '3px');
	}
	else if(controller == 'subscribe')
	{
		prevDivider.setProperty('src', '/images/mainnav_leftcap_subscribe.gif');
	}
	else
	{
		prevDivider.setProperty('src', '/images/mainnav_leftcap.gif');
	}
	if(controller == 'subscribe')
	{
		nextDivider.setProperty('src', '/images/mainnav_rightcap_subscribe.gif');
		nextDivider.setStyle('display', '');
		nextDivider.setStyle('width', '3px');
	}
	else
	{
		nextDivider.setProperty('src', '/images/mainnav_rightcap.gif');
	}
	
	//alert('Previous Tab: ' + previous_tab + ' | Current Tab: main_tab_' + controller);
	//alert(mainTabs[0]);
	//var currentTabIndex = mainTabs.indexOf('main_tab_'+controller);
	//alert(currentTabIndex);
	
	updateTitle(controller, action);
	var newClass, activeTab;
	if($('main_tab_'+controller))
	{
		//New
		new_tab = 'main_tab_'+controller;
		new_tab_old_classname = $(new_tab).className;

		newClass = (controller == 'subscribe')?'subscribe_activetab':'main_activetab';
		$('main_tab_'+controller).className = newClass;
		current_tab = 'main_tab_'+controller;
		activeTab = current_tab;
	}
	else
	{
		//New
		new_tab = 'main_tab_'+current_controller;
		new_tab_old_classname = $(new_tab).className;

		//this is for online stats in home and my profile
		var bits = current_tab.split('_');
		var current_controller = bits[2];
		newClass = (current_controller == 'subscribe')?'subscribe_activetab':'main_activetab';
		$('main_tab_'+current_controller).className = newClass;
		activeTab = 'main_tab_'+current_controller;
	}

	//highliting messages
	if(activeTab == 'main_tab_messagecentre')
	{
		hiliteMessagesTab('stop'); 
	}
	else 
	{
		if( msgCounts>0 && $('main_tab_messagecentre').getStyle('color') =='#cccccc' )
		{
			//alert('start from other tab');
			hiliteMessagesTab('start'); 
		}			
	}	
	
	//highliting vip
	if(activeTab == 'main_tab_vip')
	{
		hiliteVipTab('stop'); 
	}
	else 
	{
		if( vipCounts>0 && $('main_tab_vip').getStyle('color') =='#cccccc' )
		{
			//alert('start from other tab');
			hiliteVipTab('start'); 
		}			
	}	
	
	$('right_column').style.display = "none";
	$('processing_page').style.display = 'block';
	
	var timestamp = new Date();
	var url, historyurl;
	if(params==undefined)
	{
		url = "/member/"+controller+"/"+action+"?"+"from_ajax=true&navcall=true&ietimestamp=" + timestamp.getTime();
		historyurl = controller+"/"+action;
	}
	else
	{
		url = "/member/"+controller+"/"+action+"?"+params+"&from_ajax=true&navcall=true&ietimestamp=" + timestamp.getTime();
		historyurl = controller+"/"+action+"?"+params;
	}
	new Ajax(url,{method: 'get', autoCancel: 'true', onComplete: function(t){
		nav_call_in_progress = false;
		$('processing_page').style.display = 'none';
		if(t.indexOf('ERROR|',0)>=0)
		{
			current_tab = previous_tab;
			$(new_tab).className = new_tab_old_classname;
			$(previous_tab).className = previous_tab_old_classname;

			var bits = t.split('|');
			var destination_url = bits[1].trim();
			historynav(destination_url,true);
		}
		else if(t.indexOf('TOPERROR|',0)>=0)
		{
			//Handle redirect on session error
			var bits = t.split('|');
			var destination_url = bits[1];
			window.location = destination_url;
		}
		else
		{
			$('right_column').style.display = "block";
			$('right_column').innerHTML = t.toString();
			previous_location = window.historyStorage.get(dhtmlHistory.getCurrentLocation());
			if(historycall==null)
			{
				dhtmlHistory.add(""+timestamp.getTime(),historyurl);
			}
			pngfix();
		}
	}, evalScripts: true}).request();
	
	// UPDATE GOOGLE ADSENSE IFRAME(S)
	$$('.googlead').each(function(el){
		el.src = el.src + '&s=' + timestamp.getTime();
	});
}

function historynav(historyurl, addHist)
{
if (!historyurl)
	return;
	var bits = historyurl.split("?");
	if(bits.length==2)
	{
		var params = bits[1];
	}

	var littlebits = bits[0].split("/");
	var controller = littlebits[0];
	var action = littlebits[1];
	if (addHist)	// for swf
		nav(controller,action,params);
	else
		nav(controller,action,params,true);	
}
function backToResults()
{
	var lists = Array("search/result", "vip/index", "hotlist/index", "profileviews/index", "blocklist/index", "messagecentre/index", "home/index");
	var keys = new Array();
	var hashtable = window.historyStorage.storageHash;
    for (var i in hashtable) {
        if (hashtable[i] != null)
            keys.push(i);
    }
    var url, key, listindex;
    var found = false;
    while (key = keys.pop()) {
    	url= ""+window.historyStorage.get(key);
    	for (listindex=0; listindex<lists.length;listindex++)
			if (url.indexOf(lists[listindex]) >= 0)
	    		return historynav(url, true);
 	    url = null;
 	    key = null;
    }
    keys = null;
}
function permissionsajax(controller,action,params)
{
	var timestamp = new Date();
	var url;
	if(params==undefined)
	{
		url = "/member/"+controller+"/"+action+"?"+"from_ajax=true&ietimestamp=" + timestamp.getTime();
	}
	else
	{
		url = "/member/"+controller+"/"+action+"?"+params+"&from_ajax=true&ietimestamp=" + timestamp.getTime();
	}
	return_request = new Ajax(url,
	{
		method: 'get',
		onComplete: function(t)
		{
			t = t.trim();
			if(t.indexOf('ERROR|',0)>=0)
			{
				var bits = t.split('|');
				var destination_url = bits[1].trim();
				historynav(destination_url,true);
			}
		},
		evalScripts: true
	}).request();
}

function status_change(controller,action,id,object_id,success_string,image_id,success_class)
{
	if(typeof image_id == 'undefined'){ image_id = 0; success_class = 0;}
	var timestamp = new Date();
	var url = "/member/"+controller+"/"+action+"?from_ajax=true&id="+id+"&ietimestamp=" + timestamp.getTime();
	return_request = new Ajax(url,
	{
		method: 'get',
		onComplete: function(response)
		{
			response = response.trim();
			if(response == '1')
			{
				$(object_id).innerHTML = success_string;
				if(image_id != 0 && success_class != 0)
				{
					$(image_id).setProperty('class', success_class);
				}
			}
			else if(response.indexOf('POPERROR|',0)>=0)
			{
				//Handle popup on permissions error
				var bits = response.split('|');
				var destination_url = bits[1].trim();
				showPopup(destination_url);
			}

		},
		evalScripts: true
	}).request();
}

function blocklist(id)
{
	var object_id = 'blocklist_'+id;
	var el = $('subnav_total_blocklist');
	if($(object_id).innerHTML.trim()=="Block")
	{
		confirmationdialog = new ConfirmPopup({ message:'Are you sure you want to Block', 
																 onConfirm:function (){ 
																		status_change('blocklist','add',id,object_id,"Unblock",'icon_blocklist_'+id,'unblock');
																			if (el && parseInt(el.innerHTML)>=0) el.innerHTML = parseInt(el.innerHTML)+1;
																}	
															});
		confirmationdialog.show();		
	}
	else
	{
		confirmationdialog = new ConfirmPopup({ message:'Are you sure you want to Unblock', 
																 onConfirm:function (){ 
																		status_change('blocklist','remove',id,object_id,"Block",'icon_blocklist_'+id,'block');
																		if (el && parseInt(el.innerHTML)>=0) el.innerHTML = parseInt(el.innerHTML)-1;
																}	
															});
		confirmationdialog.show();		
	}
}

function hotlist(id)
{
	var object_id = 'hotlist_'+id;
	if($(object_id).innerHTML.trim()=="Add to Hotlist")
	{
		confirmationdialog = new ConfirmPopup({ message:'Are you sure you want to Add to Hotlist?', 
																 onConfirm:function (){ 
																		status_change('hotlist','add',id,object_id,"Remove from Hotlist",'icon_hotlist_'+id,'hotlist_remove');
																		if ($('subnav_total_hotlist') && parseInt($('subnav_total_hotlist').innerHTML)>=0)
																			$('subnav_total_hotlist').innerHTML = parseInt($('subnav_total_hotlist').innerHTML)+1;
																 }	
															});
		confirmationdialog.show();		
	}
	else
	{
		confirmationdialog = new ConfirmPopup({ message:'Are you sure you want to Remove from Hotlist?', 
																 onConfirm:function (){ 
																				
																			status_change('hotlist','remove',id,object_id,"Add to Hotlist",'icon_hotlist_'+id,'hotlist');
																			if ($('subnav_total_hotlist') && parseInt($('subnav_total_hotlist').innerHTML)>0)
																				$('subnav_total_hotlist').innerHTML = parseInt($('subnav_total_hotlist').innerHTML)-1;
																}	
															});
		confirmationdialog.show();		
	}
}

function requestvip(id)
{
	var object_id = 'requestvip_'+id;
	if($(object_id).innerHTML.trim()=="Request VIP Access")
	{
		confirmationdialog = new ConfirmPopup({ message:'Are you sure you want to Request VIP Access?', 
											 onConfirm:function (){ 
													response = status_change('vip','request',id,object_id,"VIP Request Pending",'icon_requestvip_'+id,'vip_pending');
													if ($('vip_requestsbyme_pending') && parseInt($('vip_requestsbyme_pending').innerHTML)>=0)
														$('vip_requestsbyme_pending').innerHTML = parseInt($('vip_requestsbyme_pending').innerHTML)+1;
											}	});
		confirmationdialog.show();			
	}
}

function grantvip(id)
{
	var object_id = 'grantvip_'+id;
	if($(object_id).innerHTML.trim()=="Grant VIP Request")
	{
		confirmationdialog = new ConfirmPopup({ message:'Are you sure you want to Grant VIP Request?', 
											 onConfirm:function (){ 
			
													status_change('vip','grant',id,object_id,"Revoke VIP",'icon_grantvip_'+id,'vip_revoke');
													if ($('vip_requeststome_pending') && parseInt($('vip_requeststome_pending').innerHTML)>=0){
														$('vip_requeststome_pending').innerHTML = parseInt($('vip_requeststome_pending').innerHTML)-1;
														new_message_notification_request();
													}	
													if ($('vip_requeststome_approved') && parseInt($('vip_requeststome_approved').innerHTML)>=0)
														$('vip_requeststome_approved').innerHTML = parseInt($('vip_requeststome_approved').innerHTML)+1;
											}	});
		confirmationdialog.show();											
	}
	else
	{
		if($(object_id).innerHTML.trim()=="Give VIP")
		{
			confirmationdialog = new ConfirmPopup({ message:'Are you sure you want to Give VIP Access?', 
											 onConfirm: function (){ 
		
													status_change('vip','give',id,object_id,"Revoke VIP",'icon_grantvip_'+id,'vip_revoke');
													
													if ($('vip_requeststome_approved') && parseInt($('vip_requeststome_approved').innerHTML)>=0)
														$('vip_requeststome_approved').innerHTML = parseInt($('vip_requeststome_approved').innerHTML)+1;
											}	});
			confirmationdialog.show();		
		}
		else
		{
			confirmationdialog = new ConfirmPopup({ message:'Are you sure you want to Revoke VIP Access?', 
											 onConfirm: function (){ 
													status_change('vip','revoke',id,object_id,"Give VIP",'icon_grantvip_'+id,'vip_give');
													
													if ($('vip_requeststome_approved') && parseInt($('vip_requeststome_approved').innerHTML)>=0)
														$('vip_requeststome_approved').innerHTML = parseInt($('vip_requeststome_approved').innerHTML)-1;
											}	});
			confirmationdialog.show();	
		}
	}
}

function historyChange(newLocation, historyData) {
	if((newLocation!='undefined')&&(newLocation!='')&&(newLocation!==undefined))
	{
		historynav(historyData);
	}
}

function update_message_counts(request)
{
			request = request.trim();
			if(request.indexOf('TOPERROR|',0) == 0)
			{
				//var alert = new LogoutPopup({message: 'Your session has timed out due to inactivity. You will now be logged out.'});
				window.location = "/member/login";
				//alert.show();
			}
			else{
				var cs = request.split('!');
				var counts = cs[0].split('|');
				msgCounts = parseInt(counts[0])+parseInt(counts[1]);
				if(msgCounts==0)
				{
					$('main_tab_messagecentre').innerHTML = "Messages";
				}
				else
				{
					$('main_tab_messagecentre').innerHTML = "Messages ("+cs[0]+")";
					
					//if message tab is not active, flash it
					if($('main_tab_messagecentre').getStyle('color') =='#ffffff' && $('main_tab_messagecentre').className == 'main_tab' )
					{
						//alert('start from update message counts');
						hiliteMessagesTab('start');
					}	
				}
				
				if(cs[1]=='0')
				{
					vipCounts = 0;
					$('main_tab_vip').innerHTML = "Vip List";
				}
				else
				{
					vipCounts = parseInt(cs[1]);
					$('main_tab_vip').innerHTML = "Vip List ("+cs[1]+")";
					
					//if message tab is not active, flash it
					if($('main_tab_vip').getStyle('color') =='#ffffff' && $('main_tab_vip').className == 'main_tab' )
					{
						//alert('start from update message counts');
						hiliteVipTab('start');
					}	
				}
			}
}


function hiliteMessagesTab(request){
	if(request=='start')
	{
		msgfx();
		messageTabPeriodical = msgfx.periodical(2000);
	}
	else
	{
		$clear(messageTabPeriodical);
		msgeffect.stop();
		$('main_tab_messagecentre').setStyle('color', '');
		$('main_tab_messagecentre').setProperty('class', 'main_activetab');
	}
}

function hiliteVipTab(request){
	if(request=='start')
	{
		vipfx();
		vipTabPeriodical = vipfx.periodical(2000);
	}
	else
	{
		$clear(vipTabPeriodical);
		vipeffect.stop();
		$('main_tab_vip').setStyle('color', '');
		$('main_tab_vip').setProperty('class', 'main_activetab');
	}
}

function new_message_notification_request()
{
	var timestamp = new Date();
	return_request = new Ajax("/member/messagecentre/newmessagecount?from_ajax=true&ietimestamp=" + timestamp.getTime(),{method: 'get', onComplete: update_message_counts, evalScripts: true}).request(null);
}


function updateProfilePic() {
	if ($('profile_photo_img')) {
		$('profile_photo_img').src = "/member/media/profilephotolg?ts="+new Date().getTime();
	}
}

function check_elements()
{
	resetvalues();
	reset_others();
	var current = '';
	var previous = '';
	var x = 0;
	var y = 0;
	
	setItems = $$('input','search_form');
		setItems.each(function(e)
			{
				var name = e.id;
				switch(e.type)
				{
					case 'text':					
						break;
					case 'checkbox':
						if(name.match("basic_option_sex"))
						{
							if(x == 0)
								resetvalues();
							
							if(e.checked == false)
							{
								x++;
							}
							else
							{
								if(x <= 2)
								{
									x++;
									y++;
									e.onchange();
									
								}
								
							}
							
							if(x > 2 && y == 0)
							{
								e.onchange();
							 	resetvalues();
							}							
						}
						else
						{
							if(e.checked == true )
							{
								if(typeof e.onchange == 'function')
								{
							       e.onchange();
								}
							}						
						}
					break;
					case 'radio':
						if(e.checked == true)
						{
							if(typeof e.onchange == 'function')
							{
							       e.onchange();
							}
						}
					break;
				}
		});
		//alert('after check input: '+parent_options['search_filters_option_parent']);
		selectItems = $$('select','search_form');
		selectItems.each(function(e){
			var name = e.name;
			if(e.value != 0)
			{				
				if(!name.match("zip_radius|city_id"))
				{					
					e.onchange();
				}
			}
		});
}

var previous_location = "";

function send_message(id)
{
	$('send_form').send({
		onComplete: function(response)
		{
			response = response.trim();
			if(response == '1')
			{
				historynav(previous_location,true);
			}
			else
			{
				$(id+'_btn').setStyle('display', 'block');
				$(id+'_processing').setStyle('display', 'none');
				
				$('error_shell').setStyle('display','');
				$('error_list').innerHTML = "<ul>"+response+"</ul>";
			}
		},
		evalScripts: true
	});
}

function deletemessage(msgid,action) 
{ 
	confirmationdialog = new ConfirmPopup({message: "Are you sure you want to delete this message?", onConfirm: function (){
		var deleteit = new Ajax("/member/messagecentre/deletemsg?id="+msgid,{
			method: 'get', 
			onComplete:function(){nav('messagecentre', action);}, 
			evalScripts: true
			}).request();
		}});
	confirmationdialog.show();
}

function toggle_page(page_count){
	for( i=1; i<=page_count; i++){
		el = $('edit_account_shell_'+i);
		if( i == $('cur_page').value )
		{
			el.setStyles({display: 'block'});
		}
		else
		{		
			el.setStyles({display: 'none'});
		}	
	}
	return;
}

function increase_page(page_count){
	$('cur_page').value = parseInt($('cur_page').value)+1;
}

function decrease_page(page_count){
	$('cur_page').value = parseInt($('cur_page').value)-1;
}

function delete_checked(checker,action)
{
	var the_form = $('check_all').form;
	confirmationdialog = new ConfirmPopup({message: "Are you sure you want to delete the selected messages?", onConfirm: function (){
		for(i=0; i<the_form.length;i++)
		{
			if(the_form[i].type == 'checkbox' && the_form[i].name != 'check_all' && the_form[i].checked == true)
				deletemessagesimple(the_form[i].value);
		}
		nav('messagecentre', action);
		
		//update message counts
		new_message_notification_request();
	}});
	confirmationdialog.show();
}

function deletemessagesimple(msgid)
{
	var deleteit = new Ajax("/member/messagecentre/deletemsg?id="+msgid,{
		method: 'get', 
		evalScripts: true
		}).request(); 
}

function clear_text()
{
	if(!bit)
	{
		e = document.getElementById('message_text');
		e.value = '';
	}
	bit=true;
}
function show(id)
{
	e = document.getElementById(id);
	e.style.display = e.style.display=='none'?'':'none';
}

function send_reply()
{
	$('reply_form').send({
		onComplete: function(response) 
		{
			response = response.trim();
			if(response == '1')
			{
				nav('messagecentre','index');
			}
			else if(response.indexOf('ERROR|',0)>=0)
			{
				var bits = response.split('|');
				var destination_url = bits[1].trim();
				historynav(destination_url,true);
			}
			else
			{
				$('error_shell').setStyle('display','');
				$('error_list').innerHTML = "<ul>"+response+"</ul>";
			}
		},
		evalScripts: true
	});
}

function submitIndex(form,page){
	var serialized = $(form).toQueryString();
	var url = "/signup/profile/validate?page="+page+"&"+serialized;
	
	return_request = new Ajax(url,
	{
		method: 'get',
		onComplete: function(response)
		{
			response = response.trim();
			if(response == '')
			{
				$('error_shell').setStyle('display', 'none');
				$(form).submit();
			}
			else
			{
				$('error_shell').setStyle('display', '');
				$('error_list').innerHTML = "<ul>"+response+"</ul>";
			}
		},
		evalScripts: true
	}).request();
}

function showPopup(url, offset) 
{ 
	if (offset==undefined)
		offset = 200;

	$('popup_content').innerHTML='';
	$('popup_content').setStyle('visibility', 'hidden');
   	//resizeMask();
	var fullHeight = getScrollHeight();
	var fullWidth = getScrollWidth();
	var containerWidth;
	if($('container'))
	{ 
		containerWidth = $('container').getSize().x;
		if (containerWidth==undefined)
		{
			containerWidth = $('container').offsetWidth;
		}

	}
	else
	{
		containerWidth = $('container_small').getSize().x;
		if (containerWidth==undefined)
		{
			containerWidth = $('container_small').offsetWidth;
		}
	}
	
	var wrapperOffset = Math.round((fullWidth - containerWidth)/2 - 1);
	$('wrapper').setStyle('margin-left', wrapperOffset);
	$('popup_container').setStyle('height', fullHeight+'px');	
	if (window.ie6==true) {
		$('popup_inner').setStyle('position', 'absolute');
		$('popup_inner').setStyle('top', (getScrollTop())+'px');
	} else {
		$('popup_inner').setStyle('top', offset+'px');
	}
	var timestamp = new Date();
	if(url.indexOf('?') != -1)
	{
		url = url + "&ietimestamp=" + timestamp.getTime();
	} else {
		url = url + "?ietimestamp=" + timestamp.getTime();
	}

	new Ajax(url,{
		method: 'get',
		update: $('popup_content'),
		evalScripts: true,
		onComplete: function(response){
			$('popup_container').setStyle('display','block');
			if(window.ie6 == true){
				$('popup_content').setStyle('top', '200px');	
			}
			$('popup_content').setStyle('visibility', 'visible');
		}
	}).request();
}

function showHelpPopup(url, id, leftorright) 
{
	var xpos = $(id).getPosition().x;
	xpos =  ($('container'))?xpos - $('container').getPosition().x:xpos - $('container_small').getPosition().x;
	var ypos = $(id).getPosition().y;
	
	$('help_popup_shell').innerHTML = '';
	$('help_popup_shell').setStyle('margin-top','-1000px');
	
	var timestamp = new Date();
	if(url.indexOf('?') != -1)
	{
		url = url + "&ietimestamp=" + timestamp.getTime();
	} else {
		url = url + "?ietimestamp=" + timestamp.getTime();
	}
	
	var helpInner = new Element('div', {'class':'help_popup_inner_'+leftorright,'id':'help_popup_inner'}).injectInside('help_popup_shell');
	if(window.ie6 == true){			
		helpInner.setProperty('class', 'help_popup_inner_noshadow');
		var spacer = new Element('img', {'src':'/images/blank.gif'});
		spacer.setStyle('position', 'relative').injectInside(helpInner);
	}
	var helpConnector = new Element('div', {'class':'help_connector_'+leftorright}).injectInside(helpInner);
	var helpPopup = new Element('div', {'class':'help_popup_'+leftorright,'id':'help_popup'}).injectAfter(helpConnector);
	new Ajax(url,{
		method: 'get',
		update: $('help_popup'),
		evalScripts: true,
		onComplete: function(){
			xpos = (leftorright=='left')?xpos-$('help_popup').getSize().size.x-20:xpos+10;
			helpInner.setStyles({top:ypos-13+'px',left:xpos+'px', width:$('help_popup').getSize().size.x+'px'}).injectInside('help_popup_shell');	
			$('help_popup_shell').setStyle('margin-top','0px');
		}
	}).request();
	
	var hideTimer = setTimeout(removeHelpPopup, 8500);
	$('help_popup_shell').addEvent('mouseleave', function(e){
		e = new Event(e).stop();
		hideTimer = setTimeout(removeHelpPopup, 8500);
	});
	$('help_popup_shell').addEvent('mouseenter', function(e){
		hideTimer = $clear(hideTimer);
	});
	
}

function removeHelpPopup(){
	$('help_popup_shell').innerHTML = '';
	$('help_popup_shell').setStyle('margin-top','-1000px');
}
	

function hidePopup() {
	$('popup_content').innerHTML='';
	$('popup_container').setStyle('display','none');
	$('wrapper').setStyle('margin','0 auto');
}

function resizeMask()
{	
	$('popup_mask').setStyles({height: Window.getScrollHeight()+'px'});
}

/**
 * Take a count of checked fields and if it's <= 3 update the read-only textfield, if it = 3 let's disable other fields.
 */	

function checkOptionCount (field, div){
	//alert(field+" | "+div);
	var checkCount = 0;
	var divlist = $(div).getElements('input');
	divlist.each(function(e){
		if(e.checked==true){
			//alert(e.id);
			checkCount++;
		}
	});
	if(checkCount == 3){
		divlist.each(function(e){
			if(e.checked!=true){
				e.disabled=true;
			}
		});
	}
	else{
		divlist.each(function(e){
			if(e.checked!=true){
				e.disabled=false;
			}
		});
	}
	if(checkCount <= 3 && field != null){
		updateTextField(field, div);
	}
}

function updateTextField(field, div){
	
	//reset field to nothing
	$(field).setProperty('value','');
	
	//get all the input fields in the div 'div'
	var divlist = $(div).getElements('input');
	
	//collect all the label value for each checked input box
	var value = '';
	divlist.each(function(e){
		if(e.checked==true){
			var text = $(e.id + '_label').innerHTML.replace(/\&amp;/g, "&");
			value = value + $(field).getProperty('value')+', '+text;
		}
	});
	
	//remove leading comma and space
	value = value.substr(2); 
	
	//update the field 'field' value
	$(field).setProperty('value',value);
	$(field).setProperty('title',value);
}

/**
 * Load options for the field 
 *
 * @param int options_rows - total options rows in the page
 * @param String option - the div id of the options container
 * @param String cont - the index of the options row, also is the last digit of the divs which are related to the option row
 * @param int x - the left offset of the tab.
 */
function openOptions(options_rows, option,cont,x) {
	
	//hide all the other option rows
	for(i=1; i<=options_rows; i++){
		if(i!=cont){
			var alternate = $('signup_options_cont'+i);
			alternate.setStyle('display', 'none');
		}	
	}
	
	var tab = $('signup_options_connector'+cont);
	var elem = $('signup_options_cont'+cont);
	var inner_elem = $('signup_options_table'+cont);
	var src = $(option);
	var divlist = $(inner_elem).getElements('div');
	
	//make all the divs in the option container invisible
	divlist.each(function(e){
		e.setStyle('display', 'none');
	});
	
	tab.setStyle('left', x);
	elem.setStyle('position', 'relative');
	elem.setStyle('opacity', 1);
	src.setStyle('opacity',1);
	elem.setStyle('display', 'block');
	src.setStyle('display','block');
	
	checkOptionCount(null,option);
	/*
	var elemFx = elem.effects({duration: 0, wait:false});
	elemFx.start({ 'opacity': [0,1] });
	var srcFx = src.effects({duration: 0, wait:false});
	
	srcFx.start({ 'opacity': [0,1] });
	*/
}
/**
 * Hide all options rows when edit other fields
 *
 * @param int options_rows - total options rows in the page
 */
function hideOptions(options_rows)
{
	//hide all the option rows	
	for(i=1; i<=options_rows; i++){
		var alternate = $('signup_options_cont'+i);
		alternate.setStyle('display', 'none');
	}
}

function save_search(value)
{
	hidePopup();
	var search_form = $('search_form').toQueryString();
	new Ajax("/member/search/savesearch?searchname="+value+'&'+search_form,{
		method: 'get', 
		update: $('saved_search'),  
		onComplete: list_saved, 
		evalScripts: true
		}).request();
}

var new_search_onclick=0;
var zip_toggle=0;
var city_toggle=0;

function load_saved(searchid)
{
	new Ajax("/member/search/getsearchformtab?saved_search_id="+searchid,{method: 'get', update: $('new_search'),  onComplete: function(t){ accordionator();ajax_search('search_form', 0, 10);}, evalScripts: true}).request();
	
	$('new_search_tab').className = 'activetab';
	$('saved_search_tab').className = 'tab';
	$('saved_search').style.display='none';
	$('new_search').style.display='block';
}

function list_saved()
{
	$('saved_search').style.display = 'block';
	$('saved_search_tab').className = 'activetab';
	$('new_search_tab').className = 'tab';
	$('new_search').style.display='none';
}

function show_new_search()
{
	$('saved_search').style.display = 'none';
	$('saved_search_tab').className = 'tab';
	$('new_search_tab').className = 'activetab';
	$('new_search').style.display='block';
	
	if(advanced_search_initialized==false)
	{
		accordionator();
		advanced_search_initialized=true;
	}
}
	
/***********************
**
**
**
***********************/
function ajax_search(formname, start, limit)
{
	var serialized = $(formname).toQueryString();
	serialized+="&search_name=Advanced+Search";
	if(formname=='search_form')
	{
		nav('search','result',serialized);
	}
	else
	{
		nav('search','fullprofile',serialized);
	}
}

/***********************
**
**
**
***********************/

function delete_search(searchid,count)
{
	var update_request = new Ajax("/member/search/deletesavedsearch?del_id="+searchid,{method: 'get', update: $('saved_search'), evalScripts: true}).request();
}
function populateStates(countryid,stateid,cityid)
{
	var update_request = new Ajax(
			"/member/search/populatestates?countryid="+countryid+"&stateid="+stateid,
			{ method: 'get', 
				update: 'state_select', 
				onComplete: function()
				{
					if($('basic_option_location_radio_state').checked == true)
						$('basic_option_location_city').setProperty('disabled','');
					populateCity(stateid,cityid,countryid);
				},
				evalScripts: true
			}
		).request();
}
function populateCity(stateid,cityid, countryid)
{
	if (undefined==countryid)	countryid='';
	var update_request = new Ajax(
			"/member/search/populatecities?stateid="+stateid+"&cityid="+cityid+"&countryid="+countryid,
			{ method: 'get', 
				update: 'city_select', 
				onComplete: function()
				{
					if($('basic_option_location_radio_state').checked == true)
						$('basic_option_location_city').setProperty('disabled','');
				},
				evalScripts: true
			}
		).request();
}

function clear_form()
{
	
	setItems = $$('input','search_form');
		setItems.each(function(e){
			switch(e.type)
			{
			case 'text':
				if(e.id != 'basic_option_location_zip')
					e.setProperty('value','');
			break;	
			case 'checkbox':
				e.setProperty('checked','');
			break;
			case 'radio':
				e.setProperty('checked','nopref');
				if((e.id == 'by_match') || (e.id == 'by_location'))
				e.setProperty('checked','');
			break;
			}
		});
		selectItems = $$('select','search_form');
		selectItems.each(function(e){
			var select_name = e.id;			
			if(!select_name.match('^basic_option_location_(zip_radius|state|city)$'))
				e.selectedIndex=0;
		});
	checkItems = $$('#search_form img.check_img');
		checkItems.each(function(e){
		e.setStyle('visibility','hidden')
		});

	resetvalues();
}

function resetvalues()
{
	options['basic_option_parent']['basic_option_sex_item']=0;
	options['basic_option_parent']['basic_option_agerange_item']=0;
	options['basic_option_parent']['basic_option_location_item']=0;
	options['basic_option_parent']['basic_option_height_item']=0;
	options['basic_option_parent']['basic_option_body_type_item']=0;
	options['basic_option_parent']['basic_option_style_item']=0;
	options['basic_option_parent']['basic_option_looks_item']=0;
	options['basic_option_parent']['basic_option_eyes_item']=0;
	options['basic_option_parent']['basic_option_ethnicity_item']=0;
	options['basic_option_parent']['basic_option_looking_for_item']=0;
	options['basic_option_parent']['basic_option_relationship_status_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_smokes_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_drinks_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_diet_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_exercise_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_politics_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_religion_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_education_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_occupation_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_income_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_living_situation_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_have_kids_item']=0;
	options['lifestyle_option_parent']['lifestyle_option_want_kids_item']=0;
	options['personality_option_parent']['personality_option_sexually_into_item']=0;
	options['personality_option_parent']['personality_option_romantically_into_item']=0;
	options['personality_option_parent']['personality_option_description_item']=0;
	options['personality_option_parent']['personality_option_humour_item']=0;
	options['personality_option_parent']['personality_option_music_item']=0;
	options['personality_option_parent']['personality_option_movies_item']=0;
	options['personality_option_parent']['personality_option_activities_item']=0;
	options['personality_option_parent']['personality_option_sports_item']=0;
		
	parent_options['basic_option_parent'] = 0;
	parent_options['lifestyle_option_parent'] = 0;
	parent_options['personality_option_parent'] = 0;
	
	location_toggle=0;
}

function reset_others()
{
	options['search_filters_option_parent']['search_filters_option_has_photo_item']=0;
	options['search_filters_option_parent']['search_filters_option_has_video_item']=0;
	options['search_filters_option_parent']['search_filters_option_has_audio_item']=0;
	options['search_filters_option_parent']['search_filters_option_is_online_item']=0;
	options['search_prefs_option_parent']['search_prefs_option_by_match_item']=0;
	options['search_prefs_option_parent']['search_prefs_option_by_location_item']=0;
		
	parent_options['search_filters_option_parent'] = 0;
	parent_options['search_prefs_option_parent'] = 0;
}	

function togglecheck(elem, parent, item)
{
	curParent = parent + '_parent';
	curParentCheck = parent + '_parent_check';
	curSearchItem = item + '_item';
	curItemCheck = item + '_check';
	//alert('was '+parent_options['search_filters_option_parent']);
	if(elem.checked==true)
	{
		increase_check(curParent, curSearchItem);
	}
	else
	{	
		decrease_check(curParent, curSearchItem);
	}
	//alert(item);
	//alert(parent_options['search_filters_option_parent']);
	showchecks(curParent, curParentCheck, curSearchItem, curItemCheck)
}

function toggleselect(elem, parent, item)
{
	curParent = parent + '_parent';
	curParentCheck = parent + '_parent_check';
	curSearchItem = item + '_item';
	curItemCheck = item + '_check';
	if(elem.value!=0 && parseInt(elem.value) != 0)
	{
		increase_check(curParent, curSearchItem);
	}
	else
	{
		decrease_check(curParent, curSearchItem);
	}
	
	showchecks(curParent, curParentCheck, curSearchItem, curItemCheck);
}
function toggleradio(elem, parent, item)
{
	curParent = parent + '_parent';
	curParentCheck = parent + '_parent_check';
	curSearchItem = item + '_item';
	curItemCheck = item + '_check';
	
	//radio buttons for disabling fields in the location div
	var curItemZip = $$('#'+item+'_zip, #'+item+'_zip_radius');
	var curItemCity = $$('#'+item+'_city, #'+item+'_state, #'+item+'_country');

	if(zip_toggle == 0  && city_toggle == 0)
		parent_options[curParent]++;
	
	switch(elem.value)
	{
		case 'zip':
			curItemCity.setProperty('disabled','disabled');
			curItemZip.setProperty('disabled','');
			zip_toggle = 1;
			options[curParent][curSearchItem]=1;
		break;
		case 'city':
			curItemZip.setProperty('disabled','disabled');
			curItemCity.setProperty('disabled','');
			city_toggle = 1;			
			options[curParent][curSearchItem]=1;
		break;
		case 'nopref':
			curItemZip.setProperty('disabled','disabled');
			curItemCity.setProperty('disabled','disabled');
			city_toggle = 0;			
			zip_toggle = 0;
						
			if(parent_options[curParent] > 0) 
				parent_options[curParent]--;
			else if(parent_options[curParent] < 0)
				parent_options[curParent] = 0;
			options[curParent][curSearchItem]=0;
		break;		
	}
	
	showchecks(curParent, curParentCheck, curSearchItem, curItemCheck);
}

function toggleradiosearch(elem, parent, item, offitem)
{
	curParent = parent + '_parent';
	curParentCheck = parent + '_parent_check';
	curSearchItem = item + '_item';
	curItemCheck = item + '_check';
	offItemCheck = offitem + '_check';
	
	if(elem.checked==true)
	{
		increase_check(curParent, curSearchItem);
		$(offItemCheck).setStyle('display','none');
		$(offItemCheck).setStyle('visibility','hidden');
	}
	else
	{	
		decrease_check(curParent, curSearchItem);
	}
	
	showchecks(curParent, curParentCheck, curSearchItem, curItemCheck)
}

function togglenopref(elem, parent, item)
{
	curParent = parent + '_parent';
	curParentCheck = parent + '_parent_check';
	curSearchItem = item + '_item';
	curItemCheck = item + '_check';
	
	searchItems = $ES('input',item);
	
	searchItems.each(function(e){
		if(elem!=e)
		{
			//alert('e is not nopref');
			if(elem.checked==true)
			{ 
				//alert('nopref checked');
				if(e.checked==true){
					//alert('e checked. --');
					decrease_check(curParent, curSearchItem);
				}	
				e.setProperty('disabled','disabled');
			}	
			else
			{
				//alert('nopref not checked');
				if(e.checked==true){
					increase_check(curParent, curSearchItem);
				}	
				e.setProperty('disabled','');
			}	
		}	
	});	
	
	showchecks(curParent, curParentCheck, curSearchItem, curItemCheck);
}

function increase_check(curParent, curSearchItem)
{
	parent_options[curParent]++;
	options[curParent][curSearchItem]++;	
}

function decrease_check(curParent, curSearchItem)
{
	if(parent_options[curParent] > 0)
		parent_options[curParent]--;
	else if(parent_options[curParent] < 0)
		parent_options[curParent] = 0;
		
	options[curParent][curSearchItem]--;	
}

function showchecks(curParent, curParentCheck, curSearchItem, curItemCheck)
{
	if(parent_options[curParent] > 0)
	{	
		$(curParentCheck).setStyle('display','block');
		$(curParentCheck).setStyle('visibility','visible');
	}
	else
	{
		$(curParentCheck).setStyle('display','none');
		$(curParentCheck).setStyle('visibility','hidden');
	}
	
	if(options[curParent][curSearchItem] > 0)
	{
		$(curItemCheck).setStyle('display','block');
		$(curItemCheck).setStyle('visibility','visible');
	}
	else
	{
		$(curItemCheck).setStyle('display','none');
		$(curItemCheck).setStyle('visibility','hidden');
	}
}


function hilite_errors(name, elements)
{	
	clear_hilite_errors();
	
	for(x=0;x<elements.length;x++)
	{
		var textbox = name + '_' + elements[x];
		var label = 'label_' + name + '_' + elements[x];
		
		if($(textbox))
			$(textbox).className = "error_textbox";			
		
		if($(label))
			$(label).className = "error_fieldname";
	}
}

function clear_hilite_errors()
{
	elements = getElementsByClassName("error_textbox","*",document);
	for(x=0;x<elements.length;x++)
	{
		var textbox = elements[x];
		$(textbox).className = "textbox";
	}
		
	elements = getElementsByClassName("error_fieldname","*",document);
	for(x=0;x<elements.length;x++)
	{
		var label = elements[x];
		$(label).className = "fieldname";
	}	
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	tag = tag || "*";
	elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}	
	}
	return returnElements;
}


function toggleSection(id){
	var vis = $(id).getStyle('display');
	var toggle = id+'_toggle';
	if(vis == 'none')
	{
		$(id).setStyle('display', 'block');
		$(toggle).setProperty('src', $(toggle).getProperty('src').replace('open', 'close'));
	}
	else
	{
		$(id).setStyle('display', 'none');
		$(toggle).setProperty('src', $(toggle).getProperty('src').replace('close', 'open'));
	}
}

// Function for hiding/showing processing spinner and message for button clicks
function showProcessing(id){
	if($(id+'_processing').getStyle('display') == 'none')
	{
		$(id+'_btn').setStyle('display', 'none');
		$(id+'_processing').setStyle('display', 'block');
	}
	else
	{
		$(id+'_btn').setStyle('display', 'block');
		$(id+'_processing').setStyle('display', 'none');
	}
}
function showSubmitButtons(){
	$$('.processing_spinner').each(function(el){ el.setStyle('display', 'none');});
	$$('.pos_action_btn').each(function(el){ el.setStyle('display', 'block');});
}



function updateTitle(controller, action){
	var pageSection = '';
	var pageSubsection = '';
	switch(controller){
		case 'home':
			pageSection = "Member Home";
			break;
		case 'search':
			pageSection = "Search Results";
			break;
		case 'dailymatches':
			pageSection = "Daily Matches";
			break;
		case 'myprofile':
			pageSection = "My Profile";
			break;
		case 'messagecentre':
			pageSection = "Message Center";
			break;
		case 'hotlist':
			pageSection = "My Hotlist";
			break;
		case 'vip':
			pageSection = "My VIP List";
			break;
		case 'profileviews':
			pageSection = "My Viewed List";
			break;
		case 'blocklist':
			pageSection = "My Block List";
			break;
		case 'subscribe':
			pageSection = "Subscribe Today";
			break;
	}
	switch(action){
		case 'index':
			if(controller == "messagecentre"){
				pageSubsection = "Messages Inbox";
			}
			else if(controller == "profileviews"){
				pageSubsection = "Viewed By Me";
			}
			else{
				pageSubsection = "";
			}
			break;
		case 'result':
		case 'restrictedsearch':
			pageSubsection = "";
			break;
		case 'display':
			pageSubsection = "View Profile";
			break;
		case 'fullprofile':
			pageSubsection = "View Profile";
			break;
		case 'media':
			pageSubsection = "View Media";
			break;
		case 'edit':
			pageSubsection = "Edit My Profile";
			break;
		case 'kisses':
			pageSubsection = "Kisses Inbox";
			break;
		case 'kissessent':
			pageSubsection = "Kisses Sent";
			break;
		case 'emailsent':
			pageSubsection = "Messages Sent";
			break;
		case 'pendingrequeststome':
			pageSubsection = "Incoming Pending VIP Requests";
			break;
		case 'approvedrequeststome':
			pageSubsection = "Incoming Approved VIP Requests";
			break;
		case 'pendingrequestsbyme':
			pageSubsection = "Outgoing Pending VIP Requests";
			break;
		case 'approvedrequestsbyme':
			pageSubsection = "Outgoing Approved VIP Requests";
			break;
		case 'viewedbyme':
			pageSubsection = "Viewed By Me";
			break;
		case 'viewedme':
			pageSubsection = "Viewed Me";
			break;
		case 'editaccount':
			pageSubsection = "My Account Settings";
			break;
		case 'view':
			pageSubsection = "View Message";
			break;
		case 'viewsent':
			pageSubsection = "View Sent Message";
			break;
		case 'send':
			pageSubsection = "Send Message";
			break;
		case 'sendkiss':
			pageSubsection = "Send Kiss";
			break;
		case 'undefined':
		case undefined:
			pageSubsection = "";
			break;
	}
	pageSubsection = (pageSubsection != "")?'/' + pageSubsection:'';
	document.title = pageSection + pageSubsection + ' - LoveIsSexy.com';
}

function embedChatSwf(swf_id, session_hash, profile_id, destination_id, room_name) {
	var so = new SWFObject('/lisChat.swf', ''+swf_id+'', '260', '300', '9', '#FFFFFF');
	so.addVariable('login_cookie', ''+session_hash+'');
	so.addVariable('profile_id', ''+profile_id+'');
	so.addVariable('target_profile_id', ''+destination_id+'');
	so.addVariable('room', ''+room_name+'');
	//so.useExpressInstall('expressinstall.swf');
	so.addParam('wmode', 'transparent');
	so.addParam('scale', 'noscale');
	so.addParam('salign', 't');
	so.write(swf_id);
}

function chatRequest(profile_id, info)
{
	var url = "/member/chat/sendrequest?profile_id="+profile_id;
	var update_request = new Ajax(url,
		{ method: 'get', 
			onComplete: function(response)
			{
				if(response=="1")
				{
					createChatTab(profile_id, info);
				}
			},
			evalScripts: true
		}
	).request();
}

function upChatRequest()
{
	var timestamp = new Date();
	var url = "/member/chat/checkrequests?ietimestamp=" + timestamp.getTime();
	var update_request = new Ajax(url,{method: 'get', evalScripts: true}).request();
}

function createChatTab(profile_id, info){
	var chatTabs = getChatTabs();
	
	if($('chat_tab_'+profile_id))
	{
		return;
	}
	else
	{
		var newChatTab = new Element('td', {
			'id': 'chat_tab_'+profile_id,
			'class':'chat_tab'
		});
						
		var newChatWin = new Element('div', {
			'id': 'chat_win_'+profile_id,
			'class':'chat_win'					
		});			
		
		setTabWidth(newChatTab);
		newChatTab.injectInside($('chat_tabs_row'));
		newChatTab.innerHTML = '<div id=\'chat_session_container_'+profile_id+'\' class=\'chat_session_container\'><div id=\'chat_win_container_'+profile_id+'\' class=\'chat_win_container\'></div><div id=\'chat_tab_container_'+profile_id+'\' class=\'chat_tab_container\'><div class=\'chat_close\'></div><div id=\'user_'+profile_id+'\' class=\'chat_user\'>'+info+'</div></div></div>';
		newChatWin.injectTop($('chat_win_container_'+profile_id));
		showChat('chat_win_container_'+profile_id);
		$('chat_sessions').innerHTML = "Chat Sessions: "+getChatTabs().length;
		$('chat_tab_container_'+profile_id).addEvent('click', function(){
			if(isChatOpen('chat_tab_'+profile_id)){
				setTabWidth('none');
			}
			else{
				setTabWidth('chat_tab_'+profile_id);
			}
			showChat('chat_win_container_'+profile_id, 'none');
		});
		initChat(profile_id, info);
	}
}

function initChat(profile_id, info){
	var url = "/member/chat/displaychat?profile_id="+profile_id;
	var update_request = new Ajax(url,
		{ method: 'get',
		onComplete: function(response)
		{
			//alert(response);
			$('chat_win_'+profile_id).innerHTML = response;
		},
		evalScripts: true
		}
	).request();
}

function isChatOpen(el){
	if($(el).hasClass('active')){
		return true;
	}
	else{
		return false;
	}
}

function setTabWidth(activeTab){
	var chatTabs = getChatTabs();
	var fullWidth, numTabs;
	if(activeTab != 'none'){
		fullWidth = 833-148;
		numTabs = getChatTabs().length-1;
	}
	else{
		fullWidth = 833;
		numTabs = getChatTabs().length;
	}
	
	if((getChatTabs().length-1) >= 1){
		var chatTabWidthTemp = (fullWidth/numTabs);
		if(chatTabWidthTemp >= 148){
			chatTabWidth = 0;
		}
		else{
			chatTabWidth = Math.floor(chatTabWidthTemp);
		}
	}
	else{
		chatTabWidth = 0;
	}
	if(chatTabWidth > 0){
		chatTabs.each(function(el){
			el.setStyle('width', chatTabWidth+'px');
			el.removeClass('active');
		});
		if(activeTab != 'none'){
			$(activeTab).setStyle('width', '148px');
			$(activeTab).addClass('active');
		}
	}
	else{
		chatTabs.each(function(el){
			el.removeClass('active');
		});
		if(activeTab != 'none'){
			$(activeTab).addClass('active');
		}
	}
}

function getChatTabs(){
	var chatTabs = $$('#chat_tabs_row .chat_tab');
	return chatTabs;
}

function showChat(id, target){
	if(target && target == 'none' && $(id).getStyle('top') == '0px'){
		$(id).setStyle('top','1000px');
	}
	else{
		$$('.chat_win_container').each(function(el){
			if(el.id != id){
				el.setStyle('top','1000px');
			}
			else{
				el.setStyle('top','0px');	
			}
		});
	}
}

function createDropLists(list, droptarget, clonetarget){
	$ES('li', $(list)).each(function(el){
		// ONMOUSEDOWN CREATE A CLONE AND MAKE IT DROPPABLE
		el.addEvent('mousedown', function(e) {
			e = new Event(e).stop();
		
			// CREATE A CLONE FOR DRAGGING
			var clone = this.clone()
				.setStyles({
					'left': this.getCoordinates().left - $(clonetarget).getCoordinates().left,
					'top': this.getCoordinates().top
				})
				.setStyles({'position': 'absolute', 'z-index': '200'})
				.addEvent('emptydrop', function() {
					this.remove();
					$(list).setOpacity(1);
					el.setStyle('display', '');
				}).inject($(clonetarget))
				.addClass('listdrag_option');;
			el.setStyle('display', 'none');
			
			// DIM OTHER OPTIONS
			$(list).setOpacity(.3);
			
			// MAKE THE CLONE DRAGGABLE
			var drag = clone.makeDraggable({
				droppables: $ES('div.dropzone', $(droptarget))
			});
			
			$ES('div.dropzone', $(droptarget)).each(function(el){
				el.removeEvents();
			})
			
			$ES('div.dropzone', $(droptarget)).each(function(drop){
				//alert('asdf');
				drop.addEvents({
					'drop': function() {
						clone.remove();
						$(list).setOpacity(1);
						var listarea = drop.id+'_listarea';
						var cloned = el.clone();
						$E('.droplist_item_rightcap', cloned).remove();
						cloned.removeClass('listdrag_option');
						cloned.setProperty('id', cloned.id+'_clone');
						cloned.inject($(listarea));
						var hilite = new Fx.Styles($(listarea), {duration:1000, wait:false});
						$(listarea).setStyle('background-color', '#ffffd9');
						(function(){ hilite.start({'background-color': '#fafcfa'}); }).delay(500);
						cloned.setStyle('display', '');						
						
						var closer = new Element('div', {
							'id': cloned.id+'_close',
							'class': 'droplist_remove'
						});
						
						//el.setStyle('display', 'none');
						closer.injectInside(cloned);
						closer.setProperty('onclick', 'removeDropListItem(\''+el.id+'\', \''+drop.id+'\', \''+el.title+'\', \''+cloned.id+'\');');
						closer.innerHTML = '';
						
						if($(drop.id+'_text').value == ''){
							$(drop.id+'_text').value = "'"+cloned.title+"'";
							
						}
						else{
							$(drop.id+'_text').value += ", '"+cloned.title+"'";
						}
						drop.setStyle('background-color', '#f5ebf4');
					},
					'over': function() {
						drop.setStyle('background-color', '#f0e3ef');
					},
					'leave': function() {
						drop.setStyle('background-color', '#f5ebf4');
					}
				});
			});
			
			// MANUALLY START THE DRAG
			drag.start(e);
		});
	});
}

function removeDropListItem(el, drop, title, cloned){
	$(el).setStyle('display', '');
	var myarray = $(drop+'_text').value.split(', ');
	myarray.remove("'"+title+"'");
	$(cloned).remove();
	$(drop+'_text').value = myarray.join(', ');
}

function removeDropList(drop){
	$ES('.droplist_remove', $($(drop).id+'_listarea')).each(function(el){
		var o_el = el.id.replace('_clone_close', '');
		var clone_el = el.id.replace('_close', '');
		$(o_el).setStyle('display', '');
		$(clone_el).remove();
		$(drop+'_text').value = '';
	});
}

function checkCharCount(id, maxchars, update){
	if($(id).value.length > maxchars){
		$(id).value = $(id).value.substring(0, maxchars);
	};
	if(update){
		$(id.replace('_text', '')).innerHTML = (maxchars - $(id).value.length)+' Remaining';
	}
}

function sr_private_save(type, set_private)
{
	var url = "/member/myprofile/updatequestions?update="+type+"&private="+set_private;	
	return_request = new Ajax(url,
	{
		method: 'post',
		onComplete: function(response)
		{
			response = response.trim();
		},
		evalScripts: true
	}).request();
}

function sr_submit_form(form)
{
	var serialized = $(form).toQueryString();
	var url = "/signup/profile/updatequestions";
	
	return_request = new Ajax(url,
	{
		method: 'post',
		data: serialized,
		onComplete: function(response)
		{
			response = response.trim();
			window.location = "/signup/profile/"+response;			
		},
		evalScripts: true
	}).request();
}

function im_fb_user(profile_id)
{
	confirmationdialog = new ConfirmPopup({ message:'This user is not currently connected to the IM network. Would you like to send a message instead?', 
																 onConfirm:function (){ 
																		nav('messagecentre','send','recipient_id='+profile_id);
																}	
															});
		confirmationdialog.show();
}

function confirm_survey_complete(profile_id, stype)
{
	if (profile_id == undefined || stype == undefined)
		return;
	
	var msg = "You have not completed your "+stype+" profile so we can't display match details.  Click \"Yes\" to complete your profile now or click \"No\" to view username's profile without match details.";
	confirmationdialog = new ConfirmPopup(
															{ message: msg, 
																onConfirm:function (){ 
																 	if(stype=='romantic')
																		nav('myprofile','edit','page=edit_romantic_personality1');
																	else if(stype=='sexual')
																		nav('myprofile','edit','page=edit_sexual_personality1');
																},	
																onCancel:function (){
																	nav('search', 'display', 'id='+profile_id+'&tab='+stype );	
																}
															});
		confirmationdialog.show();
}

// SHOW DETAILS SUB-SECTION
function show_subdetails(section, id, editsection){
	var tabcontainer = section+"_subnav";
	var tabs = $(tabcontainer).getElements('a.subtab');
	var curtab = $('subtab_'+section+"_"+id);
	var sections = $(section+"_subsection").getElements('div.subdetails_section');
	var cursection = $('subdetails_'+section+"_"+id);
	var editlinkid = "edit_"+section+"_link";
	var editlink = "nav('myprofile', 'edit', 'page="+editsection+"'); return false;"
	
	// Make all tabs inactive
	tabs.each(function(el){
		if(el.hasClass('active')){
			el.removeClass('active');
			el.addClass('inactive');
		}
	});
	
	// Set new tab to active
	curtab.removeClass('inactive');
	curtab.addClass('active');
	
	// Make all sections hidden
	sections.each(function(el){
		if(el.hasClass('show')){
			el.removeClass('show');
			el.addClass('hide');
		}
	});
	
	// Set new section visible
	cursection.removeClass('hide');
	cursection.addClass('show');
	
	// Update the edit link to match the section
	$(editlinkid).setProperty('onclick', editlink);
}

function change_location()
{
	if($('location_na') && $('location_na').checked)
	{
		$('label_profile_zip').innerHTML = 'Zip/Postal:'			
		$('div_profile_zip').setStyle('display','block');
		$('div_profile_city').setStyle('display','none');
		if($('international_message_shell'))
			$('international_message_shell').setStyle('display', 'none');
		
		$('profile_city_id').value = 0;
		$('profile_state_id').value = 0;
		$('suggestions').innerHTML = "";
	}
	/*
	else if($('location_int').checked)
	{
		$('label_profile_zip').innerHTML = 'City/Town:'
		$('div_profile_zip').setStyle('display','none');
		$('div_profile_city').setStyle('display','block');
		if($('international_message_shell'))
			$('international_message_shell').setStyle('display', 'block');
	}*/
}

function suggestcityname(city_name)
{	
	if(city_name)
	{
		var url = "/signup/profile/suggestcityname?city="+city_name+"&sid="+Math.random();
		return_request = new Ajax(url,
		{
			method: 'get',		
			onComplete: function(response)
			{
				if(response){
					response = response.trim();
					$('suggestions_shell').setStyle('display','block');
					$('suggestions').innerHTML = response;
				}
				else{
					$('suggestions_shell').setStyle('display','none');
				}
			},
			evalScripts: true
		}).request();
	}
	else
	{
		$('profile_city_id').value = 0;
		$('profile_state_id').value = 0;
		$('suggestions').innerHTML = "";
	}
}

function suggestcorrect(city_id, state_id, city_name) 
{	
	$('profile_city_id').value = city_id;
	$('profile_state_id').value = state_id;
	$('profile_city').value = city_name;
	$('suggestions_shell').setStyle('display','none');
}

//function blursuggestcity(id){
	
