function kEnter(event){
	if(event.keyCode==13){ 
		$(".btntext").click();
	    }
	
  
}
var flipElement = function(targetElement){
	var elem = document.getElementById(targetElement);
	if(elem.style.display != 'none')
		elem.style.display = 'none'
	else
		elem.style.display='';
}
function checkAddPage(handle,isFull){

var ws_ajax_path_prefix = $("#thickboxContext").val();	
var path = $(handle).attr("name");
var pageLimit = $(handle).attr("pageLimit");
if(isFull=="true")
isFull =true;
else if(isFull=="false")
isFull =false;

	if(isFull)
	{

	 var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
	 messageWindow("You have reached your page limit of "+pageLimit+" pages for this account level",dialogueUrl);	
	}else
	{
	//ws_ajax_path_prefix = "http://"+window.location.host+"/";
	//alert(ws_ajax_path_prefix+path);

	window.location=ws_ajax_path_prefix+path;
	
	}
	  
}
function checkEditPage(handle,isFull){

	var ws_ajax_path_prefix = $("#thickboxContext").val();	
	var path = $(handle).attr("name");
	var pageLimit = $(handle).attr("pageLimit");
		if(isFull)
		{
		 var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=DuWindow";
		 populWindow("You have reached your page limit of "+pageLimit+" pages for this account level",dialogueUrl);	
		 $("#editUrl").val(ws_ajax_path_prefix+path);
		}else{
			window.location=ws_ajax_path_prefix+path;
		}
		//ws_ajax_path_prefix = "http://"+window.location.host+"/";
		//alert(ws_ajax_path_prefix+path);
	
	//window.location=ws_ajax_path_prefix+path;
}
function editUrl()
{
	var url=$("#editUrl").val();
	tb_remove();
	window.location=url;
}

var changeHide = function(showId, hideId, flipDiv){
	document.getElementById(showId).style.display = 'none';
	document.getElementById(hideId).style.display = '';
	flipElement(flipDiv);
	repositionMask();
}


var textLimit = function(obj,maxlength){
		if (obj.value.length > maxlength){
			obj.value = obj.value.substring(0, maxlength);
		}
}
//only allow a-z,A-Z,0-9,-,_,
var charLimit = function (obj){
	obj.value = obj.value.replace(/[^a-zA-Z0-9 \-_]/g,"");
	obj.value = obj.value.replace(/\s/g,"-");	
}
var populWindow = function(content,url){
	$("#DuWindow .msgContent").html(content);	
	tb_initForce(url);
};
var messageWindow = function(content,url){
	$("#MessageWindow .msgContent").html(content);	
	tb_initForce(url);
};	
var oriIndex;
var isFull = false;
var wordLimit = function(obj,maxCount,delimiter){
	var wordLength = 20;
		if (isFull){
			//obj.value = obj.value.replace(/.*/g,"");
		}else {
			obj.value = obj.value.replace(/[^a-zA-Z0-9 ]/g,"");
		}
		
		
		var   r   =   /\b[a-zA-Z0-9]+\b/g;
		var returnString = "";
		//alert(obj.value.match(r).length);
		if (obj.value != "" && obj.value.match(r)){ 
			if (obj.value.match(r).length>maxCount){
				var str = obj.value;
				
				obj.value = str.substring(0,oriIndex);
				
				
			}else{
				oriIndex = obj.value.length;
			}
		}else{
			obj.value = "";
		}
	

		obj.value = obj.value.replace(/\s{2}$/g,"");
		
		var keys = obj.value.split(" ");
					
		for (var i=0;i<keys.length;i++){
			if (keys[i].length > wordLength){
				keys[i] = keys[i].substring(0,wordLength);
			}
			returnString +=keys[i];
			if (i<keys.length-1) returnString += " ";
		}
		
		obj.value = returnString;
}

var showWebURL = function(){
	var extURLValue = document.getElementById("webURLInput").value;
	var previewElem = document.getElementById("previewLabel");
	//alert("its value is :: "+extURLValue);
	if(extURLValue.length>0){
		//previewElem.style.display='';
		previewElem.innerHTML = 'http://www.websketch.com/sites/'+extURLValue; 
	}
}

