var dialogHandle;
var MyLife = {
	ajaxUrl: 'ajaxService.do'

};

$.extend(
	MyLife, 
    {
		ajax: function(data, callback, type) {
        	/* data can never be null */
			
            type = type || 'json';
                
            $.get(this.ajaxUrl, data, callback, type)
        }
    }
);
function closeModal(dialog) {
	$.modal.close();
}
jQuery(function ($) {
    $(".filterText").keyup(function () {
        var filter = $(this).val(), count = 0;
        var filterList = $(this).attr("id") + "List";
        $("#" + filterList + ".filtered:first li").each(function () {
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).addClass("hidden");
            } else {
                $(this).removeClass("hidden");
                count++;
            }
        });
        $("#filter-count").text(count);
    });
});
function reloadContactsModuleLeft() {
	$("#homeMyContactsFeed").load("/pages/ajax/ajaxLoader.htm");
	LoadData("/api/contactsAPI.do","","MyContacts","homeMyContactsFeed");
}
function reloadMySearchesModuleLeft() {
	$('#mySearchesList').html("");
	$("#mySearchesViewAll").html("");
	var getRecentsearches= new AjaxRequest("/api/mySearchesAPI.do","searchesLimit=5","POST","LoadRecentSearches");
	getRecentsearches.Execute();
}
function reloadActiveSearches() {
		$('#activeSearchModule').load("/activeSearchModule.do");
}
function reloadPymk() {
	 LoadData("/api/pymkAPI.do","pagesize=10","REC","recFeed");
}
function breakLongStrings(selector,tag,stringCount) {
	$(selector).each(
		function(index) {
			var objectText =jQuery.trim($(this).html());
			var objectTextArr = objectText.split(" ");
			if((objectText.length > stringCount) && (objectTextArr.length < 2)) {
				var startText = objectText.slice(0,stringCount);
				var endText = objectText.slice(stringCount);
				var newText = startText + tag + endText;
				$(this).html(newText);
			}
			else {
				return;
			}
		}
	)
}
//check if value is alpha characters 
function isAlpha(val){
   var validChars = "abcdefghijklmnopqrstuvwxyz '-";
   var isAlpha = true;
   var testChar = '';
 
   for (i = 0; i < val.length && isAlpha; i++) { 
	  testChar = val.toLowerCase().charAt(i); 
	  if (validChars.indexOf(testChar) == -1) {
		 isAlpha = false;
	  }
   }
   return isAlpha;
}
function isValidName(val) {
	var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	var inValid = "1234567890`~!@#$%^&*()=+[{]}\\|;:,<.>?/\""
	var permissible = "'-"
	var ok = "no";
	var temp, beg, end;
	//check if have any valid characters
	for (var i=0; i<val.length; i++) {
		temp = "" + val.substring(i, i+1);
		if (valid.indexOf(temp) != "-1")  {
			ok = "yes";
		}
	}
	
	//check if have any invalid characters. Only space, apostrophe, and dash are allowed
	for (var i=0; i<val.length; i++) {
		temp = "" + val.substring(i, i+1);
		if (inValid.indexOf(temp) != "-1") {
			ok = "no";
		}
	}
	
	//not allow permissible characters at the beginning or end
	beg = "" + val.substring(0, 1);
	end = "" + val.substring(val.length-1, val.length);
	if (permissible.indexOf(beg) != "-1" || permissible.indexOf(end) != "-1") {
		ok = "no";
	}
	
	if (ok == "no") {
		return false;
   	} else {
   		return true;
   	}
}
function ValidateMySearchesFormAndAjax(){

	var errArr=new Array();
	errArr.push(1);
	var flag=true;
	if($('#fn').val()=="" || $('#fn').val()=="First Name" )
	{
		$('#fn').val('').removeClass().addClass("redBorder");
		$('#fnError').html("First name is required").show();
		errArr.push(1);
	}
	else if(!isValidName($('#fn').val())){
		$('#fn').val('').removeClass().addClass("redBorder");
		$('#fnError').html("Please enter a valid First Name").show();
		errArr.push(1);
	}
	else
	{
		$('#fnError').html('').hide();
		$('#fn').removeClass().addClass("greyBorder");
		errArr.pop();
	}
	
	if($('#ln').val()=="" || $('#ln').val()=="Last Name" )
	{
		$('#ln').val('').removeClass().addClass("redBorder");
		$('#lnError').html("Last name is required").show();
		errArr.push(1);
	}
	else if(!isValidName($('#ln').val())){
		$('#ln').val('').removeClass().addClass("redBorder");
		$('#lnError').html("Please enter a valid Last Name").show();
		errArr.push(1);
	}
	else
	{
		$('#lnError').html('').hide();
		$('#ln').removeClass().addClass("greyBorder");
		errArr.pop();
	}
	
	if($('#age').val()=="" || $('#age').val()=="Approx. age" )
	{
		$('#age').val('').removeClass().addClass("small").addClass("redBorder");
		$('#ageError').html("Approx. age is required").show();
		errArr.push(1);
	}
	else if(isNaN($('#age').val())){
		$('#age').val('').removeClass().addClass("small").addClass("redBorder");
		$('#ageError').html("Please enter a valid age").show();
		errArr.push(1);
	}
	else if( parseInt($("#age").val()) > 99 ) {
		$('#age').val('').removeClass().addClass("small").addClass("redBorder");
		$('#ageError').html("Age must be<br/>younger than 100").show();
		errArr.push(1);
	}
	else if( parseInt($("#age").val()) < 13 ) {
		$('#age').val('').removeClass().addClass("small").addClass("redBorder");
		$('#ageError').html("The minimum search<br/>age is 13").show();
		errArr.push(1);
	}
	else
	{
		$('#ageError').html('').hide();
		$('#age').removeClass().addClass("small").addClass("greyBorder");
		errArr.push();
	}
	if(errArr.length>0)
	 flag=false;

	return flag;
}
function toProperCase(s)
{
	if(s) {
  return s.toLowerCase().replace(/^(.)|\s(.)/g, 
          function($1) { return $1.toUpperCase(); });
	}
}
function formatNumberWithComma(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
	x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
 function LoadData(requestUrl, queryP,fnName,sectionId,userObject)  
 {  
	 $.ajax({
		   type: "Get",
		   url: requestUrl,
		   data: queryP,		   
		   success: function(data){
		 			
					 switch (fnName)
					 {
						 case "WSFY":
							 WSFY(data,sectionId);
						 break;
						 case "WVYP":
							 WVYP(data,sectionId);
						 break;
						  case "MyContacts":
							 CONTACTS(data,sectionId,userObject);
						 break;
						 case "REC":
							 REC(data,sectionId);
					     break;
						 case "WGY":
							 WGY(data,sectionId);
					     break;
					     
						 default : //alert("Did not match");
					 }//end of switch
		   }
		 });	
 }  
function CONTACTS(data,sectionId,contactObject) {
	$("#"+sectionId).html("");
	myJSONObject = eval('(' + data + ')');
	var contactCount = 0;
		 
	if(myJSONObject.resultList.length > 0) {
		 $.each(myJSONObject.resultList, function(i,item){
			 RenderJsonContactsData(sectionId,item.group,item.contacts,i,contactObject);	
			 contactCount = contactCount + item.contacts.length;
		 });
		 //POPULATE THE TOTAL COUNT
		 $("#" + sectionId + "Count").html("(" + contactCount + ")");
		 if( (sectionId.indexOf("wsfyFamily") > -1) || (sectionId.indexOf("wsfyContacts") > -1) ) {
			 //Initialize the Carousel.
			var parentId = sectionId.split("ListContent")[0];
			var parentModule = parentId.split("wsfy")[1];
			var wsfySliderId = "wsfy" + parentModule + "Slider";
			var wgySliderId = "wgy" + parentModule + "Slider";
			var firstEntryId = $("#" + parentId + "ListContentHiddenData").html();
			if(contactObject != undefined) {
				firstEntryId = contactObject.newEntryId;
				$("#wsfy" + parentModule + "ListContent").scrollTo("li#" + contactObject.newEntryId ,800);
			}
			var firstEntryBookId = trim($("#addressBookId").html());
			var queryParams = "entryID=" + firstEntryId + "&bookID=" + firstEntryBookId;
			if(contactObject != undefined) {
				$("#wsfy" + parentModule + "Scrollers").removeClass("defaultCase");
				loadWsfySiteCarousel("/api/wsfyWgyAPI.do?" + queryParams,wsfySliderId,wgySliderId,3,'');
			}
			//SHOW THE CONTENT
			$("#" + sectionId + "-Container").removeAttr("style")
			$("#" + sectionId + "-Container").removeClass("loadModule")
		 }
	}
	else {
		//FOR THE WSFY TAB
		 if( (sectionId.indexOf("wsfyFamily") > -1) || (sectionId.indexOf("wsfyContacts") > -1) ) {
			 //SHOW THE NULL CASE
			 $("#" + sectionId + "Loading").css("background","none");
			 $("#" + sectionId + "-Container").css("height","133px");
			 $("#" + sectionId + "Loading").css("height","133px");
			 if( sectionId.indexOf("wsfyFamily") > -1) {
				 $("#" + sectionId + "-Container").css("height","185px");
				 $("#" + sectionId + "Loading").css("height","185px");
				 $("#" + sectionId + "Loading").load("/pages/searchMonitor/modules/searchSpyGender-Null.vm");
			 }
			 else {
				 $("#" + sectionId + "Loading").load("/pages/searchMonitor/modules/" + sectionId + "-Null.htm");
			 }
		 }
		 else {
			//FOR THE LEFT NAV 
			$("#myContactsHomeFilterDiv").hide();
			$("#"+sectionId).hide();
			$("#" + sectionId + "Null").show();
		 }
	}
}
 function WSFY(data,sectionId)
 {
	 $('#'+sectionId).html("");
	 myJSONObject = eval('(' + data + ')');
	 if(myJSONObject.wsfy.length > 0)
	 {
		 $.each(myJSONObject.wsfy, function(i,item){
			 RenderJsonData(sectionId,item,i);		
		 });
		 if(sectionId == "wsfyViewAllResults") {
			 resizeThumbs(sectionId,45,45);
		 }
		 else {
			 resizeThumbs(sectionId,80,80);
		 }
		 var count="#"+sectionId+"Count";
		 if(sectionId == "wsfyFeed") {
			 var peopleText = " people"
			 if(myJSONObject.wsfyCount == 1) {
				 peopleText = " person";
				 $(count + "Text").html("is");
			 }
			 $(count).html(myJSONObject.wsfyCount + peopleText);
			 if(myJSONObject.subscribed == false) {
				 if(myJSONObject.wsfyCount > 5) {
					$("#" + sectionId + "ViewAll").show(); 
				}
			 }
			 else {
				 if(myJSONObject.wsfyCount > 10) {
						$("#" + sectionId + "ViewAll").show(); 
					 }
			 }
		 }
		 else {
			 $(count).html("("+myJSONObject.wsfyCount+")");
			 if(myJSONObject.wsfyCount > 10) {
					$("#" + sectionId + "ViewAll").show(); 
				 }
		 }
		 
		 //View all Module
		 if(sectionId == "wsfyViewAllResults") {
			updatePagination(myJSONObject.wsfy.length,myJSONObject.wsfyCount); 
		 }
	 }
	 else
	 {
		 showNullData(sectionId)
	 }	
 }
 function WGY(data,sectionId)
 {
	 $('#'+sectionId).html("");
	 myJSONObject = eval('(' + data + ')');

	 if(myJSONObject.wgy.length > 0)
	 {
		 $.each(myJSONObject.wgy, function(i,item){
			 RenderJsonData(sectionId,item,i);		
		 });
		 resizeThumbs(sectionId,80,80);
		 var count="#"+sectionId+"Count";
		 $(count).html("("+myJSONObject.wsfyCount+")");
		 if(myJSONObject.wsfyCount > 10) {
			$("#" + sectionId + "ViewAll").show(); 
		 }
		//View all Module
		 if(sectionId == "wsfyViewAllResults") {
			 updatePagination(myJSONObject.wgy.length,myJSONObject.wgyCount);
		 }
	 }
	 else
	 {
		 showNullData(sectionId)
	 }	
 }
 function WVYP(data,sectionId)
 {
	 myJSONObject = eval('(' + data + ')');
	 $('#'+sectionId).html("");
	 if(myJSONObject.wvmp.length > 0)
	 {
		 $.each(myJSONObject.wvmp, function(i,item){
			
			 RenderJsonData(sectionId,item,i);		
		 });
		 if(sectionId == "wsfyViewAllResults") {
			 resizeThumbs(sectionId,45,45);
		 }
		 else {
			 resizeThumbs(sectionId,80,80);
		 }
		 var count="#"+sectionId+"Count";
		 if(sectionId == "wvypFeed") {
			 var peopleText = " people"
			 if(myJSONObject.wvmpCount == 1) {
				 peopleText = " person"
			 }
			 $(count).html(myJSONObject.wvmpCount + peopleText);
			 if(myJSONObject.subscribed == false) {
				 if(myJSONObject.wvmpCount > 5) {
					$("#" + sectionId + "ViewAll").show(); 
				}
			 }
			 else {
				 if(myJSONObject.wvmpCount > 10) {
						$("#" + sectionId + "ViewAll").show(); 
					 }
			 }
		 }
		 else {
			 $(count).html("("+myJSONObject.wvmpCount+")");
		 }
		 if(myJSONObject.wvmpCount > 10) {
				$("#" + sectionId + "ViewAll").show(); 
		}		 
		//View all Module
		 if(sectionId == "wsfyViewAllResults") {
			 updatePagination(myJSONObject.wvmp.length,myJSONObject.wvmpCount);
		 }
	 }
	 else
	 {
		 showNullData(sectionId);
		 if( $("#wvypHomeHeader").length > 0) {
			 $("#wvypHomeHeader").html("View Your Web Profile");
	 	}
	 }
 }
 function showNullData(sectionId) {
	 var parentId = toProperCase(sectionId.split("Feed")[0]);
	 $("#home"+parentId).addClass("nullCase");
 }
  function ShowActiveCount(eId,item,singularValue,pluralValue) {
	 if(typeof($('#'+eId)) != "undefined")
	  {
		if(item>1 || item == 0 )			
			$('#'+eId).html(item+" " + pluralValue)
		else
			$('#'+eId).html(item+" " + singularValue)
	 }
 }
 
 function REC(data,sectionId)
 {
	 myJSONObject = eval('(' + data + ')');
	 $('#'+sectionId).html("");
	 if(myJSONObject.pymk.length > 0)
	 {
		 $.each(myJSONObject.pymk, function(i,item){
			
			 RenderJsonData(sectionId,item,i);		
		 });
		 resizeThumbs(sectionId,80,80);
		 var countId="#"+sectionId+"Count";
		 var peopleText = " people"
		 if(myJSONObject.pymkCount == 1) {
			 peopleText = " person";
			 $(countId + "Text").html("is");
		 }
		 $(countId).html(myJSONObject.pymkCount + peopleText);
		 if(myJSONObject.pymkCount > 10) {
				$("#" + sectionId + "ViewAll").show(); 
			 }
	 }
	 else
	 {
		showNullData(sectionId)
	 }
 }
function RenderJsonContactsData(sectionName,category,contactList,i,contactObject) {
	var liE=CreateContactCategoryModule(sectionName,category,contactList,i,contactObject);
}

 function RenderJsonData(sectionName,item,i) {
		var liE=CreateUserModule(item,i,sectionName);
		 var temp="#"+sectionName;
		 $(temp).append(liE);
 }
 function CreateUserModule(item,i,sectionId) {
		//APPEND THE PROPER PARAMETER FOR PO
	 	if(myJSONObject.subscribed == false) {
	 		if(myJSONObject.wvmp) {
	 			 var smType = "wvmp";
	 			var tempHref="/searchMonitor.do?type=" + smType + "&sub=true";
	 		 }
	 		if(myJSONObject.wsfy || myJSONObject.wgy) {
	 			//FIGURE OUT IF WE ARE ON THE WSFY FAMILY OR WSFY CONTACTS
	 			var wsfyModule = "";
	 			if(sectionId.indexOf("Family") > -1) {
	 				wsfyModule = "family"
	 			}
	 			if(sectionId.indexOf("Contact") > -1) {
	 				wsfyModule = "contacts"
	 			}
	 			//FIGURE OUT IF IT'S WSFY OR WGY
	 			var smType ="wsfy"
	 			if(sectionId.indexOf("wgy") > -1) {
	 				smType = "wgy"
	 			}
	 			
	 			var tempHref="/searchMonitor.do?type=" + smType + "&sub=true";
	 			if(wsfyModule != "") {	
	 				tempHref="/searchMonitor.do?section=" + wsfyModule + "&type=" + smType + "&sub=true";
	 			}	
	 			if(item.userId == "-1") {
	 				tempHref =  "javascript:void(0)";
	 			}
	 		}
	 		if(myJSONObject.pymk) {
	 			var smType = "pymk";
	 			var tempHref="/displayProfile.do?uid="+item.userId;
	 		}	 		
	 	}
	 	else {
	 		//IF WE HAVE A NON-ML MEMBER
	 		if(item.userId == "-1") {
	 			var tempHref = "javascript:void(0)"
	 		}
	 		else {
	 			var tempHref="/displayProfile.do?uid="+item.userId;
	 		}
	 	}
		
//***** create Name Section *****/	 
		//create thumb tag
		 var thumb = document.createElement('img');
		 var photoNullImage = staticServer + "/images/09/icons/silhouette80.gif";
		 $(thumb).attr('border',"0");
		 
		 if(item.photoUrl == null) {
			  $(thumb).attr('src',photoNullImage);
		 	  $(thumb).addClass("defaultThumb");
		 }
		 else if(item.photoUrl == "") {
			  $(thumb).attr('src',photoNullImage);
		 	  $(thumb).addClass("defaultThumb");
		 }
		 else {
			 $(thumb).attr('src',item.photoUrl); 
			 $(thumb).attr('width','80');
			 $(thumb).attr('height','80');
			 $(thumb).addClass("thumbResize")
		 }

		//create imageLink tag
		var thumblink=document.createElement('a');
		$(thumblink).attr('href',tempHref);
		$(thumblink).attr('title','View full profile');
		if(myJSONObject.subscribed == true) {
			if(item.userId == "-1") {
				$(thumblink).addClass("defaultCursor")
				$(thumblink).attr("title", "Non-MyLife Member")
			}
		}
		
		//append thumb to link
		thumblink.appendChild(thumb);
		
		//create thumb div
		var thumbDv=document.createElement('div');
		$(thumbDv).addClass("feedThumbImage");
		if(item.userId == "-1") {
			$(thumblink).attr("title","Non-MyLife Member");
			$(thumbDv).addClass("nonMember")
		}
		
		//append the thumblink to thumbdiv
		thumbDv.appendChild(thumblink);
		
//***** create Name Section *****/
		
		//create nameLink
		var nameLink=document.createElement('a');
		
		$(nameLink).attr('href',tempHref);
		$(nameLink).attr('title','View full profile');
		var fullName = "";
		if(item.firstName != null)
			fullName = toProperCase(item.firstName);
		if(item.lastName != "" ) {
			if(item.lastName != null) {
				fullName = fullName + " "+ toProperCase(item.lastName)
			}
		}
		
		if (fullName==undefined) {
			fullName="MyLife Member"
		}
		fullName = fullName + ", "+item.age;
		if(item.firstName == "" && item.lastName == "" && item.age == "0") {
			fullName = ""
		}
		$(nameLink).html(fullName);
		
		//create name dv
		var nameDv=document.createElement('div');
		$(nameDv).addClass("feedName");
		if(item.userId == "-1") {
			$(nameLink).attr("title","Non-MyLife Member");
			$(nameDv).addClass("nonMember")
		}
		
		//append namelink to namediv
		nameDv.appendChild(nameLink);
		
//***** create city Section *****/		
		var cityLink=document.createElement('a');
		var city = "";
		var state="";
		if(item.city != null) {
			var city = item.city;
		}
		if((item.state != null) && (item.state!="")) {
			if((item.city != null) && (item.city!="")) {
				state= ", " + item.state;
			}
			else {
				state = item.state;
			}
		}
		$(cityLink).attr('href',tempHref);
		$(cityLink).attr('title','View full profile');
		$(cityLink).addClass('gray6');

		//If there's a matchValue field...then it's PYMK
		if(item.matchValue) {
			$(cityLink).html(item.matchValue);
		}
		else {
			$(cityLink).html(city + state);
		}
		
		//create city dv
		var cityDv=document.createElement('div');
		$(cityDv).addClass("feedCity");
		if(item.userId == "-1") {
			$(cityLink).attr("title","Non-MyLife Member");
			$(cityDv).addClass("nonMember")
		}
		
		//append citylink to city div
		cityDv.appendChild(cityLink);
		
		//DATE DIV
		var dateLink=document.createElement('a');
		$(dateLink).attr('href',tempHref);
		$(dateLink).attr('title','View full profile');
		$(dateLink).addClass('gray6');
		$(dateLink).html(item.searchDate);
		var dateDv=document.createElement('div');
		$(dateDv).addClass("feedDate"); 
		if(item.userId == "-1") {
			$(dateLink).attr("title","Non-MyLife Member");
			$(dateDv).addClass("nonMember")
		}
		dateDv.appendChild(dateLink);
		
	 // create Li
		var liElement=document.createElement('li');
		$(liElement).addClass('jcarousel-item-'+(i+1))
		
	//append everything to li
		liElement.appendChild(thumbDv);
		liElement.appendChild(nameDv);
		liElement.appendChild(cityDv);
		liElement.appendChild(dateDv);
	
		 return liElement;
 }
 
 function CreateContactCategoryModule(sectionId,category,contactList,i,contactObject)
 {
	//CATEGORY
	var obj = $("#" + sectionId);
	var liElement=document.createElement('li');
	$(liElement).addClass("alphaHeader");
	if(i==0) {
		$(liElement).addClass("firstElement");
	}
	$(liElement).html(category);	
	$(obj).append(liElement);
	
	var parentId = sectionId.split("ListContent")[0];
	
	//LIST
	 $.each(contactList, function(j,item){
		 var cLi = document.createElement("li");	
		 var contactName =  item.firstName + " " + item.lastName;
		 if(i==0 && j==0) {
			$("#addressBookId").html(item.addressBookId) 
		 }	
		 $(cLi).attr("id",item.addressBookEntryId);
		 $(cLi).attr("name",item.addressBookId);
		 $(cLi).attr("unum",item.usernum);
		 $(cLi).addClass("alphaName");
		 //For the Family & Contacts module
			if((sectionId.indexOf("wsfyFamily") > -1) || (sectionId.indexOf("wsfyContacts") > -1)) {
				if(contactName.length > 23) {
					contactName = contactName.substring(0,22) + "..."
				}
				//IF WE'RE ADDING A NEW CONTACT...DEFAULT TO IT.
				if(contactObject != undefined ) {
					if(item.addressBookEntryId == contactObject.newEntryId) {
						var parentModule = parentId.split("wsfy")[1];
						$(cLi).addClass("on");
						$("#" + parentId + "ListContentHiddenData").html(item.addressBookEntryId);
						$("#wsfy" + parentModule + "EntryId").html(item.addressBookEntryId);
						//UPDATE THE NAME
						//POPULATE THE NAME FOR WSFY + WGY
						$("#wsfy" + parentModule + "Scrollers .contactNameDynamic").html(contactName);
						$("#wgy" + parentModule + "Scrollers .contactNameDynamic").html(contactName);

					}
				}
				else {
					if(i==0 && j==0) {
						/*
						var parentModule = parentId.split("wsfy")[1];
						$(cLi).addClass("on");
						$("#" + parentId + "ListContentHiddenData").html(item.addressBookEntryId);
						$("#wsfy" + parentModule + "EntryId").html(item.addressBookEntryId);
						//UPDATE THE NAME
						//POPULATE THE NAME FOR WSFY + WGY
						$("#wsfy" + parentModule + "Scrollers .contactNameDynamic").html(contactName);
						$("#wgy" + parentModule + "Scrollers .contactNameDynamic").html(contactName);
						*/
					}
				}
			}
	
		 $(cLi).html(contactName)
		 $(obj).append(cLi);
	 });
 }
function updatePagination(objectLength,totalCount) {
	var currentPage = parseInt($("#currentPage").html());
	var paginationCount = 20;
	var start = (paginationCount*(currentPage -1)) + 1;
	var end = (start + objectLength) -1;
	$("#viewAllPaginationCount").html(start + " - " + end);
	$("#viewAllTotalCount").html(totalCount);
	
	//Hide/Display the next/prev buttons
	if(end == totalCount) {
		$(".wsfyNext").hide();
	}
	if(start == 1) {
		$(".wsfyPrev").hide()
	}
	$(".wsfyViewAllPaginationBtns").show();
	$("#wsfyViewAllResultsLoading").hide();
}
 /**************************Carousel******************************/
 //SLIDERS
 function WSFYSlider(data,sectionId,scrollVal)
 {
	 $("#" + sectionId).empty();
 	 var carouselId = sectionId;
 	 
 	 myJSONObject = eval('(' + data + ')');
 	 //UPDATE THE COUNTS
 	 printWSFYCounts(carouselId,myJSONObject.wsfyCount)
 	 if(myJSONObject.wsfy.length > 0)
 	 {
 		 $.each(myJSONObject.wsfy, function(i,item){
 			 RenderJsonData(sectionId,item,i);		
 		 }); 
 		 resizeThumbs(sectionId,80,80)
 		 //INITIALIZE THE CAROUSEL
 		 initCarousel(carouselId,scrollVal,myJSONObject.wsfyCount,myJSONObject.wsfy.length,myJSONObject.subscribed);

 		$("#"+carouselId).css("left","0px")
 	       
 		 //SHOW THE DIV (REMOVE THE LOADMODULE CLASS)
 		$("#Content-Slider-" + carouselId).removeClass("loadModule");
 	 }
 	 //NULL CASE
 	 else {
  		$("#Content-Slider-" + carouselId).removeClass("loadModule");
		 if(carouselId != "wsfySlider") {
	 		 $("#Content-Slider-" + carouselId).addClass("nullCase")
		 }
		 else {
			$("#wsfySliderNull").show();
		 }
 	 }
 }
 function WGYSlider(data,sectionId,scrollVal)
 {
 	 //$('#'+sectionId).html("");
	 $("#" + sectionId).empty();
 	 var carouselId = sectionId;
 	 
 	 myJSONObject = eval('(' + data + ')');
 	 //UPDATE THE COUNTS
	printWSFYCounts(carouselId,myJSONObject.wgyCount)
	
 	 if(myJSONObject.wgy.length > 0)
 	 {
 		 $.each(myJSONObject.wgy, function(i,item){
 			 RenderJsonData(sectionId,item,i);		
 		 });
 		 resizeThumbs(sectionId,80,80)
 		 //INITIALIZE THE CAROUSEL
 		 initCarousel(carouselId,scrollVal,myJSONObject.wgyCount,myJSONObject.wgy.length,myJSONObject.subscribed);

 		$("#"+carouselId).css("left","0px")
 	       
 		 //SHOW THE DIV (REMOVE THE LOADMODULE CLASS)
 		$("#Content-Slider-" + carouselId).removeClass("loadModule");
 	 }
 	 //NULL CASE
 	 else {
 		$("#Content-Slider-" + carouselId).removeClass("loadModule");
 		 if(carouselId != "wgySlider") {
	 		 $("#Content-Slider-" + carouselId).addClass("nullCase")
 		 }
 		 else {
 			$("#wgySliderNull").show();
 		 }
 	 }
 }
 function WVMPSlider(data,sectionId,scrollVal)
 {
	 $("#" + sectionId).empty();
 	 var carouselId = sectionId;
 	 //Subject View
	 var isSubjectView = false;
	 if($("#profile-subject-view").html()== "true") {
	 	isSubjectView = true;
	 }
	 //Subject isPremium
	 /*var isPremium = false;
	 if($("#profile-subject-premium").html() == "true") {
	 	isPremium = true;
	 }*/
 	 
 	 myJSONObject = eval('(' + data + ')');	
 	 var isPremium = myJSONObject.subscribed;
 	 
 	 if(myJSONObject.wvmp.length > 0)
 	 {
 		 $.each(myJSONObject.wvmp, function(i,item){
 			 RenderJsonData(sectionId,item,i);		
 		 });
 		 resizeThumbs(sectionId,80,80);
 		 //INITIALIZE THE CAROUSEL
 		 initCarousel(carouselId,scrollVal,myJSONObject.wvmpCount,myJSONObject.wvmp.length,isPremium);
 		 
 		 var wvypCount = myJSONObject.wvmpCount;
 		 
		//Print the WVYP Count + Name
		var userCase = "this";
		if(isSubjectView) {
			userCase = "your";
		}
 		 var pvCountText = "<b>" + wvypCount + " " + wordTense(wvypCount,"person","people") + "</b> viewed " + userCase + " profile.";
 		 pvCountText += "<a href='javascript:void(0)' class='wsfy-view-all viewAllResultsLink' id='wvypSliderViewAll'>View all results &raquo;</a>";
 		 $("#profile-wvyp-counts").html(pvCountText);
 		 
 		 //Show the Header
 		 $("#wvyp-heading-text").show();
 		 $("#wvypSliderNull").remove();

 		//if(myJSONObject.subscribed == true) {
 		if(isPremium == true) {
			 if(myJSONObject.wvmpCount > 20) {
				 $("#" + carouselId + "ViewAllText").show();
			 }
 		}
 		else {
 			$("#" + carouselId + "ViewAllText").css("padding-top","0px");
 			$("#" + carouselId + "ViewAllTextLink").addClass("red");
			$("#" + carouselId + "ViewAllTextLink").html("Upgrade now to see names, photos, and more! &raquo;"); 
			$("#" + carouselId + "ViewAllText").show(); 
 		}
 	 }
 	 //NULL CASE
 	 else {
 	 	$("#wvyp-heading-text").show();
 	 	$("#profile-wvyp-counts").remove();
 	 	$("#slider-wvyp").addClass("wvyp-null-premium");
 	 	$(".wvypSliderNull").show();
 	 	
 	 	$("#wvypSliderViewAllText").remove();
 	 	$("#wvypSliderViewAllTitle").remove();
 	 	$("#wvypSliderContainer").remove();
 	 }
 }
 function printWSFYCounts(divId,count) {
 	 var countSpan="#"+divId + "Count";
     var peopleSpan = "#"+divId+"People"; 
     var peopleCase = "people";
     
     if(typeof($(countSpan) != "undefined")) {
    	 $(countSpan).html(count);
     }
 	
 	if(count == 1) {
 		peopleCase = "person"
 	}
 	if(typeof($(peopleSpan) != "undefined")) {
 		$(peopleSpan).html(peopleCase);
 	}
 }
 function mycarousel_itemFirstOutCallback(carousel, item, idx, state) {
	 var s = carousel.size();
	 var carouselId = carousel.options.id;
	 if(carousel.options.isPremium == true) {
		 if(state == "prev") {
			 $("#" + carouselId + "ViewAll").hide()
		 }
		 if(carousel.options.totalCount > s) {
			 if(state == "next") {
				 if(idx == s) {
					 $("#" + carouselId + "ViewAll").show()
				 }
			 }
		 }
	 }
 } 
 function initCarousel(carouselId,scrollVal,totalCount,carouselSize,isPremium) {
	 var paginationResults = 20;
	 var pageSize = parseInt(Math.round(totalCount/paginationResults));
	 
	 $('#'+ carouselId).jcarousel({
			id:carouselId,
			totalCount:totalCount,
			isPremium:isPremium,
	   		scroll:scrollVal,
	   		visible:scrollVal,
	   		start:1,
	   		size:carouselSize,
	   		itemLastInCallback:mycarousel_itemFirstOutCallback
     });
	 //DISPLAY THE VIEW ALL LINK
	 if(isPremium == true) {
		 if(totalCount > paginationResults) {
			 $("#" + carouselId + "ViewAllText").show();
		 }
	 }
	 else {
		 //FOR FREE USERS, ONLY SHOW THE CTA FOR THE WSFY MODULE.
		 if(carouselId.indexOf("wsfy") > -1) {
			 $("#" + carouselId + "ViewAllTextLink").addClass("red");
			 $("#" + carouselId + "ViewAllTextLink").html("Upgrade now to see names, photos, and more! &raquo;"); 
			 $("#" + carouselId + "ViewAllText").show(); 
		 }
		 else {
			 $("#" + carouselId + "ViewAllText").hide(); 
		 }
	 }
	 //POPULATE THE PAGE SIZE
	 $("#" + carouselId + "PageSize").html(pageSize)
 }
 function loadWsfySiteCarousel(apiUrl,wsfyId,wgyId,scrollVal,queryParam) {
 	 $.ajax({
 		   type: "Get",
 		   url: apiUrl,
 		   data: queryParam,		   
 		   success: function(data){
 		 	 	var thisJSONObject = eval('(' + data + ')');
 		 		//WSFY Slider
 		 		WSFYSlider(data,wsfyId,scrollVal);
 		 		
 		 		//WGY Slider
 		 		WGYSlider(data,wgyId)
 		 		if(wgyId == "wgySlider") {
 		 			var totalCount = thisJSONObject.wsfyCount;
 		 			var googleCount = thisJSONObject.wgyCount;
 	 				$("#wsfySliderCount").html("(" + totalCount +")");
 	 				
 	 				//HANDLE NULL CASE FOR WSFY + WGY 
 	 				if(totalCount == 0 && googleCount == 0) {
 	 					$("#wsfyWgyTopModule").html( $("#wsfyTopModuleNull").html() );
 	 					$("#wsfyWgyTopModule-Content").removeClass("loadModule")
 	 				}
 	 				else {
 	 					$("#wsfyWgyTopModule-Content").removeClass("loadModule")
 	 				}
 		 		}
 		   }
 		 });	
 }
 function loadWvmpSiteCarousel(apiUrl,wvmpId,scrollVal,queryParam) {
 	 $.ajax({
 		   type: "Get",
 		   url: apiUrl,
 		   data: queryParam,		   
 		   success: function(data){
 		 	 	var thisJSONObject = eval('(' + data + ')');
 		 		//WVMP Slider
 		 		WVMPSlider(data,wvmpId,scrollVal);
 		   }
 		 });	
 }
//END SLIDERS
//******************Reusable Ajax Function*************/
 function AjaxRequest(url,queryParam,reqType,successFxn)
 {
 	 this.url=url;
 	 this.queryData=queryParam;
 	 this.reqType=reqType;
 	 this.onSuccessExecute=successFxn;
 	 this.Execute=function(){
 		 		
 		 $.ajax({
 			   type: this.reqType,
 			   url: this.url,
 			   data: this.queryData,		   
 			   success:function(data){
	 			 eval(successFxn + '('+data+')')
		 		}
 			 });
 		 
 		 }
 }
 //***************************************** //
 function AddPeople(form)
 { 
	 var errArr=new Array();		
		var errStr='';
		var nothingSelected=false;
		for (var k=1;k <= 3;k++)
		{
			var _fn= "#firstName"+k;
			var _ln= "#lastName"+k;
			var _a="#age"+k;
			
			var _fnv= $(_fn).val();
			var _lnv= $(_ln).val();
			var _av= $(_a).val();
			
			if(_fnv == "First Name")
				_fnv='';
			if(_lnv == "Last Name")
				_lnv='';
			if(_av == "Approx. Age")
				_av='';
			
			if(_fnv !="" || _lnv !="" || _av !="") 	{
				if(_fnv =="") 	{
					$(_fn).addClass("redBorder");					
					errStr=errStr+"<li>Please enter a First Name</li>"
					errArr.push(1);
				}
				else if(!isValidName(_fnv)) {
					$(_fn).addClass("redBorder");					
					errStr=errStr+"<li>Please enter a valid First Name</li>"
					errArr.push(1);
				}
				else {
					 $(_fn).removeClass("redBorder");	
				}
				
				if(_lnv == '') 	{
					$(_ln).addClass("redBorder");
					errStr=errStr+"<li>Please enter a Last Name</li>"
					errArr.push(1);					
				}
				else if(!isValidName(_lnv)) {
					$(_ln).addClass("redBorder");					
					errStr=errStr+"<li>Please enter a valid Last Name</li>"
					errArr.push(1);
				}
				else {
					 $(_ln).removeClass("redBorder");	
				}
				
				if( _av == '') 	{
					$(_a).addClass("redBorder");
					errStr=errStr+"<li>Please enter Approximate Age</li>"
					errArr.push(1);
				}				
				else if(isNaN(_av)){
					$(_a).addClass("redBorder");
					errStr=errStr+"<li>Please enter a valid age</li>"
					errArr.push(1);
				}
				else if( parseInt(_av) > 99 ) {
					$(_a).addClass("redBorder");
					errStr=errStr+"<li>Please enter a valid age</li>"
					errArr.push(1);
				}				
				else if(parseInt(_av) < 0){
					$(_a).addClass("redBorder");
					errStr=errStr+"<li>Please enter a valid age</li>"
					errArr.push(1);
				}
				else {
				  $(_a).removeClass("redBorder");					
				}				
				//break
			}
			if(errArr.length > 0) {
				break;
			}
		}
    
		if(errArr.length>0) {
			flag=false;
			$('#formErrorMessage ul').html(errStr);
			$('#formErrorMessage').show();
		}
		else 	{
			 var contactData = $(form).serialize();
			 $('#formErrorMessage ul').html('').hide();
			 var sliderId = $("form #sliderId").val();
			 if(sliderId.indexOf("Family") > -1) {
				var module = "Family" 
			 }
			 else {
				var module = "Contacts"
			 }
			 var addContacts = $.ajax({
								 			   type: "GET",
								 			   url: "/api/addContactAPI.do",
								 			   data:contactData,		   
								 			   success:function(data){
									 				RefreshContactModule(data,module)
										 		}
								 			 });
		}
		
	 return false;
 }

 function RefreshContactModule(data,module)
 {
	var response = eval('(' + data + ')');
		
	if(response.success=="1")
	{
		var newEntryId = response.message;
		var oldEntryId = trim($("#wsfy" + module + "EntryId").html());
		var contactObject = new Object();
		contactObject.newEntryId = trim(newEntryId);
		contactObject.oldEntryId = oldEntryId;
		$("#wsfyFamilyListContent-Container").addClass("loadModule");
		$("#wsfyContactsListContent-Container").addClass("loadModule");
		//RELOAD THE CONTACTS MODULE (LEFT NAV)
		reloadContactsModuleLeft() ;
		//RELOAD THE FAMILY MODULE 
		if(module == "Family") {
			loadWsfyContactModule('wsfyFamilyListContent', 'cat=4',contactObject);
			sendPageNameAndChannelToOmniture('Add Family (Successful Save)','WSFY - Family');
		}
		else
			loadWsfyContactModule('wsfyFamilyListContent', 'cat=4')

		//RELOAD THE CONTACT MODULE
		if(module == "Contacts") {
			loadWsfyContactModule('wsfyContactsListContent', 'cat=4&excl=true',contactObject);
			sendPageNameAndChannelToOmniture('Add Contacts (Successful Save)','WSFY - Contacts');
		}
		else
			loadWsfyContactModule('wsfyContactsListContent', 'cat=4&excl=true')
		//CLOSE THE MODAL WINDOW
		$.modal.close();
	}
	else
		if(response.message != "")
		{
			var responseMessage = "<li>" + response.message + "</li>";
			 $('#formErrorMessage ul').html(responseMessage);
			 $('#formErrorMessage').show();
			 $("#formErrorMessage ul").show();
		}

 }
  function LoadRecentSearches(myJSONObject)
 { 	
		 $.each(myJSONObject.resultList, function(i,item){	
			 var nameAnchor=document.createElement('a');
			 var state = "";
			if(item.state != null) {
				state = item.state;
			}
			if(myJSONObject.subscribed == true) {
				if(item.newMatchCount > 0)
					var searchLink = '/newMemberMatch.do?searchType=name&pageName=people&wel_fname='+item.firstName+'&wel_lname='+item.lastName+'&wel_age='+item.age + '&state=' + state + '&sid=' + item.searchID;
				else					
					var searchLink = 'javascript:doPeopleSearch(\'searchType=name&pageName=people&wel_fname='+item.firstName+'&wel_lname='+item.lastName+'&wel_age='+item.age + '&state=' + state + '&sid=' + item.searchID + '\')';
			}
			else {
				var searchLink = "/activateScout.do?searchFirstName=" + item.firstName + "&searchLastName=" + item.lastName + "&searchAge=" + item.age + '&state=' + state + '&sid=' + item.searchID;
			}

			 $(nameAnchor).attr('href', searchLink);
			 var comma = ""
			 if(item.newMatchCount > 0) {
				comma = ", " 
			 }
			 $(nameAnchor).html(item.fullNameProper+", "+item.age + comma);	
			 
			 var liElement=document.createElement('li');
			 $(liElement).attr('class','liWithNoDecoration');
			liElement.appendChild(nameAnchor);
			if(item.newMatchCount > 0) {
				 var newAnchor = document.createElement('a');
				 $(newAnchor).attr("href",searchLink);
				 $(newAnchor).html(item.newMatchCount + " new");
				 $(newAnchor).addClass("orange bold");
				 liElement.appendChild(newAnchor)
			 }
			$('#mySearchesList').append(liElement);
		 	$("#mySearchesNullLeft").hide();
		 });
		 
		 //GET THE LIST OF HIGH SCHOOLS
		 var userHs = new Array();
	  	$.each(myJSONObject.highSchools, function(j,hs){	
	  		if(hs.userSchool == true && hs.schoolName != "") {
	  			var schoolLink = "/classlist.do";
	  			var schoolAnchor = document.createElement("a");
	  			$(schoolAnchor).attr('href', schoolLink);
	  			$(schoolAnchor).html(hs.schoolName);
	  			var hsLi = document.createElement("li");
	  			 $(hsLi).attr('class','liWithNoDecoration');
	  			 $(hsLi).css("padding-top","6px");
	  			hsLi.appendChild(schoolAnchor);
	  			$('#mySearchesList').append(hsLi);
		 		$("#mySearchesNullLeft").hide();
	  		}
	  	})
	  	
		 if(myJSONObject.totalCount > 5) {
			 var viewMoreAnchor = document.createElement("a");
			 $(viewMoreAnchor).attr('href',"/people.do");
			 $(viewMoreAnchor).html("&raquo; View All");
			 $("#mySearchesViewAll").append(viewMoreAnchor);
			 $("#mySearchesViewAll").show();
		 }
		 //POPULATE THE WSFY + WVMP COUNT
		 if(myJSONObject.wsfyCount == 0) {
			 $("#wsfyActiveCountContainer").hide();
		 }
		 else {
			 ShowActiveCount("wsfyActiveCount",myJSONObject.wsfyCount,"search","searches");
		 }
		 if(myJSONObject.wvmpCount == 0) {
			 $("#wvypActiveCountContainer").hide();
		 }
		 else {
			 ShowActiveCount("wvypActiveCount",myJSONObject.wvmpCount, "person", "people");
		 }
		 if(myJSONObject.wgyCount == 0) {
			 $("#wgyActiveCountContainer").hide();
		 }
		 else {
			 ShowActiveCount("wgyActiveCount",myJSONObject.wgyCount, "search", "searches");
		 }
		 $("#myProfileCounts").show();
		 
		 //POPULATE MY SEARCHES
	 	if(myJSONObject.resultList.length>0) {
	 		$("#homeMySearchesFeedCount").html("(" + myJSONObject.totalCount + ")")
	 	}
	 	else {
	 		if(myJSONObject.highSchoolCount == 0 && myJSONObject.resultList.length == 0) {
	 			$("#mySearchesNullLeft").show();
	 			$("#mySearchesNullLeft").html("You have no recent searches")
	 		}
	 	}
 }
  
function resizeThumbs(divId,maxImgWidth,maxImgHeight) {
	$("#" + divId + " img.thumbResize").each(function(){
        $(this).load(function(){
            var maxWidth = maxImgWidth; // Max width for the image
            var maxHeight = maxImgHeight;// Max height for the image
            $(this).css("width", "auto").css("height", "auto"); // Remove existing CSS
            $(this).removeAttr("width").removeAttr("height"); // Remove HTML attributes
            var width = $(this).width();    // Current image width
            var height = $(this).height();  // Current image height
            var ratio = width/height;
    
            if(width > height) {
                // Check if the current width is larger than the max
                if(width > maxWidth){
                		var newWidth = maxImgHeight * ratio;
                		$(this).css("width",newWidth); ///$(this).css("width",maxWidth); // Resize the width
                        $(this).css("height",newWidth/ratio); // $(this).css("height",maxWidth/ratio); // Set the height to be the max height
                        height = height * ratio;        // Reset height to match scaled image
                }
            } 
            else {
                // Check if current height is larger than max
                if(height > maxHeight){
                		$(this).css("height", maxWidth/ratio); // Reisze the height
                        $(this).css("width",maxWidth); //Set the width to the max width
                        width = width * ratio;  // Reset width to match scaled image
                }
            }
        });
    });	
}
function submitSoftMatch(form) {
	if( $("#softMatchEmployer").val() == "Enter Employer Name") {
		$("#softMatchEmployer").val("");
	}
	var schoolId = $("#regWelcomeContent #school").val();
	var softMatchData = $(form).serialize();
	$.ajax({
	   type: "GET",
	   url: "/api/saveSoftMatchAPI.do",
	   data:softMatchData,
	   success:function(data){
			var response = eval('(' + data + ')');
			if(response.success=="1")
			{
				//OMNITURE HIT
				sendPageNameAndChannelToOmniture('Welcome Overlay - Complete','Registration');
				//We're on the Profile page
				if( $("#myLifeProfile").length) {
					setTimeout('document.location = "/displayProfile.do"',4500);
				} 
				//Other page
				else {
					var currentPage = document.location.href;
					if(schoolId != "") {
						setTimeout('reloadMySearchesModuleLeft()',2000);
					}
					if(currentPage.indexOf("regflow.do") > -1) {
						if(schoolId != "") {
							setTimeout('reloadActiveSearches()',2000);
							setTimeout('reloadPymk()',2000);
						}
					}
					$("#findPeopleTabsSearch #tabFirstName").removeAttr("disabled");
					$("#findPeopleTabsSearch #tabFirstName").focus();
					$.modal.close();
				}
			}
		}
	 });
}
function wordTense(count,singleValue,pluralValue) {
	if(parseInt(count) == 1) {
		return singleValue;
	}
	else {
		return pluralValue;
	}
}
