/*Compose*/
function ComposeformSubmit(tagrgeturl,formid)
{
//var compose = document.getElementById('compose');
//compose.value="compose";
formid = "#"+formid;
var parametri = $(formid).serialize();
	$.ajax({
	type: "POST",
	url: tagrgeturl,
	data: parametri,
	success: function(xml){
		$(".cellMSS").empty();
		$(".cellMSS").html(xml);

	}
	});
}

/*sendLink*/
function SendlinkformSubmit(tagrgeturl,formid)
{
formid = "#"+formid;
var parametri = $(formid).serialize();
	$.ajax({
	type: "POST",
	url: tagrgeturl,
	data: parametri,
	success: function(xml){
		$("#msgShare2").empty();
		$("#msgShare2").html(xml);
	}
	});
}

/*sendLink*/
function SharekformSubmit(tagrgeturl,formid,divname,divtoclose)
{
formid = "#"+formid;
var parametri = $(formid).serialize();
	$.ajax({
	type: "POST",
	url: tagrgeturl,
	data: parametri,
	success: function(xml){
		$(divname).empty();
		$(divname).html(xml);
		$(divtoclose).empty();
		$(divtoclose).html('Updated Sucessfully');
        $( "#cboxClose" ).click();
	}
	});
}

/*On Click of link take user to Different page*/
function RedirectUrl(targeturl,urltype,status)
{
	var urlstring='';
	if(urltype != null)
		urlstring = urlstring +'urltype='+urltype;

	if(status != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&messageStatus="+status;
		 else
		   urlstring = urlstring+"messageStatus="+status;
	}

	if(urlstring != '')
		var targeturl_new = targeturl+"?"+urlstring;
	else
		var targeturl_new = targeturl;

//	alert(targeturl_new);

	$.ajax({
                 type: "GET",
                 url: targeturl_new,
                 //dataType: "xml",
                 success: function(xml) {
					$(".cellMSS").empty();
                    $(".cellMSS").html(xml);
                 }
             });

}
/*Message Detail Ajax Status*/
function ChangeMessageDetailStatus(targeturl,id,lasturltype,statusvalue)
{
	var urlstring='';
	if(id != null)
		urlstring = urlstring +'msgid='+id;

	/*if(urltype != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&type1="+urltype;
		 else
		   urlstring = urlstring+"type1="+urltype;
	}*/

	if(lasturltype != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&type="+lasturltype;
		 else
		   urlstring = urlstring+"type="+lasturltype;
	}

	if(statusvalue != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&statustype="+statusvalue;
		 else
		   urlstring = urlstring+"statustype="+statusvalue;
	}

	if(urlstring != '')
		var targeturl_new = targeturl+"?"+urlstring;
	else
		var targeturl_new = targeturl;

	$.ajax({
                 type: "GET",
                 url: targeturl_new,
                 //dataType: "xml",
                 success: function(xml) {
					$(".cellMSS").empty();
                    $(".cellMSS").html(xml);
                 }
             });


}
/*Inbox Ajax Status*/
function ChangeMessageStatus(tagrgeturl,statusvalue,formid)
{
var statusField = document.getElementById('statustype');
formaction = document.getElementById(formid)
statusField.value = statusvalue;
formaction.action = tagrgeturl;
//alert(formaction.action)
formid = "#"+formid;
var parametri = $(formid).serialize();
	$.ajax({
	type: "POST",
	url: tagrgeturl,
	data: parametri,
	success: function(xml){
						$(".cellMSS").empty();
						$(".cellMSS").html(xml);
	}
	});
}

/*Inbox AJAX
* Target Url : Url
* Id = Messages Id
* Type = Url Type
* DeleteString = Change the status
* InboxSearch = Inbox Search
* Messages Status = Read / Unread / Delete
* myalert = If its delete and and to confirm user before deletle
*/
function MessageDetailAjax(targeturl,id,type,deletestring,inboxsearch,messageStatus,cancelurl)
{
	var urlstring='';
	if(id != null)
		urlstring = urlstring +'msgid='+id;
	if(type != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&type="+type;
		 else
		   urlstring = urlstring+"type="+type;
	}

	if(deletestring != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&deletestr="+deletestring;
		 else
		   urlstring = urlstring+"deletestr="+deletestring;
	}
	if(inboxsearch != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&inboxSearch="+inboxsearch;
		 else
		   urlstring = urlstring + "inboxSearch="+inboxsearch;
	}
	if(messageStatus != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&messageStatus="+messageStatus;
		 else
		   urlstring = urlstring + "messageStatus="+messageStatus;
	}

	if(cancelurl != null)
	{
		conf = confirm("Are you sure, you want to delete this message");
		if(!conf)
		{
			if(urlstring != '')
				var targeturl_new = cancelurl+"?"+urlstring;
			else
				var targeturl_new = cancelurl;
		}
		else
		{
			if(urlstring != '')
				var targeturl_new = targeturl+"?"+urlstring;
			else
				var targeturl_new = targeturl;
		}
	}
	else
	{
		if(urlstring != '')
		var targeturl_new = targeturl+"?"+urlstring;
	else
		var targeturl_new = targeturl;
	}

//alert(targeturl_new);
	$.ajax({
                 type: "GET",
                 url: targeturl_new,
                 //dataType: "xml",
                 success: function(xml) {
					 //alert(xml);
					$(".cellMSS").empty();
                    $(".cellMSS").html(xml);
                 }
             });
}


/*Inbox AJAX
Targeturl = URL NAME
Message Status = Read / Under or all
inboxsearch = Inbox Search
Currentpage = Current page no
startwith = start page no with
previous Page = Previous page no
Next Page = Next Page No
*/
function InboxAjax(targeturl,messageStatus,inboxSearch,currentpage, startwith, goprev, gonext,endwith)
{
	var urlstring='';
	if(messageStatus != null)
		urlstring = urlstring +'messageStatus='+messageStatus;

	if(inboxSearch != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&inboxSearch="+inboxSearch;
		 else
		   urlstring = urlstring+"inboxSearch="+inboxSearch;
	}

	if(currentpage != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&currentpage="+currentpage;
		 else
		   urlstring = urlstring+"currentpage="+currentpage;
	}

	if(startwith != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&startwith="+startwith;
		 else
		   urlstring = urlstring+"startwith="+startwith;
	}

	if(goprev != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&goprev="+goprev;
		 else
		   urlstring = urlstring+"goprev="+goprev;
	}

	if(gonext != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&gonext="+gonext;
		 else
		   urlstring = urlstring+"gonext="+gonext;
	}

	if(endwith != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&endwith="+endwith;
		 else
		   urlstring = urlstring+"endwith="+endwith;
	}

	if(urlstring != '')
		var targeturl_new = targeturl+"?"+urlstring;
	else
		var targeturl_new = targeturl;

	$.ajax({
                 type: "GET",
                 url: targeturl_new,
                 //dataType: "xml",
                 success: function(xml) {
                   $(".cellMSS").empty();
                   $(".cellMSS").html(xml);
                   $('#childPriv').colorbox({
					inline: true,
					href: '#childPrivacy',
					overlayClose: true
					});
		$('.unconfirmed').colorbox({
				inline: true,
				href: '#confirmReg',
				overlayClose: true,
				title:false
				}).bind('cbox_complete' , function() {
					$('#cboxTitle').hide();
				});

                 }
             });
}

function submitChilddoctorAJAX(targeturl,formid,closingtagid,destinationtagid,pname,number,mainpname)
{
	f = formid;
	formid = "#"+formid;
	$(formid).submit(function() {
	      $.post
	      (targeturl, $(this).serialize(),
	    		  function(data)
	    		  {
						var dayn = 'adminDay'+number;
						var monthn = 'adminMonth'+number;
						var yearn = 'adminYear'+number;
						if(document.getElementById(dayn).value !=0 && document.getElementById(monthn).value !=0 && document.getElementById(yearn).value !=0)
						{
							pnameobj = document.getElementById(pname)
							pnameobj.innerHTML = document.getElementById(monthn).value+"/"+document.getElementById(dayn).value+"/"+document.getElementById(yearn).value;
							mainpnameobj = document.getElementById(mainpname)
							mainpnameobj.setAttribute("class", "smaller dated")
						}

  						data =  jQuery.trim(data);
//						submit_status = data.substring(0,5)
//						ihtml = '';
//						ihtml = data.substring(5);
						ihtml = data
					  	if (ihtml.length > 0) document.getElementById(destinationtagid).innerHTML = ihtml;
						document.getElementById(closingtagid).style.display = "none";
						return (true);

	    		  }
	      );
	       return false;

	});
}