var flipElementWithCSSDefined = function(targetElement,thisHandler,expandClass,shrinkClass){
	var elem = document.getElementById(targetElement);
	if(elem.style.display != 'none'){
		elem.style.display = 'none';
		$(thisHandler).html("Show Latest");	
	}else{
		elem.style.display='';
		$(thisHandler).html("Hide Latest");		
	}
}
var changeHideWithCallBack = function(showId, hideId, flipDiv,callback){
	document.getElementById(showId).style.display = 'none';
	document.getElementById(hideId).style.display = '';
	flipElement(flipDiv);
	if (callback!=null){
		(callback)()
	}
}

var changeUserTable = function featuredsEnabled(userId,displayOption)
{
	$.ajax({url:"featuredsAble?displayOption="+displayOption+"&userId="+userId,
               type: 'GET',
               dataType: 'html',
               timeout: 10000,
               error: function(){ 
               },
              success:function(html){}
	});
}

var flipFeaturedsElement = function(targetElement){
	var elem = document.getElementById(targetElement);
	if(elem.style.display != 'none')
		elem.style.display = 'none'
	else
		elem.style.display='';
}

var changeFeaturedsHide = function(showId, hideId, flipDiv,userId,displayOption){
	document.getElementById(showId).style.display = 'none';
	changeUserTable(userId,displayOption);
	document.getElementById(hideId).style.display = '';
	flipFeaturedsElement(flipDiv);
}

var deleteComment = function(commentId,commentBlock,commentHrId)
{

	var url = window.location.toString().split('sites');
	$.ajax({url:url[0]+'removeComment?commentId='+commentId,
               type: 'GET',
               dataType: 'html',
               timeout: 10000,
               error: function(){ 
               },
              success:function(html){}
	});
	$("#"+commentBlock).remove(0);
	$("#"+commentHrId).remove(0);
	var size = $(".commentBlock").length;
	var commentSize ="";
		if(size==0)
			commentSize ="";
		else if(size==1)
		 	commentSize ="1 Comment";
		else
			commentSize =size+" Comments";
	$(".commentCount").html(commentSize);
}

function checkLoginStatus(handle){
		var context = $(handle).attr("rel");
		var path = $(handle).attr("name")+"&deletesubmit=1";
		
$.getJSON(context+"/session?callback=?",
					  function(json){	
							if (json.session=="true") {
									var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=DeleteWindow";	
									messageWindow("",dialogueUrl);	
									$("#deleteUrl").val(path);
							}else{
								window.location=context+"login";
							}
					}
		  );


}
function deleteCommentInView(){
			var context = $("#thickboxContext").val();	
			var query = $("#deleteUrl").val();

		$.getJSON(context+query+"&callback=?",
				   function(json){
					  if (json != "") {
								
									window.location.reload(true);							
								}
					  tb_remove();
				   }
				);	
}

function checkConfirm(handle){
		var context ="http://"+document.location.host;
		var userId = $("#userId").val();
		var flag = $("#flag").val();
		//var statChecked=$("#setSubscriptionFlag").attr("checked")
			    
		var path = "deleteWarning?type=subscription&delete=870121235617951125&deletesubmit=1&userId=";
		if(flag=="false" && $("#site_0").attr("checked")==true)
		 $("#deletecontent").html("Are you sure you want to re-enable your subscription?");
		
		var siteValuePost =$('input[@name=site][@checked]').val();
		if((siteValuePost=="0"  && flag=="false") 
			||(siteValuePost=="1" && flag=="true" )  )
			
			{
		  	$.getJSON(context+"/session?callback=?",
					  function(json){	
							if (json.session=="true") {
									var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=DeleteWindow";	
									messageWindow("tttt",dialogueUrl);	
									$("#deleteUrl").val(path+userId);
							}else{
								window.location=context+"login";
							}
					}
				);
		  }
		  /*
		if(($("#setSubscriptionFlag").attr("checked")==true && flag=="false" ) 
			||($("#setSubscriptionFlag").attr("checked")==null && flag=="true" )  )
		  {
		  	$.getJSON(context+"/session?callback=?",
					  function(json){	
							if (json.session=="true") {
									var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=DeleteWindow";	
									messageWindow("tttt",dialogueUrl);	
									$("#deleteUrl").val(path+userId);
							}else{
								window.location=context+"login";
							}
					}
				);
		  }
		  */

}
function setSubscription(){
			var context ="http://"+document.location.host;
			var query = $("#deleteUrl").val();
			$("#confirm").hide();
			$("#shareNoteLoading").html("<img src='"+context+"/js/thickbox/loadingAnimation.gif' >");
			$("#shareNoteLoading").show();
		$.getJSON(context+"/"+query+"&callback=?",
				   function(json){
					  if (json != "") {
							window.location.reload(true);							
						}
					  tb_remove();
				   }
				);	
}


