/*

Copyright (c) 2009 Anant Garg (anantgarg.com | inscripts.com)

This script may be used for non-commercial purposes only. For any
commercial purposes, please contact the author at 
anant.garg@inscripts.com

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/

var MyJq=jQuery.noConflict();
var windowFocus = true;
var username;
var isUserOnline;
var chatHeartTimer;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 1000;
var maxChatHeartbeat = 33000;
var chatHeartbeatTime = minChatHeartbeat;
var originalTitle;
var blinkOrder = 0;

var chatboxFocus = new Array();
var newMessages = new Array();
var newMessagesWin = new Array();
var chatBoxes = new Array();

MyJq(document).ready(function(){
     MyJq("#load").hide();
	originalTitle = document.title;
	startChatSession();
	

	MyJq([window, document]).blur(function(){
		windowFocus = false;
	}).focus(function(){
		windowFocus = true;
		document.title = originalTitle;
	});
	
	MyJq(document).bind('click', function(e) {
                var MyJqclicked = MyJq(e.target);
                if (! MyJqclicked.parents().hasClass("dropdown"))
                    MyJq(".dropdown dd ul").hide();
            });
            
    
    
    function hideSearchTab(obj){
            var stab=MyJq("#searchTab");
            
            
            
            if (stab.css("display")=='none')
            {
                obj.src='images/show.gif';
                stab.toggle('slow');                    
                MyJq.cookie('SearchOpt','unhide');
            } 
            else
            {
                obj.src='images/hide.gif';
                stab.toggle('slow');                   
                MyJq.cookie('SearchOpt','hide');
                
            }   
      }             
    MyJq("#hideme_").click(function(){ 
                hideSearchTab(this);
       });
       
     MyJq("#hideme_").mouseover(function(){ 
            var stab=MyJq("#searchTab");
           if (stab.css("display")=='none')    {
                this.src='images/show_hover.gif';
           }
           else{
                this.src='images/hide_hover.gif';
           }
           return overlib('<center><b>Show or Hide Search Options</b><hr size=1 color=black></center>Click here to display or hide Search Options');
     });
     
     MyJq("#hideme_").mouseout(function(){ 
            var stab=MyJq("#searchTab");
           if (stab.css("display")=='none')    {
                this.src='images/show.gif';
                
           }
           else{
                this.src='images/hide.gif';
           }
           return nd();
     });
     
     
     MyJq("#searchwithopt img").mouseout(function(){
        this.src='Images/search_but1.gif';
     });
     
     MyJq("#searchwithopt img").mouseover(function(){
        this.src='images/search_but.gif';
     });
     
     MyJq(".close_rnd").mouseout(function(){
            this.src='images/close_rnd.gif';
        });
        
     MyJq(".close_rnd").mouseover(function(){
            
            this.src='images/close_rnd_hover.gif';
        });   
    
    MyJq("#SrhId").click(function(){
        searchId();
        return false;
     });
     
   MyJq("#searchwithopt").click(function(){
        searchwithoptions();
        return false;
   });
   
   MyJq("#searchwithoptadv").click(function(){
        
        searchwithoptionsadv();
        return false;
   });
   
  
   
   MyJq("#searchwithoptadv img").mouseout(function(){
        this.src='Images/search_but1.gif';
     });
     
     MyJq("#searchwithoptadv img").mouseover(function(){
        this.src='images/search_but.gif';
     });
});

function restructureChatBoxes() {
	align = 0;
	for (x in chatBoxes) {
		chatboxtitle = chatBoxes[x];

		if (MyJq("#chatbox_"+chatboxtitle).css('display') != 'none') {
			if (align == 0) {
				MyJq("#chatbox_"+chatboxtitle).css('right', '20px');
			} else {
				width = (align)*(225+7)+20;
				MyJq("#chatbox_"+chatboxtitle).css('right', width+'px');
			}
			align++;
		}
	}
}

function chatWith(chatuser) {
    try{
       
      if (chatuser==username)
        {
            MyJq.alerts.okButton='Close';
            jAlert("You are trying to chat to yourself","Chatting Alert..");           

            return;
        }
        
        
     
        MyJq.ajax( {
                  type: "POST",
                  url: "Chat.aspx/IsCallingUserLoggedIn",
                  data: "{MyId:'" + username + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(res) {  
                            
                            if (!res && chatuser!='admin')
                            {
                                MyJq.alerts.okButton='Close';
                                jAlert("Please Login in or register yourself to chat with the user","Chatting Alert..");                                               
                                return;
                            }
                            ischatboxexist=(MyJq("#chatbox_"+chatuser).length>0);
                            createChatBox(chatuser);
                            MyJq("#chatbox_"+chatuser+" .chatboxtextarea").focus();

                            //if guest needs to chat with admin then
                            if ((username=='' || username=='undefined' || username==null) && chatuser=='admin')
                            {
                                if (ischatboxexist) return;
                    	        
                                MyJq("#chatbox_"+chatuser+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo"><div id="emlDiv_'+chatuser+'"  style="display:block;background:silver;border:solid 1px blue;text-align:center">Enter Your Name:<input id="Eml_'+chatuser+'" type="text"  /> <br/>Enter Your EmailId:<input id="EmlId_'+chatuser+'" type="text"  /><br /><input type="Button" value="Go" onclick="javascript:RegEmailId(\''+chatuser+'\')" /></div></span></div>');       
                    	        
                    	        
                                MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled","disabled");
                                
                                
                                MyJq("#Eml_"+chatuser).focus();
                                
                                return;
                            }
                      },error: function(xmld,erre,ere){ alert(xmld.responseText); }
                  });
        }
        
        
       
            
        
      catch(e){
        alert(e);
      }
      
//       var ischatboxexist=(MyJq("#chatbox_"+chatuser).length>0);
//        createChatBox(chatuser);
//	    MyJq("#chatbox_"+chatuser+" .chatboxtextarea").focus();
//	    
//	    
//	    
//	    //if guest needs to chat with admin then
//	    if ((username=='' || username=='undefined' || username==null) && chatuser=='admin')
//	    {
//	        if (ischatboxexist) return;
//	        
//	        MyJq("#chatbox_"+chatuser+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo"><div id="emlDiv_'+chatuser+'"  style="display:block;background:silver;border:solid 1px blue;text-align:center">Enter Your Name:<input id="Eml_'+chatuser+'" type="text"  /> <br/>Enter Your EmailId:<input id="EmlId_'+chatuser+'" type="text"  /><br /><input type="Button" value="Go" onclick="javascript:RegEmailId(\''+chatuser+'\')" /></div></span></div>');       
//	        
//	        
//            MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled","disabled");
//            
//            
//            MyJq("#Eml_"+chatuser).focus();
//            
//            return;
//	    }
	    
        
        
	    
	    
        
        
        //IsChatterOnline(chatuser)
	    
}

function createChatBox(chatboxtitle,minimizeChatBox,DeniedUser) {
    
	if (MyJq("#chatbox_"+chatboxtitle).length > 0) {
		if (MyJq("#chatbox_"+chatboxtitle).css('display') == 'none') {
			MyJq("#chatbox_"+chatboxtitle).css('display','block');
			restructureChatBoxes();
		}
		MyJq("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		return;
	}
    
    
     
	        MyJq(" <div />" ).attr("id","chatbox_"+chatboxtitle)
	        .addClass("chatbox")
                 .html('<div class="chatboxhead"><div class="chatboxtitle">'+chatboxtitle+'<span id="MyStatus_'+chatboxtitle+'" class="mystat">Available</span> </div><div class="chatboxoptions"><span class="bb"><dl id="status_'+chatboxtitle+'" class="dropdown"><dt><a href="#" onclick="ToggleStatus(this)" style="background-image: url(images/arrow.png)"><span>Available</span></a></dt><dd><ul><li><a href="#" onclick="SelectOption(this,\''+chatboxtitle+'\')"><img class="flag" src="images/avail_smiley.gif"  alt="" />Available<span class="value">Available</span></a></li><li><a href="#" onclick="SelectOption(this,\''+chatboxtitle+'\')"><img class="flag" src="images/deny_smiley.gif" alt="" />Deny<span class="value">Deny</span></a></li><li><a href="#" onclick="SelectOption(this,\''+chatboxtitle+'\')"><img class="flag" src="images/busy_smiley.gif" alt="" />Busy<span class="value">Busy</span></a></li></ul></dd></dl></span><a href="javascript:void(0)"  onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')"><span>-</span></a> <a href="javascript:void(0)"  onclick="javascript:closeChatBox(\''+chatboxtitle+'\')"><span class="chcls">X</span></a></div><br clear="all"/></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></div>')
            .appendTo(MyJq( "body" ));
     
	
	MyJq("#chatbox_"+chatboxtitle).css('bottom', '0px');
	
	chatBoxeslength = 0;

	for (x in chatBoxes) {
		if (MyJq("#chatbox_"+chatBoxes[x]).css('display') != 'none') {
			chatBoxeslength++;
		}
	}

	if (chatBoxeslength == 0) {
		MyJq("#chatbox_"+chatboxtitle).css('right', '20px');
	} else {
		width = (chatBoxeslength)*(225+7)+20;
		MyJq("#chatbox_"+chatboxtitle).css('right', width+'px');
	}
	
	chatBoxes.push(chatboxtitle);

	if (minimizeChatBox == 1) {
		minimizedChatBoxes = new Array();

		if (MyJq.cookie('chatbox_minimized')) {
			minimizedChatBoxes = MyJq.cookie('chatbox_minimized').split(/\|/);
		}
		minimize = 0;
		for (j=0;j<minimizedChatBoxes.length;j++) {
			if (minimizedChatBoxes[j] == chatboxtitle) {
				minimize = 1;
			}
		}

		if (minimize == 1) {
			MyJq('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
			MyJq('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
		}
	}

	chatboxFocus[chatboxtitle] = false;

	MyJq("#chatbox_"+chatboxtitle+" .chatboxtextarea").blur(function(){
		chatboxFocus[chatboxtitle] = false;
		MyJq("#chatbox_"+chatboxtitle+" .chatboxtextarea").removeClass('chatboxtextareaselected');
	}).focus(function(){
		chatboxFocus[chatboxtitle] = true;
		newMessages[chatboxtitle] = false;
		MyJq('#chatbox_'+chatboxtitle+' .chatboxhead').removeClass('chatboxblink');
		MyJq("#chatbox_"+chatboxtitle+" .chatboxtextarea").addClass('chatboxtextareaselected');
	});

	MyJq("#chatbox_"+chatboxtitle).click(function() {
		if (MyJq('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') != 'none') {
			MyJq("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		}
	});

	MyJq("#chatbox_"+chatboxtitle).show();
	
	GetStatus(chatboxtitle,"my");
	
}




function chatHeartbeat(){

	if (username=='') {
	    chatHeartTimer=setTimeout('chatHeartbeat();',chatHeartbeatTime);
	    return;
	}
	
    for (i=0;i<chatBoxes.length;i++) {
		 chatboxtitle = chatBoxes[i];
		 GetStatus(chatboxtitle,"user");
		 //if (GetStatusOfUser(chatboxtitle)=='Denied') return;          
		
        
        //IsChatterOnline(chatboxtitle);
        
     }
    
        
	var itemsfound = 0;
	
	if (windowFocus == false) {
 
		var blinkNumber = 0;
		var titleChanged = 0;
		for (x in newMessagesWin) {
			if (newMessagesWin[x] == true) {
				++blinkNumber;
				if (blinkNumber >= blinkOrder) {
					document.title = x+' says...';
					titleChanged = 1;
					break;	
				}
			}
		}
		
		if (titleChanged == 0) {
			document.title = originalTitle;
			blinkOrder = 0;
		} else {
			++blinkOrder;
		}

	} else {
		for (x in newMessagesWin) {
			newMessagesWin[x] = false;
		}
	}

	for (x in newMessages) {
		if (newMessages[x] == true) {
			if (chatboxFocus[x] == false) {
				//FIXME: add toggle all or none policy, otherwise it looks funny
				MyJq('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
			}
		}
	}
	
       try{                
                //var res=Chat.GetChatDtlWithTo(username);
            
                if (username!='')
                {
                    MyJq.ajax( {
                          type: "POST",
                          url: "Chat.aspx/GetChatDtlWithTo",
                          data: "{MyId:'" + username + "'}",
                          contentType: "application/json; charset=utf-8",
                          dataType: "json",
                          success: function(res) {
                            
                              MyJq.each(res, function(i,item){
                                    if (this)	{ // fix strange ie bug
                                        var iAmIn;
                                        if (username==this.From_User){ 
                                            iAmIn='from'; 
                                        } else { 
                                            iAmIn='to'; 
                                        }
                                        
                                        if (iAmIn=='from'){
                                            chatboxtitle = this.To_User;
                                        }
                                        else   {
                                            chatboxtitle = this.From_User;
                                        }
                                        
                                                
                                        
                                        if (MyJq("#chatbox_"+chatboxtitle).length <= 0) {
                                            createChatBox(chatboxtitle,1);
                                        }
                    		            

                                        if (MyJq("#chatbox_"+chatboxtitle).css('display') == 'none') {
                                            MyJq("#chatbox_"+chatboxtitle).css('display','block');
                                            restructureChatBoxes();
                                        }
                                                    
                                    				
                                        if (this.Recd==0) {
                                            newMessages[chatboxtitle] = true;
			                                newMessagesWin[chatboxtitle] = true;           
                                        }

                                		        
                                		             
                                          if (iAmIn=='to' && this.Recd==0) {
                    		                
                                            //var res=Chat.UpdateChatRecd(this.ChatId);
                                            MyJq.ajax( {
                                                  type: "POST",
                                                  url: "Chat.aspx/UpdateChatRecd",
                                                  data: "{ChatId:'" + this.ChatId + "'}",
                                                  contentType: "application/json; charset=utf-8",
                                                  dataType: "json",
                                                  success: function() { }
                                             });
                                                         
                                            MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+ this.From_User +':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+this.Message+'</span></div>');  
                                         }
                                                 
                                                     
                                		            				
                                				
                                                
                                        MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
				                        setTimeout('MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);', 100); // yet another strange ie bug                                
                                                
                                        
                        		
				                        itemsfound += 1;                       
                                    }
                                });
                             }
                     });
		         }
		        
		  }
		catch(e)
		{
		}

		chatHeartbeatCount++;

		if (itemsfound > 0) {
			chatHeartbeatTime = minChatHeartbeat;
			chatHeartbeatCount = 1;
		} else if (chatHeartbeatCount >= 10) {
			chatHeartbeatTime *= 2;
			chatHeartbeatCount = 1;
			if (chatHeartbeatTime > maxChatHeartbeat) {
				chatHeartbeatTime = maxChatHeartbeat;
			}
		}
		
		chatHeartTimer=setTimeout('chatHeartbeat();',chatHeartbeatTime);

}

function closeChatBox(chatboxtitle) {
	MyJq('#chatbox_'+chatboxtitle).css('display','none');
	restructureChatBoxes();

//	MyJq.post("chat.php?action=closechat", { chatbox: chatboxtitle} , function(data){	
//	});

}


//function for status

function PlaceSelectedValue(id,value){
        
        
    MyJq.each(MyJq("#"+id+" li a"),function(i){
    
           
           
        if (MyJq(this).find('span.value').html()==value) {
                 MyJq("#"+id+" dt a span").html(MyJq(this).html());
            }                 
        });
}
function getSelectedValue(id) {
    return MyJq("#" + id).find("dt a span.value").html();
}
function ToggleStatus(obj){
      var id=MyJq(obj).parent().parent().attr("id");

    // MyJq(".dropdown dt a").click(function() {
      MyJq("#"+id+ " dd ul").toggle();

}
function SelectOption(obj,chatuser){
   
    
      
    
    var id=MyJq(obj).parent().parent().parent().parent().attr("id");
    
    if (chatuser=='admin') { 
        MyJq("#chatbox_"+chatuser+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">You cannot change status of administrator of the site....</span></div>');
        MyJq("#"+id+" dd ul").hide();
        return;
    }
    
    var text = MyJq(obj).html();
    
    
    MyJq("#"+id+" dt a span").html(text);
    MyJq("#"+id+" dd ul").hide();
   
  
  //Chat.SendStatusToTheUser(chatuser,username,MyJq("#"+id+" dt a span.value").html());
  
            MyJq.ajax( {
                      type: "POST",
                      url: "Chat.aspx/SendStatusToTheUser",
                      data: "{userId:'" + chatuser + "',MyId:'" + username + "',Status:'" + MyJq("#"+id+" dt a span.value").html() + "'}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function(res) {
                        
                            },
                      error: function(res,df,dfd){ alert(res.responseText); }
                });
  
}

            
            
  //end of function for status


//function GetMyStatusToUser(chatuser){
    
    
    //var st=GetStatus(chatuser,"my");
    
    
//}

//function GetStatusOfUser(chatuser){
    //var st=GetStatus(chatuser,"user");
    
//    if (st=="Deny"){
//        st="(Denied)";
//        if (MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled")) return;
//        MyJq("#chatbox_"+chatuser+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">Sorry!! '+chatuser+' is not willing to chat with you..</span></div>');       
//        MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled","disabled");
//    }
//    
//    if (st=="Available"){
//         st="(Available)";
//        if (MyJq("#chatbox_"+chatuser+" .chatboxinfo:last").html()!=chatuser+ ' is Online now.')
//         MyJq("#chatbox_"+chatuser+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+chatuser+ ' is Online now.</span></div>');       
//        if(MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled")){
//            MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled","");
//            }
//            
//    }
//    
//    if (st=="Busy"){
//        st="(Busy)";
//        if (MyJq("#chatbox_"+chatuser+" .chatboxinfo:last").html()!=chatuser+ ' is Busy now!! Please wait.')
//         MyJq("#chatbox_"+chatuser+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+chatuser+ ' is Busy now!! Please wait.</span></div>');       
//        if(MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled")){
//            MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled","");
//            }
//     }
//     
//    if (st=="Offline"){
//        st="(offline)";      
//        if (MyJq("#chatbox_"+chatuser+" .chatboxinfo:last").html()!=chatuser+' is offline. But '+chatuser+' will receive messages when he/she comes online')
//            MyJq("#chatbox_"+chatuser+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+chatuser+' is offline. But '+chatuser+' will receive messages when he/she comes online</span></div>');       
//        
//        if(MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled")){
//            MyJq("#chatbox_"+chatuser+" .chatboxtextarea").attr("disabled","");
//            }
//    }
//        
//        
//    MyJq("#MyStatus_"+chatuser).html(st);
//    return st;
//}

function GetStatus(uid,whom){
  
     try
    {
        
        if (whom=='my')
        {
   
            MyJq.ajax( {
                  type: "POST",
                  url: "Chat.aspx/GetMyStatus",
                  data: "{ChatUsrId:'" + uid + "',MyId:'" + username + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(rs){ 
                            if (rs=='Available'){
                                     MyJq("#status_"+uid + " dt a span").html('<img class="flag" src="images/avail_smiley.gif" alt="" />Available<span class="value">Available</span>');
                                }
                                if (rs=='Deny'){
                                    MyJq("#status_"+uid + " dt a span").html('<img class="flag" src="images/deny_smiley.gif" alt="" />Deny<span class="value">Deny</span>');
                                }
                                if (rs=='Busy'){
                                    MyJq("#status_"+uid + " dt a span").html('<img class="flag" src="images/busy_smiley.gif" alt="" />Busy<span class="value">Busy</span>');
                                }
                   },
                  error: function(res,fds,dfd){ alert(res.responseText); }
            });
            
        }
        else
        {
            //var res=Chat.GetUserStatus(uid,username);
            MyJq.ajax( {
                  type: "POST",
                  url: "Chat.aspx/GetUserStatus",
                  data: "{ChatUsrId:'" + uid + "',MyId:'" + username + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(res){ 
                            
                            if (res=="Deny"){
                                    res="(Denied)";
                                    if (MyJq("#chatbox_"+uid+" .chatboxtextarea").attr("disabled")) return;
                                    MyJq("#chatbox_"+uid+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">Sorry!! '+uid+' is not willing to chat with you..</span></div>');       
                                    MyJq("#chatbox_"+uid+" .chatboxtextarea").attr("disabled","disabled");
                                }
                                
                                if (res=="Available"){
                                     res="(Available)";
                                    if (MyJq("#chatbox_"+uid+" .chatboxinfo:last").html()!=uid+ ' is Online now.')
                                     MyJq("#chatbox_"+uid+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+uid+ ' is Online now.</span></div>');       
                                    if(MyJq("#chatbox_"+uid+" .chatboxtextarea").attr("disabled")){
                                        MyJq("#chatbox_"+uid+" .chatboxtextarea").attr("disabled","");
                                        }
                                        
                                }
                                
                                if (res=="Busy"){
                                    res="(Busy)";
                                    if (MyJq("#chatbox_"+uid+" .chatboxinfo:last").html()!=uid+ ' is Busy now!! Please wait.')
                                     MyJq("#chatbox_"+uid+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+uid+ ' is Busy now!! Please wait.</span></div>');       
                                    if(MyJq("#chatbox_"+uid+" .chatboxtextarea").attr("disabled")){
                                        MyJq("#chatbox_"+uid+" .chatboxtextarea").attr("disabled","");
                                        }
                                 }
                                 
                                if (res=="Offline"){
                                    res="(offline)";      
                                    if (MyJq("#chatbox_"+uid+" .chatboxinfo:last").html()!=uid+' is offline. But '+uid+' will receive messages when he/she comes online')
                                        MyJq("#chatbox_"+uid+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+uid+' is offline. But '+uid+' will receive messages when he/she comes online</span></div>');       
                                    
                                    if(MyJq("#chatbox_"+uid+" .chatboxtextarea").attr("disabled")){
                                        MyJq("#chatbox_"+uid+" .chatboxtextarea").attr("disabled","");
                                        }
                                }
                                    
                                    
                                MyJq("#MyStatus_"+uid).html(res);                 
                        },
                  error: function(res,fds,dfd){ alert(res.responseText); }
            });
            
        }
    	 
         
         
    }
    catch(e){
        alert(e);
      //  status='Available';
    }
  
}


function toggleChatBoxGrowth(chatboxtitle) {
	if (MyJq('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {  
		
		var minimizedChatBoxes = new Array();
		
		if (MyJq.cookie('chatbox_minimized')) {
			minimizedChatBoxes = MyJq.cookie('chatbox_minimized').split(/\|/);
		}

		var newCookie = '';

		for (i=0;i<minimizedChatBoxes.length;i++) {
			if (minimizedChatBoxes[i] != chatboxtitle) {
				newCookie += chatboxtitle+'|';
			}
		}

		newCookie = newCookie.slice(0, -1)


		MyJq.cookie('chatbox_minimized', newCookie);
		MyJq('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
		MyJq('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
		MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
	} else {
		
		var newCookie = chatboxtitle;

		if (MyJq.cookie('chatbox_minimized')) {
			newCookie += '|'+MyJq.cookie('chatbox_minimized');
		}


		MyJq.cookie('chatbox_minimized',newCookie);
		MyJq('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
		MyJq('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
	}
	
}

function checkChatBoxInputKey(event,chatboxtextarea,chatboxtitle) {

	
	 
	if(event.keyCode == 13 && event.shiftKey == 0)  {
	    
		message = MyJq(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+MyJq/g,"");
        message=message.replace(/\'/g," ")
		MyJq(chatboxtextarea).val('');
		MyJq(chatboxtextarea).focus();
		MyJq(chatboxtextarea).css('height','44px');
		
		if (message != '') {
		    //Chat.InsertChatRecd(chatboxtitle,username,message);
		    
		     MyJq.ajax( {
                  type: "POST",
                  url: "Chat.aspx/InsertChatRecd",
                  data: "{toUsrId:'" + chatboxtitle + "',frmUsrId:'" + username + "',Mess:'" + message + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(){ },
                  error: function(res,fdf,ere) { alert(res.responseText); }
               
            });
            
			message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
			MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">Me:&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
			MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			
		}
		chatHeartbeatTime = minChatHeartbeat;
		chatHeartbeatCount = 1;

		return false;
	}

	var adjustedHeight = chatboxtextarea.clientHeight;
	var maxHeight = 94;

	if (maxHeight > adjustedHeight) {
		adjustedHeight = Math.max(chatboxtextarea.scrollHeight, adjustedHeight);
		if (maxHeight)
			adjustedHeight = Math.min(maxHeight, adjustedHeight);
		if (adjustedHeight > chatboxtextarea.clientHeight)
			MyJq(chatboxtextarea).css('height',adjustedHeight+8 +'px');
	} else {
		MyJq(chatboxtextarea).css('overflow','auto');
	}
	 
}


function RegEmailId(user){
    
    
    var name=MyJq("#Eml_"+user).val().replace(/[^a-zA-Z 0-9]+/g,'');
    var emlid=MyJq("#EmlId_"+user).val();
    
    
    
    if (name=='')     { 
      alert('Please enter your name'); 
      MyJq("#Eml_"+user).focus();
      return; 
      }
      
      if (!mailcheck(emlid))     {
        MyJq("#EmlId_"+user).focus();
        return;
    }
    
    
      MyJq.ajax( {
                  type: "POST",
                  url: "Chat.aspx/IsUserRegistered",
                  data: "{usrNm:'" + MyJq("#Eml_"+user).val() + "',replacedUsrNm:'" + name + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(res) {
                          if (!res){
                               
                              username=name;
                
                
                                MyJq.ajax( {
                                      type: "POST",
                                      url: "Chat.aspx/EnterGuestEmlId",
                                      data: "{EmlId:'" + username + "',EmailId:'"+emlid+"'}",
                                      contentType: "application/json; charset=utf-8",
                                      dataType: "json",
                                      success: function(res) {
                                        
                                            }
                                });
                                
                                MyJq("#chatbox_"+user+" .chatboxtextarea").attr("disabled","");
                                MyJq("#chatbox_"+user+" .chatboxtextarea").focus();
                                //MyJq.each(MyJq("#chatbox_"+user+" .chatboxinfo"),function(){
                                  //  this.html('');
                                    //}
                                //);
                                MyJq("#chatbox_"+user+" .chatboxcontent").html('');
                                //MyJq("#emlDiv_"+user).attr("display","none");
                                IsChatterOnline(user);
                              }
                             else
                             {
                                MyJq("#chatbox_"+user+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+name+' is already Present. Please try a different Name </span></div>');                 
                                MyJq("#Eml_"+user).focus();
                             }
                      }
                      });
                      
}

function IsChatterOnline(chatuser){
    //if to user is online or offline
    try{
        //var res=Chat.isChatUserOnline(chatuser);
        MyJq.ajax( {
                      type: "POST",
                      url: "Chat.aspx/isChatUserOnline",
                      data: "{ChatUsrId:'" + chatuser + "'}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function(res) {
                                
                                if (res!=isUserOnline){
                                    if (!res)
                                    {
                                        
                                        MyJq("#chatbox_"+chatuser+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+chatuser+' is offline. <br />But '+chatuser+' will receive messages when he/she comes online</span></div>');       
                                        isUserOnline=false;
                                    }
                                    else
                                    {
                                        MyJq("#chatbox_"+chatuser+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+chatuser+' is Online now. </span></div>');       
                                        isUserOnline=true;
                                    }
                                }
                            }
                });
    
        
     }
     catch(e){
        isUserOnline=true;
     }
 }

function startChatSession(){  

        
        try
        {
        
                MyJq.ajax( {
                      type: "POST",
                      url: "Chat.aspx/GetCurrentUser",
                      data: "{}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function(msg) {
                        // Replace the div's content with the page method's return.
                        
                        username=msg;
                         
                        if (username==null) username='';
                        
                        
                        if (username!='') username=username.replace(/[^a-zA-Z 0-9]+/g,'');
                        
                        if (username!='')
                            {
                                MyJq.ajax( {
                                      type: "POST",
                                      url: "Chat.aspx/GetChatDtlWithTo",
                                      data: "{MyId:'" + username + "'}",
                                      contentType: "application/json; charset=utf-8",
                                      dataType: "json",
                                      success: function(res) {
                                        
                                        MyJq.each(res, function(i,item){
                                                        
		                                        if (this)	{ // fix strange ie bug
                                                    var iAmIn;
                                       
                                                    if (username==this.From_User){ 
                                                        iAmIn='from'; 
                                                    } else { 
                                                        iAmIn='to'; 
                                                    }
                                                    
                                                    if (iAmIn=='from'){
			                                            chatboxtitle = this.To_User;
			                                        }
			                                        else   {
			                                            chatboxtitle = this.From_User;
			                                        }
                                                    
				                                    if (MyJq("#chatbox_"+chatboxtitle).length <= 0) {
					                                    createChatBox(chatboxtitle);
				                                    }
                                    				
                        				            

                        //				            if (iAmIn=='from') {
                        //				                MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">Me:&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+this.message+'</span></div>');
                        //				             }
                        //				             else{
                        //				                MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+ this.from_User +':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+this.message+'</span></div>');
                        //				             }
                        //				                
				                                     if (iAmIn=='to' && this.Recd==0) {
				                                        MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+ this.From_User +':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+this.Message+'</span></div>');
				                                        
				                                        
				                                        
				                                        //update Chat Recd by user
				                                        //Chat.UpdateChatRecd(this.ChatId);
				                                        
				                                        MyJq.ajax( {
                                                                  type: "POST",
                                                                  url: "Chat.aspx/UpdateChatRecd",
                                                                  data: "{ChatId:'" + this.ChatId + "'}",
                                                                  contentType: "application/json; charset=utf-8",
                                                                  dataType: "json",
                                                                  success: function() { }
                                                         });
				                                     }
                                                }					            
                        				            
                        			            
		                                    });//each
                                    		
		                        for (i=0;i<chatBoxes.length;i++) {
                        		    
			                        chatboxtitle = chatBoxes[i];
                    //			    MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop(MyJq("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
                    //			    setTimeout('MyJq("#chatbox_"'+chatboxtitle+'" .chatboxcontent").scrollTop(MyJq("#chatbox_"'+chatboxtitle+'" .chatboxcontent")[0].scrollHeight);', 100); // yet another strange ie bug
		                        }
                                      },
                                      error: function(htprequest,txtstatus,err){ //alert(htprequest.responseText); 
                                      }
                                 });
                                        
                                
////                                
    	                }//if username!=''
	                    
        	
                      }//function between 1st Ajax request
                    });//1st Ajax request
                  

                   
		}//end of try
		catch(e)
		{
		
		    alert(e.message); 
		}   
		if (username==null) username='';
		setTimeout('chatHeartbeat();',chatHeartbeatTime);
		
}
function errFunction(errResp,dfd,errText){
    alert(errResp.responseText);
}

function IsUserLoggedIn(){
    
    MyJq.ajax( {
                  type: "POST",
                  url: "Chat.aspx/IsUserLoggedIn",
                  data: "{}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(res) {
                    if (!res){
                       
                        MyJq.alerts.okButton='Close';
                        jAlert("You have not yet Logged in<br> Please Login in..","Logged Status");
                     }
                    return res;
                   },
                  error: function (errResp,dfd,errText){
                    MyJq.alerts.okButton='Close';
                    jAlert(errResp.responseText,"Error: Checking User Logged Status");
}

                  
     });
    
     
 }
 
// MyJq(".SendInt_H").mouseout(function(){
//    MyJq("#"+this.id).hide('normal');
// });
// 
 
 function SendInterestClicked(RecId,RecNm)
 {
//      
      showload(MyJq("#imgSend_"+RecId),"Loading..");
      MyJq(".SendInt_H").hide('normal');
      MyJq(".Send_But").show('normal');
      MyJq.ajax( {
                  type: "POST",
                  url: "Chat.aspx/IsUserLoggedIn",
                  data: "{}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(res) {
                    if (!res){
                       
                        MyJq.alerts.okButton='Close';
                        jAlert("You have not yet Logged in<br> Please Login in..","Logged Status");
                        hideload();
                        return res;
                     }
                     
                     MyJq.ajax( {
                      type: "POST",
                      url: "Chat.aspx/IsUserCallingHimselfById",
                      data: "{RecId:'" + RecId + "'}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function(res) {
                        
                        if (res){
                           
                            MyJq.alerts.okButton='Close';
                            jAlert("You Cannot send Interest to yourself ","Beware..");
                            hideload();
                            return res;
                        }
                        MyJq.ajax( {
                          type: "POST",
                          url: "Chat.aspx/IsOfSameSex",
                          data: "{RecId:'" + RecId + "'}",
                          contentType: "application/json; charset=utf-8",
                          dataType: "json",
                          success: function(res) {
                                    
                                  if (res){
                                    MyJq.alerts.okButton='Close';
                                    jAlert("You Cannot send Interest to Same Gender","Very Bad..");
                                    hideload();
                                    return res;
                                }           
                                    MyJq.ajax( {
                                  type: "POST",
                                  url: "Chat.aspx/IsInterestAlreadySend",
                                  data: "{RecId:'" + RecId + "'}",
                                  contentType: "application/json; charset=utf-8",
                                  dataType: "json",
                                  success: function(res) {
                                        
                                        if (res){
                                            MyJq.alerts.okButton='Close';
                                            jAlert("You have already Send an Interest to this person <br> You can only send an expression once","Expression cannot be Repeated..");
                                            hideload();
                                            return res;
                                        }
                                        MyJq("#imgSend_"+RecId).hide('normal');
                                        hideload();
                                        
                                        MyJq("#SendInt_H_"+RecId).show('slow');
                                        
                                        
                                    }                                  
                                    
                                  });
                                  
                                 }
                        });
                        
                        
                        }
     
                        });
                   },
                  error: function (errResp,dfd,errText){
                    MyJq.alerts.okButton='Close';
                    jAlert(errResp.responseText,"Error: Checking User Logged Status");
                    hideload();
                }
                });
                
 }
 
 function SendIntClick(RecId){
    //alert(MyJq("input[@name='sOEx']:checked").val());
    
    
    var expopt=MyJq("#sendInt_opt_"+RecId+" input[@name='sOEx']:checked").val();
    
    
    if (expopt=='' || expopt=='undefined' || expopt==null){
           MyJq(".sucMess").remove(); 
           MyJq("#sendButt_"+RecId).after("<div class='sucMess'>Please Select any one of the expressions in the list</div>");
           setTimeout('removesucmess()',3000);         
           return;
    }
    
    var expstr;
    expstr=MyJq("#sendInt_opt_"+RecId+" .opt"+expopt).html();
    
    
    showload(MyJq("#sendButt_"+RecId),"Sending Interest....");
    MyJq("#sendButt_"+RecId).attr("disabled","true");
    MyJq.ajax( {
                  type: "POST",
                  url: "Chat.aspx/IsUserLoggedIn",
                  data: "{}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(res) {
                    if (!res){
                       
                        MyJq.alerts.okButton='Close';
                        jAlert("You have not yet Logged in<br> Please Login in..","Logged Status");
                        hideload();
                        MyJq("#sendButt_"+RecId).attr("disabled","");
                        return res;
                     }
                     
                     MyJq.ajax( {
                      type: "POST",
                      url: "Chat.aspx/IsUserCallingHimselfById",
                      data: "{RecId:'" + RecId + "'}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function(res) {
                        
                        if (res){
                           
                            MyJq.alerts.okButton='Close';
                            jAlert("You Cannot send Interest to yourself ","Beware..");
                            hideload();
                            MyJq("#sendButt_"+RecId).attr("disabled","");
                            return res;
                        }
                        MyJq.ajax( {
                          type: "POST",
                          url: "Chat.aspx/IsOfSameSex",
                          data: "{RecId:'" + RecId + "'}",
                          contentType: "application/json; charset=utf-8",
                          dataType: "json",
                          success: function(res) {
                                    
                                  if (res){
                                    MyJq.alerts.okButton='Close';
                                    jAlert("You Cannot send Interest to Same Gender","Very Bad..");
                                    hideload();
                                    MyJq("#sendButt_"+RecId).attr("disabled","");
                                    return res;
                                }           
                                  MyJq.ajax( {
                                  type: "POST",
                                  url: "Chat.aspx/IsInterestAlreadySend",
                                  data: "{RecId:'" + RecId + "'}",
                                  contentType: "application/json; charset=utf-8",
                                  dataType: "json",
                                  success: function(res) {
                                        
                                        if (res){
                                            MyJq.alerts.okButton='Close';
                                            jAlert("You have already Send an Interest to this person <br> You can only send an expression once","Expression cannot be Repeated..");
                                            hideload();
                                            MyJq("#sendButt_"+RecId).attr("disabled","");
                                            return res;
                                        }
                                        MyJq.ajax( {
                                          type: "POST",
                                          url: "Chat.aspx/InterestReceived",
                                          data: "{RecId:'" + RecId + "',ExpSend:" + expopt + ",ExpStr:'" + expstr + "'}",
                                          contentType: "application/json; charset=utf-8",
                                          dataType: "json",
                                          success: function(res) {
                                                
                                                hideload();
                                                MyJq(".sucMess").remove();
                                                if(res){                                                   
                                                   MyJq("#sendButt_"+RecId).after("<div class='sucMess'>You have send the interest Successfully..</div>");
                                                   setTimeout('CloseSendInt(\''+RecId+'\')',2000);                                                   
                                                  }                 
                                                else{
                                                    MyJq("#sendButt_"+RecId).after("<div class='sucMess'>Some error occured while sending Interest..<br>Please try again!!!</div>");
                                                }
                                                   MyJq("#sendButt_"+RecId).attr("disabled","");
                                            },
                                            error:function (errResp,dfd,errText){
                                                    alert(errResp.responseText,"Error:While Sending Interest");
                                                    hideload();
                                            }
                                          });
                                        
                                        
                                    }                                  
                                    
                                  });
                                  
                                 }
                        });
                        
                        
                        }
     
                        });
                   },
                  error: function (errResp,dfd,errText){
                    MyJq.alerts.okButton='Close';
                    jAlert(errResp.responseText,"Error: Checking User Logged Status");
                    hideload();
                }
                });
                MyJq("#sendButt_"+RecId).attr("disabled","");
 }
 
 function CloseSendInt(RecId){
    MyJq("#SendInt_H_"+RecId).hide('slow');
    MyJq("#imgSend_"+RecId).show();
    MyJq(".sucMess").remove();
 }
 
 function CloseForwardInt(RecId){
    MyJq("#Forward_H_"+RecId).hide('slow');
    MyJq("#imgForward_"+RecId).show('normal');
    MyJq(".sucMess").remove();
 }
 function ForwardProfileTo(RecId,ProfUid,ProfMsg){
    
    var toNm=MyJq("#Forward_H_"+RecId+" .txtNm").val();
    var frNm=MyJq("#Forward_H_"+RecId+" .txtFrName").val();
    var toEmlId=MyJq("#Forward_H_"+RecId+" .txtEmail").val();
    var comments=MyJq("#Forward_H_"+RecId+" .txtcmts").val();
    var Subject=MyJq("#Forward_H_"+RecId+" .txtSubj").val();
    var ProfImg=MyJq("#image_"+RecId+" Img").attr("src");
    
    
    MyJq.alerts.okButton='Close';
    if (toNm==''){
        showMessage(MyJq("#Forward_H_"+RecId+" .txtNm"),"Please enter your Name");
        MyJq("#Forward_H_"+RecId+" .txtNm").focus();
        return;
    }
    if(frNm==''){
        showMessage(MyJq("#Forward_H_"+RecId+" .txtFrName"),"Friends Name cannot be blank");
        MyJq("#Forward_H_"+RecId+" .txtFrName").focus();
        return;
    }        
    if(toEmlId==''){
        showMessage(MyJq("#Forward_H_"+RecId+" .txtEmail"),"Please Enter Freinds Email Id");
        MyJq("#Forward_H_"+RecId+" .txtEmail").focus();
        return;
    }
    
    if (!mailcheck(toEmlId)){
        MyJq("#Forward_H_"+RecId+" .txtEmail").focus();
        return;
    }
    
    showload(MyJq("#send_"+RecId),"Sending mail....");

            
        MyJq.ajax( {
                                  type: "POST",
                                  url: "Chat.aspx/ForwardProfile",
                                  data: "{toNm:'" + frNm + "',toEml:'" + toEmlId +"',frNm:'" + toNm + "',Subj:'"+ toNm + " forwarded A Matching profile from Mangalyasearch.com to you',comments:'" + comments +"',ProfUid:'" + ProfUid + "',ProfImg:'" + ProfImg + "',ProfMsg:'" + ProfMsg + "'}",
                                  contentType: "application/json; charset=utf-8",
                                  dataType: "json",
                                  success: function(res) {
                                        if (res=='') res="Mail Successfully Send";
                                        hideload();
                                        MyJq(".sucMess").remove();
                                        showMessage(MyJq("#send_"+RecId),res);
                                        MyJq("#send_"+RecId).attr("disabled","");
                                        setTimeout('CloseForwardInt(\''+RecId+'\')',2000); 
                                    
                                  },
                                  error: function (errResp,dfd,errText){
                                    
                                    alert(errResp.responseText);
                                    hideload();
                                }
                });
        
}                                

 function showMessage(obj,mesg,timeout){
    if (timeout==null) timeout=2000;
    MyJq(".sucMess").remove();
    obj.after("<div class='sucMess'>"+mesg+"</div>");
    setTimeout('MyJq(".sucMess").hide();',timeout);
 }
 
 function hideload(){
    MyJq("#load").fadeOut('normal');
    MyJq("#load").remove();
 }
 function showload(obj,mess){
    MyJq("#load").remove();
    obj.after("<span id='load' class='load'><img src='images/load.gif' alt='' />"+mess+"</span>");
    MyJq("#load").fadeIn('normal');
    
 }
 
 function ForwardProfileClicked(RecId,RecNm)
 {
      showload(MyJq("#imgForward_"+RecId),"Loading..");
      MyJq(".Forward_H").hide('normal');
      MyJq(".Forward_But").show('normal');
      setTimeout('hideload()',2000);
      MyJq("#imgForward_"+RecId).hide('normal');
      MyJq("#Forward_H_"+RecId).show('slow');
  }    
      
 function removesucmess(){
    MyJq(".sucMess").remove()
 }
 
 
 //***************************** Search Options****************************
 
    function searchId(){
        if (MyJq("#srchId").val()==''){
            showMessage(MyJq("#searchIdSpan"),"Profile Id cannot be blank",'4000');
            return;
         }
         showload(MyJq("#searchIdSpan"),"Accessing the profile..");
        var str = "";
        
        str = 'uId=' + MyJq("#srchId").val() + '&isUid=1';
        window.location='bggrmdtls.aspx?' + str;
        hideload();
         
    }
    
    function searchwithoptions(){
        var agefr,ageto,htfrm,htto;
        agefr=MyJq("#selMstAgeFr").val();
        ageto=MyJq("#selMstAgeTo").val();
        htfrm=MyJq("#selMstHeightFrm").val();
        htto=MyJq("#selMstHeightTo").val();
        
        if (agefr>ageto){
            showMessage(MyJq("#selMstAgeFr"),"Age from cannot be greater than Age To",'4000');
            MyJq("#selMstAgeFr").focus();
            return;    
        }
        if (agefr>0 && ageto==0){
            showMessage(MyJq("#selMstAgeTo"),"Select Age To also",'4000');
            MyJq("#selMstAgeTo").focus();
            return;    
        }    
        if (agefr==0 && ageto>0){
            showMessage(MyJq("#selMstAgeFr"),"Select Age From also",'4000');
            MyJq("#selMstAgeFr").focus();
            return;    
        }
        if (htfrm>htto){
            showMessage(MyJq("#selMstHeightFrm"),"Height from is greater than Height To",'4000');
            MyJq("#selMstHeightFrm").focus();
            return;    
        }
        if (htfrm>0 && htto==0){
            showMessage(MyJq("#selMstHeightTo"),"Select Height To also",'4000');
            MyJq("#selMstHeightTo").focus();
            return;    
        }
        if (htfrm==0 && htto>0){
            showMessage(MyJq("#selMstHeightFrm"),"Select Height From also",'4000');
            MyJq("#selMstHeightFrm").focus();
            return;    
        }
       var queryStr=""
       var lang=MyJq("#selMstLang").val();
       var rel=MyJq("#cmbMstRel").val();
       var cast=MyJq("#cmbMstCast").val();
       var photo;
       
       if (MyJq("#photo").attr("checked")) {       
            photo="Y"; 
       }         
       else {
            photo="N";
       }
            
       var sex=MyJq("#selMstSex").val();
       
       
        if(!(lang==null || lang=='undefined')) {queryStr = "&lang=" + lang;}
        queryStr += "&reli=" + rel;
        queryStr += "&caste=" + cast;
        queryStr += "&ageQf=" + agefr;
        queryStr += "&ageQt=" + ageto;
        queryStr += "&htQf=" + htfrm;
        queryStr += "&htQt=" + htto;
        queryStr += "&MF=" + sex;
        queryStr += "&photo=" + photo;
       
       window.location="MatriSearch.aspx?search=2" + queryStr;
    }
    
//   
    
    function searchwithoptionsadv(){
        var agefr,ageto,htfrm,htto,edu,occ,st,country;
        agefr=MyJq("#selMstAgeFr").val();
        ageto=MyJq("#selMstAgeTo").val();
        htfrm=MyJq("#selMstHeightFrm").val();
        htto=MyJq("#selMstHeightTo").val();
        
        edu="";occ="";st="";country="";
        
        
        if (agefr>ageto){
            showMessage(MyJq("#selMstAgeFr"),"Age from cannot be greater than Age To",'4000');
            MyJq("#selMstAgeFr").focus();
            return;    
        }
        if (agefr>0 && ageto==0){
            showMessage(MyJq("#selMstAgeTo"),"Select Age To also",'4000');
            MyJq("#selMstAgeTo").focus();
            return;    
        }    
        if (agefr==0 && ageto>0){
            showMessage(MyJq("#selMstAgeFr"),"Select Age From also",'4000');
            MyJq("#selMstAgeFr").focus();
            return;    
        }
        if (htfrm>htto){
            showMessage(MyJq("#selMstHeightFrm"),"Height from is greater than Height To",'4000');
            MyJq("#selMstHeightFrm").focus();
            return;    
        }
        if (htfrm>0 && htto==0){
            showMessage(MyJq("#selMstHeightTo"),"Select Height To also",'4000');
            MyJq("#selMstHeightTo").focus();
            return;    
        }
        if (htfrm==0 && htto>0){
            showMessage(MyJq("#selMstHeightFrm"),"Select Height From also",'4000');
            MyJq("#selMstHeightFrm").focus();
            return;    
        }
       
       var lang="";
       MyJq("#selMstLang_param").each(function(){
                MyJq("#selMstLang_param option").attr("selected","selected");
            });
            
       if (MyJq("#selMstLang_param").val()!=null) lang=MyJq("#selMstLang_param").val();
       
       var cast="";
       MyJq("#selMstCaste_param").each(function(){
                MyJq("#selMstCaste_param option").attr("selected","selected");
            });
            
       if (MyJq("#selMstCaste_param").val()!=null) cast=MyJq("#selMstCaste_param").val();     
       
       MyJq("#selMstOcc_param").each(function(){
                MyJq("#selMstOcc_param option").attr("selected","selected");
            });
            
       if (MyJq("#selMstOcc_param").val()!=null) occ=MyJq("#selMstOcc_param").val();
       
       MyJq("#selMstEdu_param").each(function(){
                MyJq("#selMstEdu_param option").attr("selected","selected");
            });
            
       if (MyJq("#selMstEdu_param").val()!=null) edu=MyJq("#selMstEdu_param").val();
       
       
       MyJq("#selMstSt_param").each(function(){
                MyJq("#selMstSt_param option").attr("selected","selected");
            });
            
       if (MyJq("#selMstSt_param").val()!=null) st=MyJq("#selMstSt_param").val();
       
       MyJq("#selMstCountry_param").each(function(){
                MyJq("#selMstCountry_param option").attr("selected","selected");
            });
            
       if (MyJq("#selMstCountry_param").val()!=null) country=MyJq("#selMstCountry_param").val();
       
            
       
       var marital,profpost,haschildren,manglik,diet,complexion,bodytype,smoke,drink,physical;
       
       marital="";profpost="";haschildren="";manglik="";diet="";
       complexion="",bodytype="";smoke="",drink="";physical="";
       
       MyJq('input[type="checkbox"]:checked').each(function(){
                  
        if (MyJq("#"+this.id).val()!='' && MyJq("#"+this.id).val()!=undefined){
        
            switch (this.name){
                case "Marital_Status":{
                    if (marital!="")   marital+=",";  
                 
                    marital+=MyJq("#"+this.id).val();
                    
                }
                break;
                case "profilePost":{
                    if (profpost!="")   profpost+=",";  
                 
                    profpost+=MyJq("#"+this.id).val();
                }
                break;
                case "manglik":{
                    if (manglik!="")   manglik+=",";  
                 
                    manglik+=MyJq("#"+this.id).val();
                }
                break;
                case "diet":{
                    if (diet!="")   diet+=",";  
                 
                    diet+=MyJq("#"+this.id).val();
                }
                break;
                case "complexion":{
                    if (complexion!="")   complexion+=",";  
                 
                    complexion+=MyJq("#"+this.id).val();
                }
                break;
                case "BodyType":{
                    if (bodytype!="")   bodytype+=",";  
                 
                    bodytype+=MyJq("#"+this.id).val();
                }
                break;
                case "Smoke":{
                    if (smoke!="")   smoke+=",";  
                 
                    smoke+=MyJq("#"+this.id).val();
                }
                break;
                case "drink":{
                    if (drink!="")   drink+=",";  
                 
                    drink+=MyJq("#"+this.id).val();
                }
                break;
           }
           
        }
       
        });
        
        
        MyJq('input[type="radio"]:checked').each(function(){
                  
                if (MyJq("#"+this.id).val()!='' && MyJq("#"+this.id).val()!=undefined){
                        switch (this.name){
                            case "HasChildren":{
                        
                                if (haschildren!="")   haschildren+=",";  
                                 
                                haschildren+=MyJq("#"+this.id).val();
                                }
                                break;
                            case "Physical":{
                                if (physical!="")   physical+=",";  
                             
                                physical+=MyJq("#"+this.id).val();
                                }
                                break;
                     }
                }
                
           });
        
       
        
       
       var photo;
       
       if (MyJq("#photo").attr("checked")) {       
            photo="Y"; 
       }         
       else {
            photo="N";
       }
            
       var sex=MyJq("#selMstSex").val();
        
       var loc= "MatriSearch.aspx?search=3&lang="+lang+"&caste="+cast+"&city="+st+"&country="+country+"&Occ="+occ+"&Edu="+edu+"&marital="+marital;
       loc+="&hasChild="+haschildren+"&post="+profpost+"&mang="+manglik+"&diet="+diet+"&complex="+complexion+"&bodyType="+bodytype;
       loc+="&smok="+smoke+"&drin="+drink+"&phy="+physical+"&photo="+photo+"&ageQf="+agefr+"&ageQt="+ageto+"&htQf="+htfrm+"&htQt="+htto+"&MF="+sex;
       window.location= loc;
    }        
 
    
 //************************************************************************
/**
 * Cookie plugins
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