function submitAJAXForm(targeturl,formid,destinationtagid,redirecturl,closingtagid,opentagid,submitId,progressIconId,reloadpage)
{
	formid = "#"+formid;
	$(formid).submit(function() {
		 //alert($(this).serialize());
	     // do validation.. if you want and then post it.
		 if (submitId !=null && progressIconId !=null)
		 	psnProgressIconSet(submitId,progressIconId);
			 
	      $.post
	      (targeturl, $(this).serialize(), 
	    		  function(data)
	    		  {
	    	  			//alert("new");
	    	  			//alert(data);
						data =  jQuery.trim(data);
						submit_status = data.substring(0,4)
						ihtml = '';
						ihtml = data.substring(4);
						//alert('ihtml is ');
						//alert(ihtml);
	    	  			if (submit_status == "true")	 
	    	  			{	
	    	  				if (redirecturl != '')
							{
	    	  					location.href = redirecturl;
							}
	    	  				else
							{
								if (reloadpage != undefined && reloadpage==1)
									location.reload(true);
								if (ihtml.length > 0) document.getElementById(destinationtagid).innerHTML = ihtml;
								document.getElementById(opentagid).style.display = "block";
								document.getElementById(closingtagid).style.display = "none";
								$('#' + opentagid).parent().find('div.change3').toggleText("Close","Change");

								
							}
	    	  			}
	    	  			else
						{
	    	  				document.getElementById(destinationtagid).innerHTML = data;	
						}
	    		  }
	      );
	       return false;

	});
}


function psnProgressIconSet(submitId,imageId)
{	
	if (document.getElementById(submitId) != null)  document.getElementById(submitId).disabled = true;
	if (document.getElementById(imageId) != null)   
	{
		document.getElementById(imageId).style.visibility = "visible";
		document.getElementById(imageId).style.display = "block";
	}
}

function psnProgressIconUnSet(submitId,imageId)
{	
	if (document.getElementById(submitId) != null) document.getElementById(submitId).disabled = false;
	if (document.getElementById(imageId) != null) 
	{
		document.getElementById(imageId).style.visibility = "hidden";
		document.getElementById(imageId).style.display = "none";
	}
}

function closeParentWindow(opentagid,closingtagid)
{
        document.getElementById(opentagid).style.display = "block";
        document.getElementById(closingtagid).style.display = "none";
        currentTxt = $('#' + opentagid).parent().find('div.change3').text();
        if (currentTxt!="Change")
           $('#' + opentagid).parent().find('div.change3').toggleText("Close","Change");


}

function openParentWindow(opentagid,closingtagid)
{
        document.getElementById(opentagid).style.display = "none";
        document.getElementById(closingtagid).style.display = "block";
        currentTxt = $('#' + opentagid).parent().find('div.change3').text();
        if (currentTxt!="Close")
           $('#' + opentagid).parent().find('div.change3').toggleText("Change","Close");


}

function favoritesAddToMine(url, itemid, uid, categoryId, bookSelfId, $refersh)
{
	url = url +"?itemid=" + itemid + "&uid=" + uid + "&categoryId=" + categoryId + "&bookSelfId=" + bookSelfId;
	$.get
	    (url,  
	    	 function(data)
	    	 {
				if( $refersh == '1')
				{
					window.location.reload( true );
				}
			   //alert("test" + data);
			 }
		);
}

function submitComment(url, itemId, type, uid, num)
{
	bookCmtsId = "bookCmts" + num;
	if(document.getElementById(bookCmtsId).value.length == 0 )
	return;
	msg = document.getElementById(bookCmtsId).value;
	document.getElementById(bookCmtsId).value = "";
	document.getElementById("image_"+num).style.display = '';
	tooltipx = document.getElementById("image_"+num).tooltipText;
	pos = tooltipx.search(/You said:/);
	sub_tip = tooltipx.substr(0,pos+9);
	document.getElementById("image_"+num).tooltipText=sub_tip +'</b> ' + msg;
	url = url + "?bookCmts=" + msg + '&itemId=' + itemId + '&type=' + type + '&uid=' + uid;
	$.get
	    (url,  
	    	 function(data)
	    	 {
			   //alert("test" + data);
			 }
		);
}

function makeBookFloat(){$(this).parent().find("div.tools").customFadeIn();}
function destroyBookFloat(){$(this).parent().find("div.tools").customFadeOut();}


function getFavElements(url, excludeIds, profileid, type, divId, tableId, ispublic, subCategory)
{
	url = url + "?excludeIds=" + excludeIds + "&profileid=" + profileid + "&type=" + type + "&tableId=" + tableId + "&ispublic=" + ispublic + '&subCategory=' + subCategory;
	$.get
	    (url,  
	    	 function(data)
	    	 {
			  //alert(data);
			  document.getElementById(tableId).innerHTML = data;
			  $(tableId).slideDown();
				
			  	var config2 = {    
				 sensitivity: 3,
				 interval: 250,    
				 over: makeBookFloat,    
				 timeout: 500,  
				 out: destroyBookFloat
				};
			 		
				$("div.item").hoverIntent(config2);
			  	$("div.tools").hover(
				function(){$(this).show();},
				function(){$(this).customFadeOut();}
				);
			 
				$("div.bookComment2 img.poptip").tooltip({track:true,delay:0,showURL:false,showBody:" - ",extraClass:"poptip",top:15,left:15});
				$("div.bookComment2 .convotip").tooltip({track:true,delay:0,showURL:false,showBody:" - ",extraClass:"convotip",top:15,left:15});
				$("div.bookComment2 .warntip").tooltip({track:true,delay:0,showURL:false,showBody:" - ",extraClass:"warntip",fixPNG:true,top:15,left:15});
				
				$("div.tools a.comment").click(function(){
					$(this).parent().parent().find("div.comment").customFadeIn();
					$(this).parent().customFadeOut();
			 	});
				 
				$("table.stuff a.addMinePop").click(function(){
					$(this).parent().find("div.addMine").customFadeIn();
			 	});

				$("div.addMine").hover(
					function(){$(this).show();},
					function(){$(this).customFadeOut();}
				);
				
				$(" a.moreCmts").click(function(){
  				$(this).offsetParent().find("div.comment.hidden").customFadeIn();
				$(this).parent().hide();
				});
	});
}




function authenticate_facebook_user()
{	
	$.ajax({
		type: "get",
		url: document.getElementById("facebook_login_callback").value,
		success: function(res){
			if(res == '3')
			{
				window.location.reload( true );
			}
			if(res == '1')
			{
				window.location.reload( true );
			}
			if(res == '4')
			{
				window.location = document.getElementById("create_user").value;
			}
		}
		});
	
		  
			 
}


function getCityFromState(targeturl,fieldid,targetid,targetid1)
{
	fieldid = "#"+fieldid;

	if (fieldid == "#state")
	{
		$(fieldid).change(function() {
			selectedId = document.getElementById("state").selectedIndex;
			stateid = document.getElementById("state").options[selectedId].value;
			$.ajax({
				type: "get",
				url: targeturl+"?state="+stateid,
				success: function(data){
						if (data==0)
						    top.location.href = '/psn/web/';
					
						citySchoolArray = data.split("-schoollist-");
						cityArray = citySchoolArray[0].split(",");
						citySelect = document.getElementById(targetid);
							
						for(i=0;i<cityArray.length;i++)
						{
							if (cityArray[i]!='')
							{
								citySelect.options[i] = new Option (cityArray[i],cityArray[i]);
							}	
						}

							
						schoolArray = citySchoolArray[1].split(",");

						schoolSelect = document.getElementById(targetid1);
						schoolSelect.options[0] =  new Option ('Select Your School:',0);
						for(i=0;i<schoolArray.length;i++)
						{
							if (schoolArray[i]!='')
							{
								schoolInfo = schoolArray[i].split(':');
								schoolSelect.options[i+1] = new Option (schoolInfo[1],schoolInfo[0]);
							}	
						}
						schoolSelect.options[schoolArray.length] =  new Option ('Add a new school','A000');
						
						// reset the school combo
						if (schoolArray.length<2)
						{
							schoolSelect.options.length=0;
							schoolSelect.options[0] =  new Option ('Select Your School:',0);
							schoolSelect.options[1] =  new Option ('Add a new school','A000');				
						}					
					}
			});
		});
	}

	if (fieldid == "#teachercity")
	{
		$(fieldid).change(function() {
			selectedId = document.getElementById("teachercity").selectedIndex;
			selectedId1 = document.getElementById("state").selectedIndex;
			cityid = document.getElementById("teachercity").options[selectedId].value;
			stateid = document.getElementById("state").options[selectedId1].value;
			
			$.ajax({
				type: "get",
				url: targeturl+"?state="+stateid+"&city="+cityid,
				success: function(data){//alert(res);
                                        if (data==0)
                                            top.location.href = '/psn/web/';

					schoolArray = data.split(",");
					schoolSelect = document.getElementById(targetid);
					schoolSelect.options.length = 0;
					schoolSelect.options[0] =  new Option ('Select Your School:',0);
					for(i=0;i<schoolArray.length;i++)
					{
						if (schoolArray[i]!='')
						{
							schoolInfo = schoolArray[i].split(':');
							schoolSelect.options[i+1] = new Option (schoolInfo[1],schoolInfo[0]);
						}	
					}
					schoolSelect.options[schoolArray.length] =  new Option ('Add a new school','A000');
 
					// reset the school combo
					if (schoolArray.length<2)
					{
						schoolSelect.options.length=0;
						schoolSelect.options[0] =  new Option ('Select Your School:',0);
						schoolSelect.options[1] =  new Option ('Add a new school','A000');				
					}										
				}
			});
	
		});
	}	

	
	if (fieldid == "#city")
	{
		$(fieldid).change(function() {
			selectedId = document.getElementById("city").selectedIndex;
			selectedId1 = document.getElementById("state").selectedIndex;
			cityid = document.getElementById("city").options[selectedId].value;
			stateid = document.getElementById("state").options[selectedId1].value;
			
			$.ajax({
				type: "get",
				url: targeturl+"?state="+stateid+"&city="+cityid,
				success: function(data){//alert(res);
                                       if (data==0)
                                            top.location.href = '/psn/web/';
					schoolArray = data.split(",");
					schoolSelect = document.getElementById(targetid);
					schoolSelect.options.length = 0;
					schoolSelect.options[0] =  new Option ('Select Your School:',0);
					for(i=0;i<schoolArray.length;i++)
					{
						if (schoolArray[i]!='')
						{
							schoolInfo = schoolArray[i].split(':');
							schoolSelect.options[i+1] = new Option (schoolInfo[1],schoolInfo[0]);
						}	
					}
					schoolSelect.options[schoolArray.length] =  new Option ('Add a new school','A000');
 
					// reset the school combo
					if (schoolArray.length<2)
					{
						schoolSelect.options.length=0;
						schoolSelect.options[0] =  new Option ('Select Your School:',0);
						schoolSelect.options[1] =  new Option ('Add a new school','A000');				
					}										
				}
			});
	
		});
	}	
}