function deleteCategoryConfirm(handle){
		var context ="http://"+document.location.host;
		var categoryId = $("#categoryId").val();
		var categoryName=$("#categoryName").attr("value");
		var type=$("#type").val();
		//var flag = $("#flag").val();
		//var statChecked=$("#setSubscriptionFlag").attr("checked")
		if($("#categoryId").attr("value")=="" || $("#categoryId").attr("value")==null ){
			 var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
			 messageWindow("You must chose category",dialogueUrl);
		 }else if(categoryId=="1"){
		     var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
			  messageWindow("You can't  delete  Root",dialogueUrl);
		 }else{
		 	 $("#deletecontent").html("Are you sure you want to delete your category "+categoryName+" ?");
		var path = "deleteWarning?type=categoryTree&delete="+categoryId+"&deletesubmit=1&categorytype="+type+"&userId=";

		  	$.getJSON(context+"/session?callback=?",
					  function(json){	
							if (json.session=="true") {
									var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=DeleteWindow";	
									messageWindow("tttt",dialogueUrl);	
									$("#deleteUrl").val(path);
							}else{
								window.location=context+"login";
							}
					}
				);
			}
		 
}

function publishConfirm(handle){
		var context ="http://"+document.location.host;
		var categoryId = $("#categoryId").val();
		
		//var flag = $("#flag").val();
		//var statChecked=$("#setSubscriptionFlag").attr("checked")
		if(categoryId==null){
			 var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
			 messageWindow("You must chose parent category",dialogueUrl);
		 }else{
		 	// $("#deletecontent").html("Are you sure you want to delete your category "+categoryId+" ?");
		//var path = "deleteWarning?type=subscription&delete=870121235617951125&deletesubmit=1&userId=";

		  	$.getJSON(context+"/session?callback=?",
					  function(json){	
							if (json.session=="true") {
									window.location=context+"/adminCategoryTree?add="+categoryId;
							}else{
								window.location=context+"login";
							}
					}
				);
			}
		 
}

function saveTemplatesCategory(handle){
		var context ="http://"+document.location.host;
		var categoryId = $("#categoryId").val();
		
		//var flag = $("#flag").val();
		//var statChecked=$("#setSubscriptionFlag").attr("checked")
		if(categoryId==null){
			 var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
			 messageWindow("You must chose parent category",dialogueUrl);
		 }else{
		 	// $("#deletecontent").html("Are you sure you want to delete your category "+categoryId+" ?");
		//var path = "deleteWarning?type=subscription&delete=870121235617951125&deletesubmit=1&userId=";

		  	$.getJSON(context+"/session?callback=?",
					  function(json){	
							if (json.session=="true") {
									window.location=context+"/admintemplatescategory?add="+categoryId;
							}else{
								window.location=context+"login";
							}
					}
				);
			}
		 
}

function deleteCategory(){

			var context ="http://"+document.location.host;
			var query = $("#deleteUrl").val();
			var type=$("#type").val();
			$("#confirm").hide();
			$("#shareNoteLoading").html("<img src='"+context+"/js/thickbox/loadingAnimation.gif' >");
			$("#shareNoteLoading").show();
		$.getJSON(context+"/"+query+"&callback=?",
				   function(json){
					  if (json.flag == "true") {
					  		window.location=json.url;				
					  }
					  tb_remove();
				   }
				);	
}



function editMultiComment(commentId){
	// comment_2 div div div span
	 $(".commentBody .inline-edit #"+commentId).click()
}

function Trim  (str){
        return str.replace(/(^\s*)|(\s*$)/g, "");
}

