// Global JS Object for AOL Personals
var personals ={
	// Intialization function based on various pages
	init : function(param){
		switch (param)
		{
			case 'main':

				var leftCol = $('div.leftCol');
				var minage = 25, maxage = 45;

				// Main Page man woman selection
				leftCol.find("a.clsGender").bind('click', function(){
					if ($(this).hasClass('clsMan')){
						$(this).addClass("selectedM").siblings().removeClass("selectedW");

						if ($(this).hasClass('seeker')){
							$(this).parents("form:eq(0)").find("input[name='sgender']").val("male");
						}
						else{
							$(this).parents("form:eq(0)").find("input[name='gender']").val("male");
						}
					}
					else{
						$(this).addClass("selectedW").siblings().removeClass("selectedM");

						if ($(this).hasClass('seeker')){
							$(this).parents("form:eq(0)").find("input[name='sgender']").val("female");
						}
						else{
							$(this).parents("form:eq(0)").find("input[name='gender']").val("female");
						}
					}
				});

				// Friendly Input for the text Box
				//leftCol.find("div.singles_search input.txtBox").val(userData.userLocation);
				friendlyInput("div.singles_search input.txtBox");

				// On form Submit go to singles finder
				leftCol.find("div.singles_search form").submit(function(){
					var obj = this;
					var userInput = $(obj).find('input.txtBox').val();
					
					// Is the user clicking without changing ?
					if($(obj).find('input.txtBox').val() == 'City, State Or Zip Code')
					{
						showError($(obj).find('input.txtBox'));
						return false;
					}

					// did we already find a location?
					if($(obj).data('done') == true)
						return true;
										
					// Call to get the correct location
					$.getJSON('/getLocation',{'where' : userInput}, function(response){						
						if(response.zip != '')
						{
							$(obj).find('input[name="zip"]').val(response.zip);
							// Setting city and state values for omniture
							$(obj).find('input[name="state"]').val(response.stateAB);
							// Did we really get a City, State or just the state name itself
							if(response.place.split(",").length > 1){
								$(obj).find('input[name="city"]').val(response.place.split(",")[0]);
							}

							$(obj).data('done',true); 
							setCookie('srchPrfs',$(obj).find('input[name="sgender"]').val() + '||'+$(obj).find('input[name="gender"]').val()+'||'+$(obj).find('input[name="minage"]').val()+'||'+$(obj).find('input[name="maxage"]').val()+'||'+ userInput ,7);
							obj.submit();			
						}
						else
						{
							showError($(obj).find('input.txtBox'),'Please Enter A Valid Location');
						}
					});

					return false;
				});

				//Initialize the page with the default value of location of the user
				personalsAPI.call('partner=match&minage=25&maxage=35&gender=female&sgender=male&num=20&zipCode=' + userData.userZip, "#singlesnear div.container", 
					function(){ $('#singlesnear').infiniteCarousel('> div').find('h4').html('Singles Near ' + userData.userLocation); });
				
				// Tab feature for tabbed modules
				leftCol.find('#datingsvcs ul.tabs li').click(function (event){
				//bN.click(event);

					// remove selected classes from siblings
					$(this).siblings().removeClass('active activefirstcorner activelastcorner hover hoverfirstcorner');

					// add respective class, could be done in a simpler way but IE6 doesn't support joined css classes
					if ($(this).hasClass('firstcorner'))
						$(this).addClass('activefirstcorner active');
					else if ($(this).hasClass('lastcorner'))
						$(this).addClass('activelastcorner active');
					else
						$(this).addClass('active');

					// Element with the suitable index is displayed
					var index = $(this).parent().children().index(this);
					leftCol.find("#datingsvcs div.tab_contents_container > div:eq(" + index + ")").addClass('tab_contents_active').siblings().removeClass('tab_contents_active');

				});

				//Bind the tab hover functions for dating services
				leftCol.find("#datingsvcs ul.tabs li").hover(function(){
					// remove selected classes from siblings
					$(this).siblings().removeClass('hover hoverfirstcorner');

					// add respective class, could be done in a simpler way but IE6 doesn't support joined css classes
					if ($(this).hasClass('firstcorner'))
						$(this).addClass('hoverfirstcorner');
					else
						$(this).addClass('hover');
				}, function(){
					// remove selected classes from siblings
					$(this).removeClass('hover hoverfirstcorner').siblings().removeClass('hover hoverfirstcorner');
				});

				// Set user preferences based on previous search settings
				var settings = getCookie('srchPrfs').split('||');
				if (settings == "")
				{
					settings = new Array("male","female","25","45","City, State Or Zip Code");
				}
				if(settings.length == 5)
				{
					if(settings[0] == 'male')
						leftCol.find('a.seeker.clsMan').click();
					else
						leftCol.find('a.seeker.clsWoman').click();
					
					if(settings[1] == 'male')
						leftCol.find('a.seeking.clsMan').click();
					else
						leftCol.find('a.seeking.clsWoman').click();

					minage = settings[2];
					maxage = settings[3];
					//leftCol.find('input.txtBox').val(settings[4]);
				}

				// Age Slider function to set the values of form fields based on the user input
				leftCol.find("div.singles_search input[name='minage']").val(minage);
				leftCol.find("div.singles_search input[name='maxage']").val(maxage);
				leftCol.find('h2.ageRange:eq(0)').html(minage);
				leftCol.find('h2.ageRange:eq(1)').html(maxage);

				// slider function on the slider
				$('#slider').slider({
					slide: function(event, ui){ 
						var values = $('#slider').slider('option', 'values');
						var elements = leftCol.find('h2.ageRange');

						// Change the age headings
						$(elements[0]).html(values[0]);
						$(elements[1]).html(values[1]);
						
						// Set the values in hiddne fields
						leftCol.find("div.singles_search input[name='minage']").val(values[0]);
						leftCol.find("div.singles_search input[name='maxage']").val(values[1]);
					},
					max: 99,
					min:18,
					range: true,
					values: [minage, maxage]
				});

			break;

			case 'cchart':

				var tempchart = $("ul.cchart");

				// Autofix cell heights on same columns for entire chart
				tempchart.find("ul.ccindex li").each(function(i){
					var thisheight = $(this).outerHeight() - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'));
					// IE6 fix
					$(this).height(thisheight);
					tempchart.find("li.ccitem li:nth-child("+(i+1)+")").each(function(){ 
						$(this).height(thisheight);
					});  
				});

				// Make the chart sortable
				tempchart.find("ul.ccpart").sortable({
						axis: 'x', 
						containment: 'parent', 
						cursor: 'move', 
						handle: '.cchandle',
						forcePlaceholderSize: true,
						forceHelperSize: true,											
						tolerance: 'pointer',
						start : function(event, ui){ $(ui.item[0]).addClass('ccitemh');	 },
						stop : function(event, ui){ $(ui.item[0]).removeClass('ccitemh'); }
				});
				
				// Remove function
				tempchart.find("li.ccitem li.ccmenu span").live("click",function(){
					$(this).parents('.ccitem:last').attr('rel','collapsed').addClass('cchidden').fadeOut('fast',function(){
						var ccpart = $(this).parents('.ccpart');
						var tli = ccpart.find('> li');
						var li = tli.filter(':not([rel])');
						var width = Math.floor(ccpart.width() / li.length);
						li.each(function(){ $(this).width(width).addClass('cchidden'); });
						// IE6 is a buggy browser
						if($.browser.msie && $.browser.version === '6.0')
							li.filter(":last-child").width(width-3);
						if(li.length <= Math.ceil(tli.length/2))
						{
							ccpart.find('li.ccmenu span').css('visibility','hidden').addClass('cchidden');
						}
					});
				});

				// Reset function
				$("a.ccreset").click(function(){ tempchart.find(".cchidden").show().removeClass('cchidden ccheadingh').css({'display':'','visibility':'','width':''}).removeAttr('rel'); });

				// Collapse functionality
				tempchart.find(".ccheading").toggle(function(){
					$(this).addClass('ccheadingh cchidden');
					var hideclass = $(this).next().attr('class').split(' ')[0];
					tempchart.find('.' + hideclass).hide().addClass('cchidden');
				}, function(){
					$(this).removeClass('ccheadingh cchidden');
					var showclass = $(this).next().attr('class').split(' ')[0];
					tempchart.find('.' + showclass).show();
				});

				// Hand Hover functionality
				tempchart.find("li.cchandle").hover(function(){
					$(this).addClass('cchandleh');
				}, function(){
					$(this).removeClass('cchandleh');
				});

			break;

			case 'singlesFinder':
				
				var sf = $("#singlesFinder");
		

				// Main Page man woman selection
				$("a.clsGender").bind('click', function(){
					if ($(this).hasClass('clsMan')){
						$(this).addClass("selectedM").siblings().removeClass("selectedW");
						if ($(this).hasClass('seeker')){
							$(this).parents("form:eq(0)").find("input[name='sgender']").val("male");
						}
						else{
							$(this).parents("form:eq(0)").find("input[name='gender']").val("male");
						}
					}
					else{
						$(this).addClass("selectedW").siblings().removeClass("selectedM");
						if ($(this).hasClass('seeker')){
							$(this).parents("form:eq(0)").find("input[name='sgender']").val("female");
						}
						else{
							$(this).parents("form:eq(0)").find("input[name='gender']").val("female");
						}
					}
					if(!singlesFinder.ajax){ singlesFinder.populateSinglesFinder(); }
				});
				
				// Set the value of sliders
				function fnSetValues(event, ui){
					var values = $('#slider').slider('option', 'values');
					var elements = $('h2.ageRange');

					// Change the age headings
					$(elements[0]).html(values[0]);
					$(elements[1]).html(values[1]);

					// Set the values in hiddne fields
					sf.find("input[name='minage']").val(values[0]);
					sf.find("input[name='maxage']").val(values[1]);
				}

				// slider function on the slider
				$('#slider').slider({
					slide: function(event, ui){ fnSetValues(event, ui); },
					max:99,
					min:18,
					range: true,
					values: [userData.minage, userData.maxage],
					stop: function(event, ui){ singlesFinder.populateSinglesFinder(); }
				});
				
				fnSetValues();

				// checkbox preview functionality
				$("div.leftColsf div.crit input[type='checkbox']").click(function(){
					var input = $(this).parent().parent().siblings("input[type='hidden']");	
					singlesFinder.lastChange =  $(this).parent().parent().siblings('h4').text();
					if($(this).attr('checked') == false)
					{
						$("span[rel="+ $(this).attr('rel') + "]").remove();
						input.val(input.val().replace($(this).attr('rel') + '|',""));
					}
					else
					{
						var html="<span onclick='singlesFinder.removeChecked(this)' rel='"+$(this).attr('rel') +"'>"+$(this).parent().parent().siblings('h4').text() + " : " +$(this).parent().text()+"</span>&nbsp;&nbsp;";
						$("div.rightColsf .crit div.critcontain").append(html);
						input.val(input.val() + $(this).attr('rel') + '|');
					}
					if(!singlesFinder.ajax){ singlesFinder.populateSinglesFinder(); }
				 });

				// Slide open the containers for checkboxes
				$("div.leftColsf div.crit h4").toggle(function(){ 
					$(this).addClass('opened').next('ul').slideDown('fast');
				},function(){ 
					$(this).removeClass('opened').next('ul').slideUp('fast');
				});

				// Tabs for gallery and detailed view
				$("div.rightColsf ul.sftabs li").click(function(){ 
					$(this).addClass('selected').siblings().removeClass('selected');
					var thisIndex = $(this).parent().find('li').index(this);
					singlesFinder.currentView =  $(this).attr('rel');
					$('div.rightColsf .result li[rel="' + $(this).attr('rel') + '"]').show().siblings('[rel]').hide();
				});
				
				// Validation for input types
				sf.submit(function(){
					var userInput = $(this).find('input.locat').val();
					var obj = this;
					if(userInput.length > 0)
					{
						$.getJSON('/getLocation',{'where' : userInput}, function(response){ 
							if(response.zip != '')
							{
								$(obj).find('input[name="zipCode"]').val(response.zip);
								singlesFinder.currentState = ( typeof response.stateAB === 'undefined' ? "" : response.stateAB );
								singlesFinder.currentCity = ( typeof response.place === 'undefined' ? "" : response.place.split(',')[0] );
								singlesFinder.lastChange = "Location";
								singlesFinder.populateSinglesFinder();
							}
							else
								showError($(obj).find('input.locat'),'Please check your input');
						});
					}
					else
						showError($(obj).find('input.locat'),'Please check your input');
				});

				// Populating the select boxes
				sf.find('select[name=minheight],select[name=maxheight]').each(function(){ 
					var html = '<select name="'+ $(this).attr('name') +'">';
					for( var i=10; i<=300; i+=5){
						html+='<option '+( ($(this).attr('name') == 'minheight' && i==10) ? 'selected=""' : (($(this).attr('name') == 'maxheight' && i==300) ? 'selected=""' : '' ))+' value="'+i+'">'+i+' cm</option>';
					}
					html += '</select>';
					$(this).replaceWith(html);
				});

				// Fill singles finder with previous values
				sf.find('input[name="zipCode"]').val(userData.zip);
				sf.find('input[name="minage"]').val(userData.minage);
				sf.find('input.locat').val(userData.search);
				sf.find('input[name="maxage"]').val(userData.maxage);
				sf.find('input[name="gender"]').val(userData.gender);
				sf.find('input[name="sgender"]').val(userData.sgender);
				if(userData.gender == 'male')
					$('a.seeking.clsMan').click();
				else
					$('a.seeking.clsWoman').click();

				if(userData.sgender == 'male')
					$('a.seeker.clsMan').click();
				else
					$('a.seeker.clsWoman').click();

				// Gallery view hovers to show hide user details
				$("li.gallery ul div").live('mouseover', function(){ $(this).addClass('hover'); });
				$("li.gallery ul div").live('mouseout', function(){ $(this).removeClass('hover'); });

				// Function on box change
				sf.find('select[name=minheight],select[name=maxheight]').change(function(){ 

					if($(this).attr('name') == 'minheight' && parseInt(sf.find('select[name=maxheight]').val()) < parseInt($(this).val()) )
					{
						var html = '<select name="maxheight">';
						html+='<option value="'+$(this).val()+'">'+$(this).val()+' cm</option>';
						for( var i=parseInt($(this).val())+5; i<=300; i+=5){
							html+='<option value="'+i+'">'+i+' cm</option>';
						}
						html += '</select>';
						sf.find('select[name=maxheight]').replaceWith(html);
					}
					else if($(this).attr('name') == 'maxheight' && parseInt(sf.find('select[name=minheight]').val()) > parseInt($(this).val()) )
					{
						var html = '<select name="minheight">';
						for( var i=10; i<=parseInt($(this).val())-5; i+=5){
							html+='<option value="'+i+'">'+i+' cm</option>';
						}
						html+='<option selected="" value="'+i+'">'+i+' cm</option>';
						html += '</select>';
						sf.find('select[name=minheight]').replaceWith(html);
					}
					if(!singlesFinder.ajax){ singlesFinder.populateSinglesFinder(); }
				});

				singlesFinder.ajax = false;
				
				singlesFinder.populateSinglesFinder();

			break;
			
			// Compare Singles Page
			case 'cProfiles':
				// Has to be defined beforehand
				if( typeof cS == 'string')
				{
					// Profile Split
					cS = cS.split('|||');
					var html = '<ul class="ccpart">';

					for(var i=0; i<cS.length-1; i++)
					{
						// Field Split
						var tmp = cS[i].split('||');
						
						// Dirty Code to generate the html
						html += '<li class="ccitem"><ul>'+
								'	<li class="ccmenu"><span class="remove">Remove</span></li>'+
								'<li onmouseout="personals.cchart.highlight2(\'ccrow1\',false)" onmouseover="personals.cchart.highlight2(\'ccrow1\',true)"class="ccrow1 hd2"><img src="'+tmp[10]+'" alt="Profile Image" /><a href="http://webcenter.match.love.aol.com/profile/showprofile.aspx?lid=1000005&TP=PRTBK&Handle='+tmp[0]+'&TrackingID=525516&BannerID=663937">'+tmp[0]+'<br />View Profile</a></li>';
						
						for(var k=1; k<9; k++){
							html += '<li onmouseout="personals.cchart.highlight2(\'ccrow'+(k+1)+'\',false)" onmouseover="personals.cchart.highlight2(\'ccrow'+(k+1)+'\',true)"class="ccrow'+(k+1)+'">'+tmp[k].replace(/^null$/i, 'Not Provided').replace(/([a-z])([A-Z])/g,"$1 $2")+'</li>';
						}

						html += '<li onmouseout="personals.cchart.highlight2(\'ccrow'+(k+1)+'\',false)" onmouseover="personals.cchart.highlight2(\'ccrow'+(k+1)+'\',true)"class="ccrow'+(k+1)+' hd1">'+tmp[k]+'</li>';
						
						k++;
						
						html +=	'<li class="cchandle">&nbsp;</li><li class="ccrow'+(k+1)+'"><a title="match.com" class="matchlogo" href="/search-for-a-match">&nbsp;</a></li></ul></li>';
					}
					$("li.pprofiles").html(html + '</ul>');
				}

				var cchart = $('ul.cchart');
				// Fix the profile boxes
				$('.ccpart > li').width(cchart.find('.ccpart').width() / (cS.length-1));
				if(cS.length == 3){
					cchart.find('.ccmenu span').css('visibility','hidden');
				}
			break;

			default:
			break;
		}
	},
	
	// Comparison chart functions
	cchart : { 
		// highlight function
		highlight : function(row, status){
			if(status){
				var obj = $('li.' + row);
				obj.height('');
				obj.addClass('hover');
				var h = obj.height();
				obj.height(h);
			}
			else{
				var obj = $('li.' + row);
				obj.height('');
				obj.removeClass('hover');
				var h = obj.height();
				obj.height(h);
			}
		},

		// highlight function without adjustment
		highlight2 : function(row, status){
			if(status){
				var obj = $('li.' + row);
				obj.addClass('hover');
			}
			else{
				var obj = $('li.' + row);
				obj.removeClass('hover');
			}
		},
		
		// delete row function
		deleterow : function(row){
			$('li.' + row).hide('slow').addClass('cchidden');
		}
	}
};