function signout()
{
	var isFacebookUser = false;

	try
	{
		FB_RequireFeatures(["XFBML"], function()
		{
			FB.Facebook.init(document.getElementById("facebook_api_key").value, document.getElementById("facebook_receiver").value);
			FB.Facebook.get_sessionState().waitUntilReady(function()
			{
				isFacebookUser = true;
				
				FB.Connect.logout(function(){
									$.ajax({
										  type:"get" , 
										  url: document.getElementById("facebook_logout_callback").value,
										  success: function(res){window.location = document.getElementById("home_page_logged_out").value;}						   
										  });
								   return true; 
								   });
			});
		});
	}
	catch(err)
	{
		$.ajax({
		  type:"get" , 
		  url: document.getElementById("facebook_logout_callback").value,
		  success: function(res){window.location = document.getElementById("home_page_logged_out").value;}						   
		  });
	}
	
	
	if(!isFacebookUser)
	{
		$.ajax({
				  type:"get" , 
				  url: document.getElementById("facebook_logout_callback").value,
				  success: function(res){window.location = document.getElementById("home_page_logged_out").value;}						   
			 });
	}
	
	return false;
}

function displayage(yr, mon, day, unit, decimal, round){

  /*
  Ultimate Age calculator script- By JavaScript Kit (http://www.javascriptkit.com)
  Over 200+ free scripts here!
  Credit must stay intact for use
  */
  var one_day=1000*60*60*24
  var one_month=1000*60*60*24*30
  var one_year=1000*60*60*24*30*12


  today=new Date()
  var pastdate=new Date(yr, mon-1, day)
  var countunit=unit
  var decimals=decimal
  var rounding=round
  finalunit=(countunit=="days")? one_day : (countunit=="months")? one_month : one_year
  decimals=(decimals<=0)? 1 : decimals*10
  if (unit!="years"){
    if (rounding=="rounddown")
      numMonths = Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals+" "+countunit;
    else
      numMonths = Math.ceil((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals+" "+countunit;
  }
  else{
    yearspast=today.getFullYear()-yr-1
    tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0
    pastdate.setFullYear(today.getFullYear())
    pastdate2=new Date(today.getFullYear()-1, mon-1, day)
    tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals :

    Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals
    numMonths = yearspast+tail+" "+countunit;
  }
  return parseInt(numMonths);
}

function showSchool() {
  year = document.getElementById('dobYear').value;
  day = document.getElementById('dobDay').value;
  month = document.getElementById('dobMonth').value;
  ageInMonths = displayage(year, month, day, "months", 0, "rounddown");

  if ((year != 0) && (day != 0) && (month != 0)) {

       if ((ageInMonths > 30) && (!$('#controlSchool').is(":visible"))) {
          $('#controlSchool').slideDown("slow");
           $('#schoolDisplay').val(1);
       } else {
          if ($('#controlSchool').is(":visible") && (ageInMonths <= 30)) {
            $('#controlSchool').slideUp("slow");
             $('#schoolDisplay').val(0); 
          }
       }


  }
}

function showSchoolEditProfile(childSequence) {
  year = document.getElementById('dobYear' + childSequence).value;
  day = document.getElementById('dobDay' + childSequence).value;
  month = document.getElementById('dobMonth' + childSequence).value;
  ageInMonths = displayage(year, month, day, "months", 0, "rounddown");

  if ((year != 0) && (day != 0) && (month != 0)) {
       if ((ageInMonths > 30) && (!$('#controlSchool' + childSequence).is(":visible"))) {
          $('#controlSchool' + childSequence).slideDown("slow");
          $('#schoolDisplay' + childSequence).val(1); 
       } else {
          if ($('#controlSchool' + childSequence).is(":visible") && (ageInMonths <= 30)) {
            $('#controlSchool' + childSequence).slideUp("slow");
            $('#schoolDisplay' + childSequence).val(0);
          }
       }
  }
}


function submitNewChildAJAXForm(targeturl,formid,destinationtagid,redirecturl,closingtagid,opentagid,childCountObj, newChildFormAction, newChildFormSeqNum, fileUploadActionHandler) {
	  
	$('#' + formid).submit(function() {
  
          $('#submitButton' + parseInt(document.getElementById('noNameChildNum').value)).attr("disabled", "true");

          if (!isFirstNameValid(parseInt(document.getElementById('noNameChildNum').value))) {
            return false;
          }
	     // do validation.. if you want and then post it.
	      $.post
	      (targeturl, $(this).serialize(), 
	    		  function(data)
	    		  {     		        
	    	  			if (jQuery.trim(data) == "true")	 
	    	  			{   
	    	  				if (redirecturl != '')
	    	  					location.href = redirecturl;
	    	  				else
							{							    
	    	  					document.getElementById(closingtagid).style.display = "none";
								document.getElementById(opentagid).style.display = "block";
							}
	    	  			}
	    	  			else 
	    	  			{

                                                $('#submitButton' + (parseInt(childCountObj.value) - 1)).removeAttr("disabled")
	    	  				document.getElementById(destinationtagid + (parseInt(childCountObj.value) - 1)).innerHTML = data;	
                                                newChildId = $("#newChildIdId" + (parseInt(childCountObj.value))).html();
                            $('#' + closingtagid).parent().find('div.controls').slideToggle();
                            $('#' + opentagid).parent().find('a.subcontrol').slideToggle();
                            $('#' + opentagid).parent().find('div.change3').toggleText("Close","Change"); 

         

                            // Cause the new child fields to have the slide effect
							$('#childTitleSpace' + (parseInt(childCountObj.value))).click(function(){
								$(this).parent().find('div.controls').slideToggle();
                                                                $(this).parent().find('a.subcontrol').slideToggle();	
								$(this).parent().find('a.subminor').slideToggle('normal');		
							    $(this).parent().find('div.change3').toggleText("Close","Change");
							    $(this).parent().find('div.update3').toggleText("Close","Update");
							  });
							$('#childTitleProfileFields' + (parseInt(childCountObj.value))).click(function(){
								$(this).parent().find('div.controls').slideToggle();
								$(this).slideToggle();		
							    $(this).parent().find('div.change3').toggleText("Close","Change");
							    $(this).parent().find('div.update3').toggleText("Close","Update");
							  });
							  
						}
                                                if(childCountObj) {
                                                  childCountObj.value = parseInt(childCountObj.value) + 1;
                                                }

	    		  }
	      );
	      return false;

	});
}

function setEmptyChildForm(newChildFormAction, newChildFormSeqNum, fileUploadHandlerAction, getCityUrl) {
          $.post(newChildFormAction, 'newChildFormId=' + newChildFormSeqNum, function (data) {
                                                          document.getElementById('newChildFormElements').innerHTML = data;
                                                                  setProfileImageUploadEvent(newChildFormSeqNum, 'New_Child', fileUploadHandlerAction);

             setStatesDropdown(newChildFormSeqNum); // Set the state fields
             // Attach the on change events to the state and school dropdowns, This has to reset everytime the form is downloaded :(
             $('#state' + newChildFormSeqNum).change(function() {
               getCitiesFromState(getCityUrl, newChildFormSeqNum);
             });
             $('#city' + newChildFormSeqNum).change(function() {
               getSchoolsFromCity(getCityUrl, newChildFormSeqNum);
             });
                                                    });
}

function saveData(targeturl, formId) {
      // Used for notification details saving
      $.post
      (targeturl, $("#" + formId).serialize(), 
    		  function(data)
    		  {  
   	  			if (jQuery.trim(data) == "true")	 
   	  			{   	    	  			    	  			          					  
  		  			$("#" + 'controlNotify').slideToggle();	
                                        $('#mynotifications').find('div.update1').toggleText("Close","Update");	
   	  			}
    		  }
      );
      return false;  
}

function isFirstNameValid(childSequenceNumber) {

      retValue = true;
      if (jQuery.trim(document.getElementById('first_name_'+ childSequenceNumber).value) == '') {
        document.getElementById('invalidFirstNameMessage' + childSequenceNumber).style.visibility = 'visible';
        document.getElementById('first_name_'+ childSequenceNumber).focus();
        retValue = false;
      }else {
        document.getElementById('invalidFirstNameMessage' + childSequenceNumber).style.visibility = 'hidden';
      }

      year = $('#dobYear' + childSequenceNumber).val();
      day = $('#dobDay' + childSequenceNumber).val();
      month = $('#dobMonth' + childSequenceNumber).val();

      if (((year != 0) || (day != 0) || (month != 0)) && ((year == 0) || (day == 0) || (month == 0))) {
        $('#invalidBirthdateMessage' + childSequenceNumber).show();
        retValue = false;
      }else{
       $('#invalidBirthdateMessage' + childSequenceNumber).hide();
      }

      if (retValue == false) {
        $('#submitButton' + childSequenceNumber).removeAttr("disabled");
      }

      return retValue;

}

function saveChild(targeturl, formId, closingtagid, opentagid, childSequenceNumber) {    
 
      // Check if the first name is filled      


      $('#submitButton' + childSequenceNumber).attr("disabled", "true");

      if (!isFirstNameValid(childSequenceNumber)) {
        return false;
      }

      $.post
      (targeturl, $("#" + formId).serialize(), 
    		  function(data)
    		  {  
   	  			if (jQuery.trim(data) == "true")	 
   	  			{   	    	  			    	  			          					  
                  $('#' + closingtagid).parent().find('div.controls').slideToggle();
                  $('#' + opentagid).parent().find('a.subcontrol').slideToggle();
                  $('#' + opentagid).parent().find('div.change3').toggleText("Close","Change");
                  
 
                  firstname = $('#' + closingtagid).parent().find('#first_name_'+ childSequenceNumber).val();                    
                  $('#' + closingtagid).parent().find('#childFirstNameTitle' + childSequenceNumber).html(firstname);
                  $('#' + closingtagid).parent().find('#childUpdateString' + childSequenceNumber).html('Update ' + firstname + '\'s information');          
               
                  $('#submitButton' + childSequenceNumber).removeAttr("disabled");

                  }
           });
      return false;
}
                  		  							  			
function getChildData(targeturl, parChildId, parChildSequenceNumber, fileUploadHandlerAction, getCityUrl, schoolState, schoolCity, schoolId, getSchoolUrl) {

     // Get the childs school details

     $.post 
      (getSchoolUrl, {childId: parChildId}, function(data) {

         childSchoolDetails = data.split('@@##@@');
         schoolState = childSchoolDetails[0];
         schoolCity = childSchoolDetails[1]; 
         schoolId = childSchoolDetails[2]; 

     $.post
      (targeturl,{childId: parChildId, childSequenceNumber:parChildSequenceNumber} ,
                  function(data)
                  {
                    document.getElementById('childFormSpace' + parChildSequenceNumber).innerHTML = data; 
                   // Set the file upload handler
                   setProfileImageUploadEvent(parChildSequenceNumber, parChildId, fileUploadHandlerAction);

                   // Set the state event to get the city dropdown

                  $('#state' + parChildSequenceNumber).change(function() {
                   getCitiesFromState(getCityUrl, parChildSequenceNumber);
                  });

                  $('#city' + parChildSequenceNumber).change(function() {
                    getSchoolsFromCity(getCityUrl, parChildSequenceNumber);
                  });

                   // Load the school details
                   setStatesDropdown(parChildSequenceNumber, schoolState); // Set the states in the dropdown
                   getCitiesFromState(getCityUrl, parChildSequenceNumber, schoolState, schoolCity, schoolId);
 
      }); 
     });
}

function getSchoolsFromCity(getCityTargetUrl, childSequenceNumber, selectedStateValue, selectedCityValue, selectedSchoolValue, removeAddSchool) {
						if (removeAddSchool == undefined) {
    						removeAddSchool = false;
  						}

                        selectedStateId = document.getElementById("state" + childSequenceNumber).selectedIndex;
                        stateId = document.getElementById("state" + childSequenceNumber).options[selectedStateId].value;
                        citySelectObj = document.getElementById('city' + childSequenceNumber);
                        schoolSelectObj = document.getElementById('school' + childSequenceNumber);

                        requestQueryParameters = "?state=" + stateId + "&city=" + citySelectObj.options[citySelectObj.selectedIndex].value;

                        $.ajax({
                                type: "get",
                                url: getCityTargetUrl + requestQueryParameters,
                                success: function(data){
                                     // Get the school list
                                     schoolsArray = data.split(",");
                                                schoolSelectObj.options.length=0;
                                                schoolSelectObj.options[0] =  new Option ('Select Your School:',0);
                                                for(i=0;i<schoolsArray.length;i++)
                                                {
                                                  if (schoolsArray[i]!='')
                                                  {
                                                    schoolInfo = schoolsArray[i].split(':');
                                                    schoolSelectObj.options[i+1] = new Option (schoolInfo[1],schoolInfo[0]);
                                                    if ((selectedCityValue != undefined) && (schoolInfo[0] == selectedSchoolValue)) {
                                                      schoolSelectObj.options[i+1].selected = true;
                     }
                   }
                                                }
                                                arrindex = schoolsArray.length;
												if (!removeAddSchool)
                                                schoolSelectObj.options[arrindex] =  new Option ('Add a new school','A000'); // Add the Add a New School Option
       

                                                if (selectedSchoolValue == 'A000') {
                                                  schoolSelectObj.options[arrindex].selected = true;
                                                  $('#school' + childSequenceNumber + 'A000').show(); 
                                                }

 
                                 }
      }); 
   	  			}

function getCitiesFromState(getCityTargetUrl,childSequenceNumber, selectedStateValue, selectedCityValue, selectedSchoolValue, removeAddSchool) {

						if (removeAddSchool == undefined) {
    						removeAddSchool = false;
  						}
                        selectedStateId = document.getElementById("state" + childSequenceNumber).selectedIndex;
                        stateId = document.getElementById("state" + childSequenceNumber).options[selectedStateId].value;
                        citySelectObj = document.getElementById('city' + childSequenceNumber);
                        schoolSelectObj = document.getElementById('school' + childSequenceNumber);

                        // Create a data request string

                        requestQueryParameters = "?state=" + stateId;

                        $.ajax({
                                type: "get",
                                url: getCityTargetUrl + requestQueryParameters,
                                success: function(data){
						    if (data==0)
                                                        top.location.href = '/psn/web/';

							
                                                    // he schools of the first city of a state come by default
                                                    citySchoolArray = data.split("-schoollist-");

                                                    // Populate the cities
                                                    citySelectObj.options.length =0 ;
                                                    cityArray = citySchoolArray[0].split(",");
                                                    for(i=0;i<cityArray.length;i++)
                                                    {
                                                        if (cityArray[i]!='')
                                                        {
                                                                citySelectObj.options[i] = new Option (cityArray[i],cityArray[i]);                                                                                           if (selectedCityValue && jQuery.trim(cityArray[i]) == jQuery.trim(selectedCityValue)) {
                                                                  citySelectObj.options[i].selected = true;
                                                                }
                                                        }
                                                    }
                                                    schoolArray = citySchoolArray[1].split(",");


                                                // Populate the schools

                                                schoolSelectObj.options.length=0;
                                                schoolSelectObj.options[0] =  new Option ('Select Your School:',0);
                                                for(i=0;i<schoolArray.length;i++)
                                                {
                                                  if (schoolArray[i]!='')
                                                  {
                                                    schoolInfo = schoolArray[i].split(':');
                                                    schoolSelectObj.options[i+1] = new Option (schoolInfo[1],schoolInfo[0]);
                                                    if ((selectedCityValue != undefined) && (schoolInfo[0] == selectedSchoolValue)) {
                                                      schoolSelectObj.options[i+1].selected = true;
                                                    }
                                                  }
                                                }
												
												if (removeAddSchool==false)
												{
                                                schoolSelectObj.options[schoolArray.length] =  new Option ('Add a new school','A000'); // Add the Add a New School Option
												}

                                                if ((selectedSchoolValue != undefined) && (citySelectObj.selectedIndex >= 0)) {
                                                  getSchoolsFromCity(getCityTargetUrl, childSequenceNumber, stateId, citySelectObj.options[citySelectObj.selectedIndex].value, selectedSchoolValue,removeAddSchool);
                                                }

                                                if (selectedSchoolValue == 'A000') {
                                                  schoolSelectObj.options[schoolArray.length].selected = true;
                                                  $('#school' + childSequenceNumber + 'A000').show();  
                                                }

                                        }
                        });

}


function setProfileImageUploadEvent(parChildSequenceNumber, parChildId, fileUploadHandlerAction){               
                  $fileFieldObj = document.getElementById('picture' + parChildSequenceNumber);
                  if (($fileFieldObj == null) || ($fileFieldObj == undefined)) {
                    return;
                  } 
                   new Ajax_upload('#picture' + parChildSequenceNumber, {
                     action: fileUploadHandlerAction, 
                     name: 'myfile' + parChildSequenceNumber,
                     data: {childSeqNumber : parChildSequenceNumber, childId: parChildId},
                     onSubmit: function(file, ext){
                       if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                         document.getElementById('FileExtentionErrorMessage' + parChildSequenceNumber).style.visibility = 'visible';
                         return false;  
                       } else {
                         document.getElementById('FileInvalidTypeErrorMessage' + parChildSequenceNumber).style.visibility = 'hidden';  
                       }
                       document.getElementById('progressIcon' + parChildSequenceNumber).style.visibility = 'visible';    
                       $('#submitButton' + parChildSequenceNumber).attr("disabled", "true");
                       $('#submitButton' + parChildSequenceNumber).fadeTo("slow", 0.2);
                           
                     }, 
                     onComplete : function(file, response){
                            imageUrl = $(response).find('responseImageok');                          
                            // alert(imageUrl.html() + '-' + imageUrl.text());  
                             // Check if the uploaded file is valid
                             if (imageUrl.html() != null) {
                               document.getElementById('FileInvalidTypeErrorMessage' + parChildSequenceNumber).style.visibility = 'hidden';
                         document.getElementById('FileExtentionErrorMessage' + parChildSequenceNumber).style.visibility = 'hidden';
                        document.getElementById('fileToUpload' + parChildSequenceNumber).innerHTML = '<br><br><b>File to Upload:</b> ' + file;
                             } else {
                               document.getElementById('FileInvalidTypeErrorMessage' + parChildSequenceNumber).style.visibility = 'visible';
                             }
                             document.getElementById('progressIcon' + parChildSequenceNumber).style.visibility = 'hidden';
                             $('#submitButton' + parChildSequenceNumber).removeAttr("disabled");
                             $('#submitButton' + parChildSequenceNumber).fadeTo("slow", 1);

    		  }
                  });

}

function setStatesDropdown(childSeqNumber, schoolState) {
            var stateString ="AK,AL,AR,AZ,CA,CO,CT,DC,DE,FL,GA,HI,IA,ID,IL,IN,KS,KY,LA,MA,MD,ME,MI,MN,MO,MS,MT,NC,ND,NE,NH,NJ,NM,NS,NV,NY,OH,OK,ON,OR,PA,RI,SC,SD,TN,TX,UT,VA,VT,VT ,WA,WI,WV,WY";
            stateArray = stateString.split(",");
            statebox = document.getElementById('state' + childSeqNumber);
                // this function is used to fill the category list on load
                if(statebox){
                        statebox.options.length=0;
                        addOptionForChildProfileEdit(statebox,"-1","- Select State -");
                        for (i=0;i<stateArray.length;i++)
                        {
                                addOptionForChildProfileEdit(statebox, stateArray[i],stateArray[i]);
                                if (jQuery.trim(statebox.options[i].value) == jQuery.trim(schoolState)) {
                                  statebox.options[i].selected = true;
                                }
                        }
                }
}

function addOptionForChildProfileEdit(selectbox4, value, text) {
                if(selectbox4!=null)
                        selectbox4.options[selectbox4.options.length] = new Option (text,value);
}

function getCityForChildEdit(targeturl,fieldid,targetid,targetid1, childSequenceNumber, selectedCityValue, selectedSchoolValue) {

                        selectedId = document.getElementById("state" + childSequenceNumber).selectedIndex;
                        stateid = document.getElementById("state" + childSequenceNumber).options[selectedId].value;
                        $.ajax({
                                type: "get",
                                url: targeturl+"?state="+stateid,
                                success: function(data){//alert(res);
                                        if (data==0)
                                           top.location.href = '/psn/web/';								
                                                citySchoolArray = data.split("-schoollist-");
                                                cityArray = citySchoolArray[0].split(",");
                                                citySelect = document.getElementById(targetid + childSequenceNumber);

                                                for(i=0;i<cityArray.length;i++)
                                                {
                                                        if (cityArray[i]!='')
                                                        {
                                                                citySelect.options[i] = new Option (cityArray[i],cityArray[i]);
                                                                if ((selectedCityValue != undefined) && (citySelect.options[i].value == jQuery.trim(selectedCityValue))) {
                                                                  citySelect.options[i].selected = true;
                                                                }
                                                        }
                                                }


                                                schoolArray = citySchoolArray[1].split(",");

                                                schoolSelect = document.getElementById(targetid1 + childSequenceNumber);
                                                schoolSelect.options[0] =  new Option ('Select Your School:',0);
                                                for(i=0;i<schoolArray.length;i++)
                                                {
                                                        if (schoolArray[i]!='')
                                                        {
                                                                schoolInfo = schoolArray[i].split(':');
                                                                schoolSelect.options[i+1] = new Option (schoolInfo[1],schoolInfo[0]);
                                                                if ((selectedSchoolValue != undefined) && (schoolSelect.options[i].value == selectedSchoolValue)) {
                                                                  schoolSelect.options[i].selected = true;
                                                                }
                                                        }
                                                }
                                                schoolSelect.options[schoolArray.length] =  new Option ('Add a new school','A000');

                                                // reset the school combo
                                                if (schoolArray.length<2)
                                                {
                                                        schoolSelect.options.length=0;
                                                        schoolSelect.options[0] =  new Option ('Select Your School:',0);
                                                        schoolSelect.options[1] =  new Option ('Add a new school','A000');
                                                }
                                        }
                        });

}

function fillStates(selectedState, stateDropdown)
{
	var stateString ="AK,AL,AR,AZ,CA,CO,CT,DC,DE,FL,GA,HI,IA,ID,IL,IN,KS,KY,LA,MA,MD,ME,MI,MN,MO,MS,MT,NC,ND,NE,NH,NJ,NM,NS,NV,NY,OH,OK,ON,OR,PA,RI,SC,SD,TN,TX,UT,VA,VT,VT ,WA,WI,WV,WY";
	stateArray = stateString.split(",");
        if (stateDropdown == undefined) {
  	   statebox = document.getElementById('state');
        } else {
           statebox = document.getElementById(stateDropdown);
        }
     // this function is used to fill the category list on load
     if(statebox){
        statebox.options.length=0;
        addOption(statebox,"-1","- Select State -");
        for (i=0;i<stateArray.length;i++)
        {
            addOption(statebox, stateArray[i],stateArray[i]);
            if ((selectedState != undefined) && (stateArray[i] == selectedState)) {
              statebox.options[(i + 1)].selected = true;  
            }
        }
     }
}

function addOption(selectbox4, value, text )
{
        if(selectbox4!=null)
          selectbox4.options[selectbox4.options.length] = new Option (text,value);
}

function getStateFromCity(targeturl,fieldid,targetid,targetid1, childSequenceNumber) {
                        selectedId = document.getElementById("city" + childSequenceNumber).selectedIndex;
                        selectedId1 = document.getElementById("state" + childSequenceNumber).selectedIndex;
                        cityid = document.getElementById("city" + childSequenceNumber).options[selectedId].value;
                        stateid = document.getElementById("state" + childSequenceNumber).options[selectedId1].value;

                        $.ajax({
                                type: "get",
                                url: targeturl+"?state="+stateid+"&city="+cityid,
                                success: function(data){//alert(res);
                                        if (data==0)
                                           top.location.href = '/psn/web/';

                                        schoolArray = data.split(",");
                                        schoolSelect = document.getElementById(targetid + childSequenceNumber);
                                        schoolSelect.options[0] =  new Option ('Select Your School:',0);
                                        for(i=0;i<schoolArray.length;i++)
                                        {
                                                if (schoolArray[i]!='')
                                                {
                                                        schoolInfo = schoolArray[i].split(':');
                                                        schoolSelect.options[i+1] = new Option (schoolInfo[1],schoolInfo[0]);
                                                }
                                        }
                                        schoolSelect.options[schoolArray.length] =  new Option ('Add a new school','A000');

                                        // reset the school combo
                                        if (schoolArray.length<2)
                                        {
                                                schoolSelect.options.length=0;
                                                schoolSelect.options[0] =  new Option ('Select Your School:',0);
                                                schoolSelect.options[1] =  new Option ('Add a new school','A000');
                                        }
                                }
                        });


}

function getCityFromStateForChildEdit(targeturl,fieldid,targetid,targetid1, childSequenceNumber, selectedCityValue, selectedSchoolValue )
{       
        fieldid = "#"+fieldid;

        if (fieldid == "#state")
        {
                $(fieldid + childSequenceNumber).change(function() {
                  getCityForChildEdit(targeturl,fieldid,targetid,targetid1, childSequenceNumber, selectedCityValue, selectedSchoolValue);         
                });
        }


        if (fieldid == "#city")
        {
                $(fieldid + childSequenceNumber).change(function() {

                  getStateFromCity(targeturl,fieldid,targetid,targetid1, childSequenceNumber);
                });
        }
}

function checkChildrenSignupForm() {
  firstnameObj = document.getElementById('psn_child_first_name'); 
  returnValue = true;

  firstNameErrorObj = document.getElementById('invalidFirstNameMessage');
  if (jQuery.trim(firstnameObj.value) == '') {
    firstNameErrorObj.style.visibility = 'visible'; 
    firstNameErrorObj.style.display = 'block';
    firstnameObj.focus();        
    returnValue = false;
  }else {
    firstNameErrorObj.style.visibility = 'hidden';
    firstNameErrorObj.style.display = 'none';
  }

  year = document.getElementById('dobYear').value;
  day = document.getElementById('dobDay').value;
  month = document.getElementById('dobMonth').value;

  if (((year != 0) || (day != 0) || (month != 0)) && ((year == 0) || (day == 0) || (month == 0))) {
    $('#invalidBirthdateMessage').show();
    returnValue = false; 
  }else{
    $('#invalidBirthdateMessage').hide();
  }

  if (returnValue == false) {
    $('#submitButton').removeAttr("disabled");       
    $('#submitButton1').removeAttr("disabled"); 
  }

  return returnValue;
}


function saveSimpleData(targetUrl, dataToSend, reloadPage) {

             if (reloadPage == undefined) {
               reloadPage = 0;
             }

              $.post
              (targetUrl, dataToSend,
                          function(data){
                            if (reloadPage == 1) {
                              location.reload(true);
                            }

                          }
              );

}

function getSimpleData(targetUrl, dataToSend, responseDestinationId, progressImage, specialAction) {

              if (progressImage == true) {
                $('#' + responseDestinationId).innerHTML = '<img src="' + progressImage + '">';
              } else if (progressImage != undefined ) {
                $('#' + responseDestinationId).html('<tr><td colspan=4><img src="' + progressImage + '"></td></tr>');

              }

              $.post
              (targetUrl, dataToSend,
                          function(data){
                            if (specialAction == 'zip') {      
                              if (jQuery.trim(data) != '<p>There are no groups for this area.</p>') {                  
                                $.fn.colorbox({
                                  open: true,
                                  inline: true,
                                  href: '#selectLocal',
                                  overlayClose: true,
                                  title: '&nbsp;'
                                 });
                              }
                            }

                            if (specialAction == 'cityeditor') {
                              if (jQuery.trim(data) == 'Has Editors') {
                                $("#cityGuides").show(); 
                              } else {
                                $("#cityGuides").hide();
                              }
                            }

                            if (responseDestinationId != undefined) {

                              responseDestinationObj = $('#' + responseDestinationId);//document.getElementById(responseDestinationId);
                              if (responseDestinationObj) {
								$('table.posts div.removePop').hover(
									function(){$(this).show();},
									function(){$(this).customFadeOut();}
								);

/*
                                responseDestinationObj.innerHTML = data;
*/

                                //responseDestinationObj.text());
                                responseDestinationObj.html(data);

                              }
                            }


                              $("table.stuff a.addMinePop").click(function(){
                                $(this).parent().find("div.addMine").customFadeIn();
                              });
                              $("div.addMine").hover(
                                function(){$(this).show();},
                                function(){$(this).customFadeOut();}
                              );
                              $("a.friendShow").click(function(){
                                $(this).parent().parent().find(".friendList").toggleFade();
                              });
                              $("table.stuff a.moreCmts").click(function(){
                                $(this).offsetParent().find(".hidden").customFadeIn();
                                $(this).parent().hide();
                              });
							  
							  $("div.tools a.comment").click(function(){
								$(this).parent().parent().find("div.comment").customFadeIn();
								$(this).parent().customFadeOut();
							  });
							 
							  $(" a.moreCmts").click(function(){
  							  	$(this).offsetParent().find("div.comment.hidden").customFadeIn();
								$(this).parent().hide();
							  });
							  
							  $('table#friendsMore td.post').hover(function(){						
								$(this).find('div.remove').customFadeIn('slow');},
								function(){$(this).find('div.remove').hide();}
							 );
           
           
							  $('table#friendsMore a.postRemove').hover(function(){
							  	$(this).parent().next('div.removePop').customFadeIn();
								});
							  
							  $('table#friendsMore div.removePop').hover(
								function(){$(this).show();},
								function(){$(this).customFadeOut();}
							   );
							   
							   $('table#friendsMore a.friendCities').click(function(){
								$(this).parent().find('div.citiesList').customFadeIn('slow');
								});
								$('div.citiesList').hover(
									function(){$(this).show();},
									function(){$(this).customFadeOut();}
								);


                               $('td.data div.more span').click(function(){
                                 $(this).parent().find('p.detail').slideToggle();
                                 $(this).toggleText("[+]","[-]");
                               });
                               $("td.data .warntip").tooltip({track:true,delay:0,showURL:false,showBody:" - ",extraClass:"warntip",fixPNG:true,top:15,left:15});
                               $("input.checkAll").click(function(){
                                 var checkClass = $(this).attr('id');
                                 var checkState = this.checked;
                                 $('input.' + checkClass).each(function(){
                                   this.checked = checkState;
                                 });
                               });
			       
			       $('.unconfirmed').colorbox({
				inline: true,
				href: '#confirmReg',
				overlayClose: true,
				title:false
				}).bind('cbox_complete' , function() {
					$('#cboxTitle').hide();
				});

                          }
              );
}

function showNewSchoolFields(selectBoxObj, newSchoolSequenceCount) {
  newSchoolSpaceObj = document.getElementById('school' + newSchoolSequenceCount + 'A000');
  if(selectBoxObj.value == 'A000') {
    newSchoolSpaceObj.style.visibility = 'visible';
    newSchoolSpaceObj.style.display = 'block';
  } else {
    newSchoolSpaceObj.style.visibility = 'hidden';
    newSchoolSpaceObj.style.display = 'none';
  }
}

function favoritesAddToMineEvents(url, itemid, uid, categoryId, bookSelfId, cityId)
{
	url = url +"?itemid=" + itemid + "&uid=" + uid + "&categoryId=" + categoryId + "&bookSelfId=" + bookSelfId + "&cityId=" + cityId;
	$.get
	    (url,  
	    	 function(data)
	    	 {
			   //alert("test" + data);
			 }
		);
}



function getCitiesData(targetUrl, dataToSend, responseDestinationId) {
              $.post
              (targetUrl, dataToSend,
                          function(data){
                            if (responseDestinationId != undefined) {
                              responseDestinationObj = document.getElementById(responseDestinationId);
                              if (responseDestinationObj) {
								$('table.posts div.removePop').hover(
									function(){$(this).show();},
									function(){$(this).customFadeOut();}
								);
                                responseDestinationObj.innerHTML = data;
                              }
                            }
                             
							   
							   $('table#friendsMore a.friendCities').click(function(){
								$(this).parent().find('div.citiesList').customFadeIn('slow');
								});
								$('div.citiesList').hover(
									function(){$(this).show();},
									function(){$(this).customFadeOut();}
								);

                          }
              );
}

function initPhotoUpload(formAction) {  	
   var ajxUpload = new AjaxUpload('#psn_photos_image_filename', { 
    action: formAction,
	closeConnection: (/AppleWebKit|MSIE/.test(navigator.userAgent)) ? 'addPhoto/closeConnection' : null,
	name: 'psn_photos[image_filename]',
	autoSubmit: false,
	onChange: function(file, extension){
                document.getElementById('photo_filename').innerHTML = 'Image selected:' + file;
				return false;
	          },
	onSubmit: function(file, extension){
	          },			  
    onComplete: function(file, response){
				   var matchPos = response.search(/createsuccess/);
				   if(matchPos == -1) {
						document.getElementById('addPhotoerror').innerHTML = response;
		                document.getElementById('photo_filename').innerHTML = '';				
					}
					else{
						// get the new photo added
						var matchPosBegin = response.search(/<li id="/);
						if(matchPosBegin > -1 ){
							var matchPosEnd = response.search(/<\/span><\/li>/);					
							var length = (matchPosEnd + 12 ) - matchPosBegin;
							var photo = response.substr(matchPosBegin, length);
						
							// add the photo to corressp list
							var newList = '';
							var elemToAdd = null;
							var albummedPos = response.search(/unalbummed/);					
							if(albummedPos == -1 ) {
								elemToAdd = document.getElementById('albummed');
								if(elemToAdd != null){
									newList = elemToAdd.innerHTML + photo;
								}
								
							}else {
								elemToAdd = document.getElementById('unalbummed');
								if(elemToAdd != null){
									newList = photo + elemToAdd.innerHTML;
								}
							}
							
							if(elemToAdd != null){
								elemToAdd.innerHTML = newList;
							}
							
							// reset form
							document.getElementById('addPhotoForm').reset();
							document.getElementById('photo_filename').innerHTML = '';				
							$.fn.colorbox.close();
						}else {
							window.location.href = window.location.href;
						}
					}
		}
    });
   
    $('#addphotobutton').click(function(){
				
		var serialize = $('#addPhotoForm').serialize();
		serialize = serialize.replace(/\+/g, ' ');
		serialize = decodeURIComponent(serialize);
		
		// handle multiple choices , arrays
		var count = 0;
		while(serialize.search(/\[\]/) != -1 ) {
			serialize = serialize.replace(/\[\]/, '_ob_' + count + '_cb_' );
			count++;
		}
		serialize = serialize.replace(/\]/g, '_cb_');
		serialize = serialize.replace(/\[/g, '_ob_');	
		
		
		// let's remove the image buttons that weren't clicked on
		var formData = [];
		formData.push("ajax:'1'");
		var params = serialize.split("&");
		for (var i=0 ; i<params.length; i++) {
			var param =  params[i].split("=");
			if('psn_photos[image_filename]' != param[0] && param[1] != ''){
				param[0] = param[0].replace(/\]/, '_cb_');
				param[0] = param[0].replace(/\[/, '_ob_');
				
				var jsonFormat =  param[0] +  ":'" + param[1] + "'";
				formData.push(jsonFormat);
			}
		}
		eval('serialize = {' + formData.join(',') + '};');
		
		ajxUpload.setData(serialize);
		
		ajxUpload.submit();
		return false;
	});

}

function managePagination(selNum, set, url, data, destination, totNum, progressImage, operation) {


//  alert(selNum);
  numPages = parseInt($('#' + set + 'a').attr('numPages'));
  aObjs = $('#' + set + 'a').find('a');
  aObjs.each (function() {
    if ($(this).attr('style') == 'font-weight:bold;') {
      if (operation == 'next') {
        selNum = parseInt($(this).text()) + 1;
  if (selNum > numPages) {
          selNum = numPages;
        }
  }
      if (operation == 'prev') {
        selNum = parseInt($(this).text()) - 1;
        if (selNum <= 0) {
          selNum = 1;
        }  
      }      
    }
  });


  numPerTab1 = parseInt($('#numPerTab').html());
  dataUrl = $('#dataUrl').html();

  startPageItem = (numPerTab1 * (selNum - 1)) + 1;
  endItem = (startPageItem + numPerTab1 - 1);

  endPageIndex = (endItem > totNum) ? totNum : endItem;

  $('#' + set + 'ais').html(startPageItem);
  $('#' + set + 'aie').html(endPageIndex);

  $('#' + set + 'bis').html(startPageItem);
  $('#' + set + 'bie').html(endPageIndex);


  getSimpleData(url, ((data == undefined) ? '' : data + '&') + 'pageNum=' + selNum, destination, progressImage);

  aObjs = $('#' + set + 'a').find('a');
  // Select what will be the start page number


  index = 0;
  aObjs.each(function() {
    presentValue = parseInt($(this).text());
    if (index == 0) {
      maxDispPage = presentValue;
      minDispPage = presentValue;
    }

    if (presentValue > maxDispPage) {
      maxDispPage = presentValue;
    }

    if (presentValue < minDispPage) {
      minDispPage = presentValue;
    }
    index ++;
  });

//  alert('setNum' + selNum + 'minDisp' + minDispPage + 'maxDisp' + maxDispPage);

  startIndex = 1;

  if (minDispPage == 1 && selNum == 1) {
    startIndex = 1;
  } else if (selNum == minDispPage) {
      startIndex = minDispPage - 1;
  } else if (selNum > minDispPage && selNum < maxDispPage) {
      startIndex = minDispPage;
  } else if (selNum == maxDispPage && ((parseInt(selNum) + 1 ) <= numPages)) {
      startIndex = parseInt(minDispPage) + 1;
  } else if (selNum == numPages) {
      startIndex = minDispPage;
  }

//  alert('start index' + startIndex);

  //alert('MIN' + minDispPage + 'MAX' + maxDispPage);

  index = startIndex;
  sets1 = [set + 'a', set + 'b'];

  jQuery.each(sets1, function() {
    $('#' + this).find('a').each(function() {
      $(this).text(index);
      $(this).attr('href', 'javascript:;');
      if (selNum == index) {
        $(this).attr('style', 'font-weight:bold;');
      } else {
        $(this).attr('style', 'font-weight:normal;');
      }

      $(this).unbind("click");

      $(this).click(function() {
        managePagination($(this).text(), set, url, data, destination, totNum, progressImage);
      });

      index ++;
    });
    index = startIndex;
  });

  jQuery.each(sets1, function(q) {

    prevObj = $('#' + this + 'P');
    prevObj.unbind("click");
      setPrevNum = (selNum > 1) ? (selNum - 1) : 1;

    prevObj.click(function() {
      managePagination(setPrevNum, set, url, data, destination, totNum, progressImage, 'prev');
    });

    if (minDispPage <= 1 && selNum <= 1) {
      prevObj.hide();
    } else {
      prevObj.show();
    }

    nextObj = $('#' + this + 'N');
    nextObj.unbind("click");
    setNextNumber = (selNum + 1) <= numPages ? (selNum + 1) : selNum;
//    alert(nextObj.attr('id') + ' Next ' + setNextNumber + ' sel ' + selNum + ' set ' + set);
    nextObj.click(function() {
      managePagination(setNextNumber, set, url, data, destination, totNum, progressImage, 'next');
    });








    if (maxDispPage  >= numPages && selNum == numPages) {
      nextObj.hide();
    } else {
      nextObj.show();
    }

    if (maxDispPage == minDispPage) {
      prevObj.hide();
      nextObj.hide();
    }

  });

  // Generate the page string

  pageStr = '';

}

function setUpPagination(set, url, data, destination, totNum, progressImage) {
  objs = $('#' + set).find('a');
  objs.each(function() {
  $(this).click(function() {
       managePagination($(this).text(), set, url, data, destination, totNum, progressImage);
     });
   });

   managePagination(1, set, url, data, destination, totNum, progressImage);

}


function membergroups(targeturl,groupid,fieldname,order,limit,page,total_page,mode,keyword)
{
	var urlstring='';
	if(groupid != null)
		urlstring = urlstring +'groupId='+groupid;

	if(fieldname != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&fieldname="+fieldname;
		 else
		   urlstring = urlstring+"fieldname="+fieldname;
	}

	if(order != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&orderby="+order;
		 else
		   urlstring = urlstring+"orderby="+order;
	}
	
	if(limit != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&limit="+limit;
		 else
		   urlstring = urlstring+"limit="+limit;
	}
	
	if(total_page != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&total_page="+total_page;
		 else
		   urlstring = urlstring+"total_page="+total_page;
	}
	
	if(page != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&page="+page;
		 else
		   urlstring = urlstring+"page="+page;
	}

	if(mode != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&mode="+mode;
		 else
		   urlstring = urlstring+"mode="+mode;
	}
	
	if(keyword != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&keyword="+keyword;
		 else
		   urlstring = urlstring+"keyword="+keyword;
	}
	
	if(urlstring != '')
		var targeturl_new = targeturl+"?"+urlstring;
	else
		var targeturl_new = targeturl;
		

		
	$.ajax({
                 type: "GET",
                 url: targeturl_new,
                 //dataType: "xml",
                 success: function(xml) {
                   $("#container").empty();
                   $("#container").html(xml);		  
                 }
             });
}




// Added by Shambhavi and Anjali
function GetGroupsAjax(targeturl,responseDestinationId)
{

	$.ajax({
                 type: "GET",
                 url: targeturl,
                 success: function(xml) {
					$(responseDestinationId).empty();
                    $(responseDestinationId).html(xml);
			 $(responseDestinationId).show();
					if(responseDestinationId=="#groupsPop")
					{	
						
						$("#groupshome span").removeClass("tabs-selected");
						$("#populargroups").addClass("tabs-selected");
						$("#groupsNew").hide();
						$("#groupsAll").hide();
						$("#groupsSrc").hide();
						$('.unconfirmed').colorbox({
					         inline: true,
					         href: '#confirmReg',
					         overlayClose: true
					         });
					}
					else
					{	
						$("#groupshome span").removeClass("tabs-selected");
						$("#newestgroups").addClass("tabs-selected");	
						$("#groupsPop").hide();
						$("#groupsAll").hide();
						$("#groupsSrc").hide();
						$('.unconfirmed').colorbox({
                                                 inline: true,
                                                 href: '#confirmReg',
                                                 overlayClose: true
                                                 });
					}
                 }
             });


}


// Added by Shambhavi and Anjali
function joinGroup(targetUrl,dataToSend,responseDestinationId)
{

	 $.post
              (targetUrl, dataToSend,
                          function(data){
                            if (responseDestinationId != undefined) {
                              responseDestinationObj = document.getElementById(responseDestinationId);
                              if (responseDestinationObj) {
								
                                responseDestinationObj.innerHTML = data;
                              }
                            }
                             
                          }
              );

	
}


// Added by Shambhavi and Anjali
function getGroups(targetUrl,dataToSend,responseDestinationId)
{

	$.post
              (targetUrl, dataToSend,
                          function(data){

                            if (responseDestinationId != undefined) {
                              responseDestinationObj = document.getElementById(responseDestinationId);
                              if (responseDestinationObj) {

                                responseDestinationObj.innerHTML = data;
                              }
                            }
							$(responseDestinationId).show();
							$("#groupshome span").removeClass("tabs-selected");
							$("#mygroups").addClass("tabs-selected");
                			$("#groupsPop").hide();
							$("#groupsNew").hide();
							$("#groupsSrc").hide();
                          }
              );

}



function checkRecommendExpertsForm() {

	
  firstnameObj = document.getElementById('first_name'); 
  lastnameObj = document.getElementById('last_name'); 
  publicationsObj = document.getElementById('publications'); 
  contentObj = document.getElementById('content');
  
  //test = $("input[name='category']").getValue();
  //test = $("input[type='checkbox']");
  interestChecked = false;
  interests = document.getElementsByName('category[]');

  for(index=0; index < interests.length; index ++) {
	if (interests[index].checked)			
	{
		interestChecked = true;
		break;
	}
  }
  
  returnValue = true;
  errorfname = false;
  errorlname = false;
  errorpublications = false;
  errorcontent = false;
  
  if (jQuery.trim(firstnameObj.value) == ''  || jQuery.trim(firstnameObj.value) == 'First Name') {
    firstNameErrorObj = document.getElementById('invalidFirstNameMessage');
    firstNameErrorObj.style.visibility = 'visible'; 
    firstNameErrorObj.style.display = 'inline';
    //firstnameObj.focus();        
    errorfname = true;
  }
  else
  {
	firstNameErrorObj = document.getElementById('invalidFirstNameMessage');
    firstNameErrorObj.style.visibility = 'visible'; 
    firstNameErrorObj.style.display = 'none';
	errorfname = false;
  }

  if (jQuery.trim(lastnameObj.value) == ''  || jQuery.trim(lastnameObj.value) == 'Last Name') {
    lastNameErrorObj = document.getElementById('invalidLastNameMessage');
    lastNameErrorObj.style.visibility = 'visible'; 
    lastNameErrorObj.style.display = 'inline';
    //lastnameObj.focus();        
	
    errorlname = true;
  }
  else
  {
	lastNameErrorObj = document.getElementById('invalidLastNameMessage');
    lastNameErrorObj.style.visibility = 'visible'; 
    lastNameErrorObj.style.display = 'none';
    errorlname = false;
  }
   	  
  
   if (jQuery.trim(publicationsObj.value) == '') {
    publicationsErrorObj = document.getElementById('invalidPublicationsMessage');
    publicationsErrorObj.style.visibility = 'visible'; 
    publicationsErrorObj.style.display = 'block';
   // publicationsErrorObj.focus();        

    errorpublications = true;
  }
  else
  {
	publicationsErrorObj = document.getElementById('invalidPublicationsMessage');
    publicationsErrorObj.style.visibility = 'visible'; 
    publicationsErrorObj.style.display = 'none';
  

    errorpublications = false;
  }
  
   if (jQuery.trim(contentObj.value) == '') {
    contentErrorObj = document.getElementById('invalidContentMessage');
    contentErrorObj.style.visibility = 'visible'; 
    contentErrorObj.style.display = 'block';
   // contentErrorObj.focus();        

    errorcontent = true;
  }
  else
  {
	contentErrorObj = document.getElementById('invalidContentMessage');
    contentErrorObj.style.visibility = 'visible'; 
    contentErrorObj.style.display = 'none';
   // contentErrorObj.focus();        

    errorcontent = false;
  }
  
  
  if(interestChecked==false)
  {
	expertiseErrorObj = document.getElementById('invalidExpertiseMessage');
    expertiseErrorObj.style.visibility = 'visible'; 
    expertiseErrorObj.style.display = 'block';
  }
  else
  {
	expertiseErrorObj = document.getElementById('invalidExpertiseMessage');
    expertiseErrorObj.style.visibility = 'visible'; 
    expertiseErrorObj.style.display = 'none';
  }
  
  
  if(errorfname == false && errorlname == false && errorpublications == false && errorcontent == false && interestChecked==true)
  {
	 
	  returnValue = true;
  }
  else
  {
	  //alert('fname'+ errorfname);
	 // alert('lname'+ errorlname);
	  //alert('pub'+ errorpublications);
	  //alert('cont'+ errorcontent);
	  //alert(test);
	  returnValue = false;
	
  }

  return returnValue;
}

function getFriendsLikeThis(url, groupid, itemid, itemtype, divid)
{
	if(groupid == -9999) //in case of groupPlaces
	{
		var dataToSend = {
			itemId:itemid,
			itemType:itemtype
			};
	}
	else
	{
	var dataToSend = { 
			 			groupId:groupid,
			 			itemId:itemid
			    	 };
	}
	$cont = jQuery.trim(document.getElementById(divid).innerHTML);
	
	if($cont.length <= 0)
	{
		$.get
		    (url, dataToSend,
				function(data)
				{
					document.getElementById(divid).innerHTML = data;
				
				});
	}
	else
	{
		document.getElementById(divid).innerHTML = "";
	}
}


/*Friends Search AJAX
Targeturl = URL NAME
keyword = keyword to be searched in the database
Currentpage = Current page no
startwith = start page no with
previous Page = Previous page no
Next Page = Next Page No
*/
function FriendSearchAjax(targeturl,keyword, currentpage, startwith, goprev, gonext,endwith)
{
	var urlstring='';
	if(keyword != null)
		urlstring = urlstring +'keyword='+keyword;

	

	if(currentpage != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&currentpage="+currentpage;
		 else
		   urlstring = urlstring+"currentpage="+currentpage;
	}

	if(startwith != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&startwith="+startwith;
		 else
		   urlstring = urlstring+"startwith="+startwith;
	}

	if(goprev != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&goprev="+goprev;
		 else
		   urlstring = urlstring+"goprev="+goprev;
	}

	if(gonext != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&gonext="+gonext;
		 else
		   urlstring = urlstring+"gonext="+gonext;
	}

	if(endwith != null)
	{
		if(urlstring != '')
		  urlstring = urlstring + "&endwith="+endwith;
		 else
		   urlstring = urlstring+"endwith="+endwith;
	}

	if(urlstring != '')
		var targeturl_new = targeturl+"?"+urlstring;
	else
		var targeturl_new = targeturl;

	$.ajax({
                 type: "GET",
                 url: targeturl_new,
                 //dataType: "xml",
                 success: function(xml) {
                   $(".cellSettings").empty();
                   $(".cellSettings").html(xml);

                 }
             });
}


/*Source settings validation 
Added by shambhavi
*/

function validateSourceSettings()
{
	var c_value = 0;
	var flag  = false;
	var count = document.sourcEditForm.elements['cat[]'].length;
	var bio = $('#sourcebio').val();
	var validate = false;
	var val;
	var len = bio.length;
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var address = $("#sourceemail").val();
	address = (address).replace(/^\s*|\s*$/g,'');
	for(var i=0; i <count; i++)
	{
		val =document.sourcEditForm.elements['cat[]'][i].checked;
		if(val)
		{
			 c_value++;
		}
	}
	
 	if(c_value >5 || c_value==0)
 	{	
	  $("#err").show();	
		validate = true;
 	}
	if(len > 300)
	{
		
		$("#Bioerr").show();
		validate = true;
	}
	if(address)
	{
		if(reg.test(address) == false) {
			validate = true;
			$('#email').text('Invalid Email Address');
		}
	}
	else if(address=='' || reg.test(address) == true) {
			$('#email').text('');
	}
	if($('#image_source').val() != '') {
    	var fileName = $('#image_source').val();
        var extn = fileName. substr((fileName.length-3),3);
		if(extn.toLowerCase()!='png' && extn.toLowerCase()!='jpg' && extn.toLowerCase()!='gif') {
			validate = true;
            $('#image_source').prev('div.red').text('Invalid file');
        } else {
            $('#image_source').prev('div.red').text('');
        }
    }
		
	if(validate){
	
		return false;
	}
	else if(!validate)
	{
		return true;	
	}
}
function validateSource()
{
	var c_value = 0;
	var count = document.becomesource.elements['cat[]'].length;
	var val ;
	
	for(var i=0; i <count; i++)
	{
		val =document.becomesource.elements['cat[]'][i].checked;
		if(val)
		{
				 c_value++;
		}

	}
	if(c_value <=5 && c_value!=0)
  	{
	  return true;  
  	}
 	else if(c_value >5 || c_value==0)
 	{	
	  $("#err").show();	
	 	return false;
 	}
   
  
}

//code added by ellison starts
function followSource(idCount,follow){
	var siteUrl = $('#site_base_url').val();
	var baseSiteUrl =  siteUrl.substr(0,siteUrl.lastIndexOf("/"));
	baseSiteUrl1 =  baseSiteUrl.substr(0,baseSiteUrl.lastIndexOf("/"));
	$.ajax({
		 type: "POST",
		 url: siteUrl+"sources/followSource/sourceId/"+idCount,
		 dataType: "text",
		 data:{follow: follow},
		 success: function(text) {
		 	if(text==0){
		 		//fPopupSmall(baseSiteUrl+'/followSource.html'); 
		 		window.location = baseSiteUrl+"/sources/home";
		 	}else{
		 		window.location = baseSiteUrl+"/sources/home";
		 	}
		 }
	 });
}
function showMoreReccomended(obj,moduleName,excludedIds){
	var siteUrl = $('#site_base_url').val();
	$.ajax({
		 type: "POST",
		 url: siteUrl+"sourceModules/recommended",
		 dataType: "text",
		 data:{moduleName: moduleName,excludedIds:excludedIds},
		 success: function(text) {
		 	if(moduleName == 'recommend'){
		 		$('#expertsRecMore').html(text);
		 		$('#expertsRecMore').slideToggle();
		 	}else{
		 		$('#expertsPopMore').html(text);
		 		$('#expertsPopMore').slideToggle();
		 	}
		 	$(obj).parent().hide();
		 }
	 });
}

//code added by ellison ends

function getSourcesAjax(targeturl,destinationId)
{

	if(destinationId=="#sourcesAll")
	{
		$(destinationId).show();
		$("#source li").removeClass("tabs-selected");
		$("#alltab").addClass("tabs-selected");
		$("#sourcesPop").hide();
		$("#sourcesNew").hide();
		$("#sourcesSrc").hide();

	}
	else
	{	
		/*if($(destinationId).html()=='')
		{*/
		$.ajax({
					 type: "GET",
					 url: targeturl,
					 success: function(data) {
						$(destinationId).empty();
						$(destinationId).html(data);
						$(destinationId).show();
						showHideTabs(destinationId);
					 }
				 });
		/*}else{
			$(destinationId).show();
			showHideTabs(destinationId);
		}*/
	}

}

function showHideTabs(destinationId)
{
	if(destinationId=="#sourcesPop")
	{	
		$("#source li").removeClass("tabs-selected");
		$("#populartab").addClass("tabs-selected");
		$("#sourcesAll").hide();
		$("#sourcesNew").hide();						
		$("#sourcesSrc").hide();
	}
	else if(destinationId=="#sourcesNew")
	{	
		$("#source li").removeClass("tabs-selected");
		$("#newesttab").addClass("tabs-selected");
		$("#sourcesAll").hide();
		$("#sourcesPop").hide();						
		$("#sourcesSrc").hide();
	}	
}