function createSite(){
		var context ="http://"+document.location.host+"/";	
		var isExit = $("#thickboxContext").length;
		
		if (isExit>0)
		  context =$("#thickboxContext").val();
		
		    
		//var noteId = $("#splashnoteId").val();
		
		//var pageLimit = $("#pageLimit").val();
	  
			$.ajax({url:context+"pageLimit?option=add&callback=?",
	                 type: 'GET',
	                 dataType: 'json',
	                 timeout: 10000,
	                 error: function(){ },
	                success:function(json){
	                if (json.isFull=="true") {
	                	
				 var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
				 messageWindow("You have reached your page limit of "+json.pageLimit+" pages for this account level",dialogueUrl);	
	                }else {
	                	
					  //  window.location.href="editor";
					    window.location=context+"editor";
						}
	                 	   
			   }
			});
		
	 	
	};		
	
function createSiteForHeader(){
	     var context ="http://"+document.location.host;
		if(document.location.pathname.indexOf("upgrade")>-1 && document.location.href.indexOf("https")>-1)
		  context = "https://"+document.location.host;
			
		var noteId = $("#splashnoteId").val();
		
		var pageLimit = $("#pageLimit").val();
	  
			$.ajax({url:context+"/pageLimit?option=add",
	                 type: 'GET',
	                 dataType: 'json',
	                 timeout: 10000,
	                 error: function(){ },
	                success:function(json){
	                if (json.isFull=="true") {
				 var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
				 messageWindow("You have reached your page limit of "+json.pageLimit+" pages for this account level",dialogueUrl);	
	                }else {
					    window.location.href=context+"/editor";
						}
	                 	   
			   }
			});
		
	 	
	};	
	
function userFormButtonClick(userFormId){
	
	var required_vars =$("#required_"+userFormId).val();
	var opt_vars =$("#optVars_"+userFormId).val();
	var ws_ajax_path_prefix = $("#thickboxContext").val();
			var query = "userFormId="+userFormId;
			
			var requiredArray = new   Array();
			var optvarsArray = new   Array();  
			
			
			if(required_vars!="")  
			requiredArray=required_vars.split(",");
			
			if(opt_vars!="")  
				optvarsArray=opt_vars.split(",");
				
			//alert(requiredArray);
			for(var i=0;i<requiredArray.length;i++)
			{
				var objectui=$("input[name="+requiredArray[i]+"]");
				//alert(i+"=="+objectui.attr("type")+"=="+requiredArray[i]);
				if(objectui.attr("type")=="radio")
				//if($("#"+requiredArray[i]).attr("type")=="radio")
				{
					//alert("radio");
					//query+="&"+$("#"+requiredArray[i]).attr("name")+"="+$("#"+requiredArray[i]+"").val();
					//var   objradio = $("input[name="+requiredArray[i]+"]")
					for(var j=0;j<objectui.length;j++){   
                  	if(objectui[j].checked   ==   true   ){   
                           // alert   (objchk[i].value);   
                            query+="&"+requiredArray[i]+"="+objectui[j].value;
                  		}   
					}
                  	
				}else if (objectui.attr("type")=="checkbox")
				{
					
					
					//var   objchk =  $("input[name="+requiredArray[i]+"]")
					var chkValue="";
					for(var k=0;k<objectui.length;k++){   
                  		if(objectui[k].checked   ==   true   ){   
                           // alert   (objchk[i].value);   
                            chkValue+=objectui[k].value;
                            
                            if((k+1)<objectui.length){
									chkValue+=",";
								}
			
                  		}   
         		 	}   
         		 	query+="&"+requiredArray[i]+"="+chkValue;
         		 	
					
				}else
				
				query+="&"+$("#"+requiredArray[i]).attr("id")+"="+$("#"+requiredArray[i]+"").val();
				//query+="&"+$("#"+requiredArray[i])+"="+$("#"+requiredArray[i]+"").val();
				
			}
			
			for(var i=0;i<optvarsArray.length;i++)
			{
				query+="&"+$("#"+optvarsArray[i]).attr("id")+"="+$("#"+optvarsArray[i]+"").val();
				//query+="&"+$("#"+optvarsArray[i])+"="+$("#"+optvarsArray[i]+"").val();
			}
							
			query +="&antiCache="+((new Date()).getTime()); 
		
			alert(query);
					$.getJSON(ws_ajax_path_prefix+"submitForm?"+query+"&callback=?",
					
						function(json){
						  if (json != "") {								
								alert('12');
							}
					   }
					);
					
}


function profileAnswersave(){
		var context ="http://"+document.location.host;
 		var ids=$("#submitids").val().split(",");
 		var path="";
 		
 		var longMonths=[['January','01'],['February','02'],['March','03'],['April','04'],['May','05'],['June','06'],['July','07'],['August','08'],['September','09'],['October','10'],['November','11'],['December','12']]
 		
 	var message="";
 	var messageArray = [];
	$(".sideError").each(function(){
		$(this).remove();
	});	
 	if ($("#requireids").val()!=""){
 		var rids=$("#requireids").val().split(",");
 		for (var i=0;i<rids.length;i++){
 			if ($("#field"+rids[i]).val()==""){
				var fieldHandle = $("#field"+rids[i]);
 				var field=$("#name"+rids[i]).html();
 				field=field.substring(0,field.indexOf("<"));
 				//message=message+"<li class='feedbackPanelERROR'>"+field+" is required</li>"
				messageArray.push("errorNo"+rids[i]);
				fieldHandle.parent().append("<div class='feedbackPanelERROR sideError errorNo"+""+rids[i]+"' style='display:none;'>"+field+" is required</div>");
 			}
 		}
 	}
 	
 	if ($(".questionemail").val()!=undefined && $(".questionemail").val()!="" ){
 		var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
 		if(!myreg.test($(".questionemail").val()))
 			message=message+"<li class='feedbackPanelERROR'>Invalid Email Address</li>"
 	}
 	
 	if ($(".questionmonth").val()!=undefined && $(".questionmonth").val()!=""){
 		var sdate=$(".questionyear").val()+"-"+$(".questionmonth").val()+"-"+$(".questiondate").val();
 		for (var i=0;i<longMonths.length;i++){
 			sdate=sdate.replace(longMonths[i][0],longMonths[i][1]);
 		}
 		if (!IsValidDate(sdate))
 			message=message+"<li class='feedbackPanelERROR'>Invalid Date Format</li>"
 	}
 /*		
 	if (message!=""){
 			message="<ul>"+message+"</ul>"
 			$("#fieldError").html(message);
 			$("#fieldMessage").show();
 			return;
 	}
*/	
	if (messageArray.length > 0){
		for (var i=0; i<messageArray.length;i++){
			$("."+messageArray[i]).show();
			
		}
		return;
	}	
	
	
 		for (var i=0;i<ids.length;i++){
 			if ($("#"+ids[i]).attr("type")=="checkbox"
 				||$("#"+ids[i]).attr("type")=="radio"){
 				if ($("#"+ids[i]).attr("checked")==true)
 					path=path+ids[i]+"="+$.trim($("#"+ids[i]).val())+"&";
 				else
 					path=path+ids[i]+"="+"&";
 			}
 			else{
 				path=path+ids[i]+"="+$("#"+ids[i]).val()+"&";
 			}
 			
 		}
 		path=path+"groupId="+$("#groupId").val()+"&profileId="+$("#profileId").val()+"&parentId="+$("#parentId").val()+"&type=save";
 		path=encodeURI(path);
 		$.ajax({url:context+"/myProfileAnswer",
	                 type: 'POST',
	                 dataType: 'json',
	                 data: path,
	                 timeout: 10000,
	                 error: function(){ },
	                success:function(json){
	                if (json.saveflag=="true"){
						if (json.type=="10"){
							if ($("#parentId").val()==""){
								$('#answerList').show();
								$('#answerheader').show();
								$('#answerList').append(json.jsonStr);
							}	
							else
								$("#tr_"+$("#parentId").val()).html(json.jsonStr);
							
							for (var i=0;i<ids.length;i++){
								$("#"+ids[i]).val("");
							}
							$("select").attr("value","US");
							$("#parentId").val("");
							$("#divcancel").hide();
							var smessage="<ul><li class='feedbackPanelERROR'>"+json.message+"</li></ul>";
							$("#fieldError").html(smessage);
							$("#fieldError ul").css({background:"#A6FFA6",borderColor:"#00FF00"});
							$("#fieldMessage").fadeIn(3000);
							//notice: registers a document click event here
							//but, if there is other document click events 
							//defined in other place, it will be overwritten by function here
							$(document).unbind("click").bind("click",function(){
														$("#fieldMessage").fadeOut(500);					  
							});
							//$("#fieldMessage").fadeOut(5000);
							
						}else{
							var smessage="<ul><li class='feedbackPanelERROR'>"+json.message+"</li></ul>";
							$("#fieldError").html(smessage);
							$("#fieldError ul").css({background:"#A6FFA6",borderColor:"#00FF00"});
							$("#fieldMessage").fadeIn(3000);
							//notice: registers a document click event here
							//but, if there is other document click events 
							//defined in other place, it will be overwritten by function here
							$(document).unbind("click").bind("click",function(){
														$("#fieldMessage").fadeOut(500);					  
							});
							//$("#fieldMessage").fadeOut(5000);
							
						}
	                }else {
					   
					}
	                 	   
			   }
			});

}	

function profileAnswerEdit(parentId){
	
	var context ="http://"+document.location.host;
 	var ids=$("#submitids").val().split(",");
 	var path="";

	path=path+"groupId="+$("#groupId").val()+"&profileId="+$("#profileId").val()+"&parentId="+parentId+"&type=edit";
 	path="/myProfileAnswer?"+path;
 	$.ajax({url:context+path,
	                 type: 'POST',
	                 dataType: 'json',
	                 timeout: 10000,
	                 error: function(){ },
	                success:function(json){
	                if (json.saveflag=="true"){
	                	$("#parentId").val(parentId);
	                	var values=json.jsonStr.split(",");
	                	for (var i=0;i<ids.length;i++){
								$("#"+ids[i]).val(values[i]);
						}
						$("select").attr("value",json.country);
	                	$("#divcancel").show();
	                	
					}
	                 	   
			   }
	});

}

function profileAnswerDelete(answerId){
	var context ="http://"+document.location.host;
 	var ids=$("#submitids").val().split(",");
 	var path="";
	path=path+"groupId="+$("#groupId").val()+"&profileId="+$("#profileId").val()+"&parentId="+answerId+"&type=delete";
 	path="/myProfileAnswer?"+path;
 	$.ajax({url:context+path,
	                 type: 'GET',
	                 dataType: 'json',
	                 timeout: 10000,
	                 error: function(){ },
	                success:function(json){
	                if (json.saveflag=="true"){
	                	var rows=$("#tr_"+answerId).prevAll().length;
	                	var nextrows=$("#tr_"+answerId).nextAll().length;
	                	if (rows<=1 && nextrows<1 ){
	                		$("#answerheader").hide();
	                		$("#answerList").hide();
	                	}
	                	$("#tr_"+answerId).remove();
	                	for (var i=0;i<ids.length;i++){
								$("#"+ids[i]).val("");
						}
						$("select").attr("value","US");
						$("#parentId").val("");
						
	                	
					}
	                 	   
			   }
	});
}

function profileAnswerClear(){
	var ids=$("#submitids").val().split(",");
	for (var i=0;i<ids.length;i++){
		$("#"+ids[i]).val("");
	}
	//$("select").attr("value","US");
	$("#parentId").val("");
}

function onmyinput(o){  
 var nMaxLen=2000;  
 if(o.getAttribute && o.value.length>nMaxLen){  
 		o.value=o.value.substring(0,nMaxLen)  
 	}  
}  

function IsValidDate(DateStr)    
{    
    var sDate=DateStr.replace(/(^\s+|\s+$)/g,''); 
    if(sDate=='') return true;     
        var t=new Date(sDate.replace(/\-/g,'/')); 
           
        var ar = sDate.split("-");  
        if(parseInt(ar[0]) != t.getFullYear() || parseInt(ar[1]) != t.getMonth()+1 || parseInt(ar[2]) != t.getDate())    
        {    
            return false;    
        }      
    return true;  
  
} 


function profileAnswerDone(){
		var context ="http://"+document.location.host;
 		var ids=$("#submitids").val().split(",");
 		var path="";
 		
 		var longMonths=[['January','01'],['February','02'],['March','03'],['April','04'],['May','05'],['June','06'],['July','07'],['August','08'],['September','09'],['October','10'],['November','11'],['December','12']]
 		
 	var message="";
 	var messageArray = [];
	
	$(".sideError").each(function(){
		$(this).remove();
	});
	
 	if ($("#requireids").val()!=""){
 		var rids=$("#requireids").val().split(",");
 		for (var i=0;i<rids.length;i++){
 			if ($("#field"+rids[i]).val()==""){
				var fieldHandle = $("#field"+rids[i]);
 				var field=$("#name"+rids[i]).html();
 				field=field.substring(0,field.indexOf("<"));
 				//message=message+"<li class='feedbackPanelERROR'>"+field+" is required</li>"
				//message=message+"<div class='feedbackPanelERROR sideError error"+"#field"+rids[i]+"' style='left:"+fieldHandle.offset().left+"px;top:"+fieldHandle.offset().top+"px'>"+field+" is required</div>";		
				messageArray.push("errorNo"+rids[i]);
				fieldHandle.parent().append("<div class='feedbackPanelERROR sideError errorNo"+""+rids[i]+"' style='display:none;'>"+field+" is required</div>");
				
 			}
 		}
 	}
 	
 	if ($(".questionemail").val()!=undefined && $(".questionemail").val()!="" ){
 		var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
 		if(!myreg.test($(".questionemail").val()))
 			message=message+"<li class='feedbackPanelERROR'>Invalid Email Address</li>"
 	}
 	
 	if ($(".questionmonth").val()!=undefined && $(".questionmonth").val()!=""){
 		var sdate=$(".questionyear").val()+"-"+$(".questionmonth").val()+"-"+$(".questiondate").val();
 		for (var i=0;i<longMonths.length;i++){
 			sdate=sdate.replace(longMonths[i][0],longMonths[i][1]);
 		}
 		if (!IsValidDate(sdate))
 			message=message+"<li class='feedbackPanelERROR'>Invalid Date Format</li>"
 	}
 		
	/*	
 	if (message!=""){
 			//message="<ul>"+message+"</ul>"
 			$("#fieldError").html(message);
 			$("#fieldMessage").show();
 			return;
 	}
	*/
	if (messageArray.length > 0){
		for (var i=0; i<messageArray.length;i++){
			$("."+messageArray[i]).show();
			
		}
		return;
	}
	
 		for (var i=0;i<ids.length;i++){
 			if ($("#"+ids[i]).attr("type")=="checkbox"
 				||$("#"+ids[i]).attr("type")=="radio"){
 				if ($("#"+ids[i]).attr("checked")==true)
 					path=path+ids[i]+"="+$.trim($("#"+ids[i]).val())+"&";
 				else
 					path=path+ids[i]+"="+"&";
 			}
 			else{
 				path=path+ids[i]+"="+$("#"+ids[i]).val()+"&";
 			}
 			
 		}
 		path=path+"groupId="+$("#groupId").val()+"&profileId="+$("#profileId").val()+"&parentId="+$("#parentId").val()+"&type=done";
 		path=encodeURI(path);
 		$.ajax({url:context+"/myProfileAnswer",
	                 type: 'POST',
	                 dataType: 'json',
	                 data: path,
	                 timeout: 10000,
	                 error: function(){ },
	                success:function(json){
	                if (json.saveflag=="true"){
						window.location=context+"/startProfile2"
	                }else {
					   
					}
	                 	   
			   }
			});

}	   


function profileSiteCreated(){
		var context ="http://"+document.location.host;
		path="type=repalced";
		$.ajax({url:context+"/myProfileAnswer",
	                 type: 'POST',
	                 dataType: 'json',
	                 data: path,
	                 timeout: 10000,
	                 error: function(){ },
	                success:function(json){
	                tb_remove();
	                if (json.saveflag=="true"){
	                		$("#profileSiteId").val(json.jsonStr);
							var smessage="<ul><li class='feedbackPanelERROR'>"+json.message+"</li></ul>";
							
							$("#fieldError").html(smessage);
							$("#fieldError ul").css({background:"#A6FFA6",borderColor:"#00FF00"});
							
							$("#fieldMessage").fadeIn(3000);
							//notice: registers a document click event here
							//but, if there is other document click events 
							//defined in other place, it will be overwritten by function here
							$(document).unbind("click").bind("click",function(){
														$("#fieldMessage").fadeOut(500);					  
							});
	                }else {
					   
					}
	                 	   
			   }
			});
} 


function profileSiteReplace(){
	if ($("#profileSiteId").val()!="0"
		&& $("#profileSiteId").val()!="1"){
		var context ="http://"+document.location.host;
		$.getJSON(context+"/session?callback=?",
					  function(json){	
							if (json.session=="true") {
									var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=ProfielSiteWindow";	
									messageWindow("",dialogueUrl);	
							}else{
								window.location=context+"login";
							}
					}
				);
				
	}else{
		 profileSiteCreated();
	}

}


