var strMlsCheck='';
var flagRequestCheck=true;

jQuery(document).ready(function () {

	//get the fields here.
		var city2 = new Array();

        var     email = jQuery("#txtemail"),
		password = jQuery("#txtpassword"),
		title = jQuery("#txtsavesearch"),
		title_update = jQuery("#txtsavesearch_update"),
		hidSearchId = jQuery("#hidSearchId"),
		type = jQuery("#type"),
		savequery = jQuery("#savequery"),
		bdrms = jQuery("#bdrms"),
		baths = jQuery("#baths"),
		price1 = jQuery("#price1"),
		price2 = jQuery("#price2"),
		sqft = jQuery("#sqft"),
		acres = jQuery("#acres"),
		imgonly = jQuery("#imgonly"),
		vronly = jQuery("#vronly"),
		golf = jQuery("#golf"),
		water = jQuery("#water"),
		park = jQuery("#park"),
		horse = jQuery("#horse"),
		city = jQuery("#city"),
		tips = jQuery("#validateTips"),
		tips2 = jQuery("#validateTips2"),
		tips3 = jQuery("#validateTips3"),
        tips4 = jQuery("#validateTips4"),
        tips5 = jQuery("#validateTips2_update"),
		s_firstname = jQuery("#txtFirstName"),
		s_lastname = jQuery("#txtLastName"),
		s_phone = jQuery("#txtHomePhone"),
		s_email = jQuery("#txtEmail"),
		s_password = jQuery("#txtPassword"),
		s_cpassword = jQuery("#txtConfirmPassword"),
        fav_email = jQuery("#login_txtemail"),
        fav_password = jQuery("#login_txtpassword"),
       	allFields = jQuery([]).add(email).add(password).add(title);

         var s_firstname = null,s_lastname = null, s_phone = null, s_email = null, s_password = null, s_cpassword = null;
      
   jQuery("#dialog_link").hover(
		function(){
			jQuery(this).addClass("ui-state-hover");
	},
		function(){
		jQuery(this).removeClass("ui-state-hover");
	});
   jQuery("#signuplink").hover(
			function(){
				jQuery(this).addClass("ui-state-hover");
		},
			function(){
			jQuery(this).removeClass("ui-state-hover");
		});
	jQuery("#dialog_link2").hover(
			function(){
				jQuery(this).addClass("ui-state-hover");
		},
			function(){
			jQuery(this).removeClass("ui-state-hover");
		});
	
	// Dialog Link
	jQuery('#dialog_link').click(function(){
        jQuery.ajax({
            type:"POST",
            url:"/checkSessionForSaveDialog.php",
            cache: false,
            success:function(data){
        	
        	
                if(data == 'true'){
                	
                    jQuery('#dialog2').dialog('open');
                }else{
                    jQuery('#dialog').dialog('open');
                }
            }

        });
    });
	
    jQuery('#dialog_link2').click(function(){
        jQuery('#dialog2').dialog('open');
    });
    
    jQuery('#dialog_link_2').click(function(){
    	 jQuery('#signupform').dialog('close');
        jQuery('#dialog').dialog('open');
    });

    jQuery('#dialog_link_update').click(function(){
    	jQuery('#dialog2_update').dialog('open');
    });
    
    
    jQuery('#signuplink').click(function(){
        jQuery('#dialog').dialog('close');
        jQuery('#signupform').dialog('open');
        s_firstname = jQuery("#txtFirstName");
        s_lastname = jQuery("#txtLastName");
        s_phone = jQuery("#txtHomePhone");
        s_email = jQuery("#txtEmail");
        s_password = jQuery("#txtPassword");
        s_cpassword = jQuery("#txtConfirmPassword");
        s_note = jQuery('#txtNote');
        tips3 = jQuery("#validateTips3");
        allFields = jQuery([]).add(s_firstname).add(s_lastname).add(s_phone).add(s_email).add(s_password).add(s_cpassword).add(s_note);
    });
    jQuery('#login_signuplink').click(function(){
        jQuery('#login').dialog('close');
        jQuery('#signupform').dialog('open');
        s_firstname = jQuery("#txtFirstName");
        s_lastname = jQuery("#txtLastName");
        s_phone = jQuery("#txtHomePhone");
        s_email = jQuery("#txtEmail");
        s_password = jQuery("#txtPassword");
        s_cpassword = jQuery("#txtConfirmPassword");
        tips3 = jQuery("#validateTips3");
        allFields = jQuery([]).add(s_firstname).add(s_lastname).add(s_phone).add(s_email).add(s_password).add(s_cpassword);
    });
	

	function updateTips(t) {
		tips.text(t).effect("highlight",{},1500);
	}
	function updateTips2(t) {
		tips2.text(t).effect("highlight",{},1500);
	}
	function updateTips3(t) {
		tips3.text(t).effect("highlight",{},2000);
	}
        function updateTips4(t) {
		tips4.text(t).effect("highlight",{},1500);
	}
        function updateTips5(t) {
    		tips5.text(t).effect("highlight",{},1500);
    	}

        function matchPassword(p,cp)
        {
            if( p.val() != cp.val())
            {
                updateTips3("Password must match confirm password");
                return false;
            }
                
            else
                return true;
        }
	function checkLength(o,n,min,max,form) {

		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			if(form == "login")
				updateTips("Length of " + n + " must be between "+min+" and "+max+".");
			else if(form == "savetitle")
				updateTips2("Length of " + n + " must be between "+min+" and "+max+".");			
			else if(form == "signup")
				updateTips3("Length of " + n + " must be between "+min+" and "+max+".");
                        else if(form == "favorite_login")
				updateTips3("Length of " + n + " must be between "+min+" and "+max+".");
			return false;
		} else {
			return true;
		}
	}
	function checkRegexp(o,regexp,n,form) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');

                        if(form == "login")
                            updateTips(n);
                        else if(form == "signup")
                            updateTips3(n);
                        
			return false;
		} else {
			return true;
		}
	}

	// Dialog
	jQuery('#dialog').dialog({
		autoOpen: false,
		width: 340,
		title:"Sign In",
		modal: true,
		draggable: false,
		hide : 'slide',
		show :'slide',
		resizable: false,
		buttons: {
			"Login": function() {
				var bValid = true;
				var flag = false;
				allFields.removeClass('ui-state-error');
		
				bValid = bValid && checkLength(email,"email",6,80,"login");
				bValid = bValid && checkLength(password,"password",5,16,"login");
				bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com","login");
				bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9","login");
				var fav_mlsno=jQuery('input[name=login_mlsno]').val();
				if (bValid) {
					jQuery.ajax({
						type:"POST",
						url:"/mls_search/includes/ajaxfunctions.php?emailid="+ email.val() +"&password="+ password.val() + "&action=login",
						cache: false,
						success:function(data){
							if(jQuery.trim(data) == 'success'){
								updateTips("User name or password matched.");
								// Dialog Link
								jQuery("#dialog_link").unbind("click");
								jQuery('#dialog_link').click(function(){
									jQuery('#dialog2').dialog('open');
								});
								flag = true;
							}else{
								updateTips("User name or password not matched.");
								flag=false;
							}
						},
						complete:function(){
							if(flag){
								if(strMlsCheck!='')
								{	
								jQuery('#dialog').dialog('close');
								}
								else
								{
									jQuery('#dialog2').dialog('open');
									jQuery('#dialog').dialog('close');
								}
							}
						}
					});
				}
			}, 
			"Cancel": function() { 
				jQuery(this).dialog("close"); 
			}
		}
	});
	
	jQuery('#signupform').dialog({
        autoOpen: false,
        width: 730,
        height:560,
        title:"Sign Up",
        modal: true,
        draggable: false,
        hide : 'slide',
        show :'slide',
        resizable: false,
        buttons: {
            "START VIEWING HOMES RIGHT NOW!": function() {

                var bValid = true;
                var flag = false;
                
                s_firstname = jQuery("#txtFirstName");
                s_lastname = jQuery("#txtLastName");
                s_phone = jQuery("#txtHomePhone");
                s_email = jQuery("#txtEmail");
                s_password = jQuery("#txtPassword");
                s_cpassword = jQuery("#txtConfirmPassword");
                s_note =  jQuery("#txtNote");
                //tips3 = jQuery("#validateTips3");

                allFields = jQuery([]).add(s_firstname).add(s_lastname).add(s_phone).add(s_email).add(s_password).add(s_cpassword).add(s_note);

                allFields.removeClass('ui-state-error');
                bValid = bValid && checkLength(s_firstname,"first name",2,80,"signup");
                bValid = bValid && checkLength(s_lastname,"last name",2,80,"signup");
                bValid = bValid && checkRegexp(s_phone,/\d/,"Phone field only allow : 0-9",0,7,"signup");
                bValid = bValid && checkLength(s_email,"email",2,80,"signup");
                bValid = bValid && checkRegexp(s_email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. name@domain.com","signup");
                bValid = bValid && checkLength(s_password,"password",5,16,"signup");
                bValid = bValid && checkLength(s_cpassword,"password",5,16,"signup");
                bValid = bValid && checkRegexp(s_password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9","signup");
                bValid = bValid && matchPassword(s_password, s_cpassword,"signup");

                if (bValid) 
                {
                	if(flagRequestCheck)
                	{
                	flagRequestCheck=false;
                    jQuery.ajax({
                        type:"POST",
                        data:"userEmail="+ s_email.val() + "&FirstName="+s_firstname.val()+"&LastName="+s_lastname.val()+"&PhoneNo="+s_phone.val()+"&Password="+s_password.val()+"&Note="+s_note.val()+"&action=checkRegEmail",
                        url:"/mls_search/includes/ajaxfunctions.php",
                        cache: false,
                        success:function(data){
                            if(jQuery.trim(data) == 'success'){
                                updateTips3("User saved successfully.");
                                flagRequestCheck=false;
                                flag = true;
                            }else{
                                updateTips3("Email is already in used, use other..");
                                flagRequestCheck=true;
                                flag=false;
                            }
                        },
                        complete:function(){
                            if(flag){
                            	if(strMlsCheck!='')
                            	{	
                            		jQuery('#signupform').dialog('close');
                            		jQuery_addfavorite(fav_mlsno);
	                            }
                            	else
                            	{
                            		jQuery('#signupform').dialog('close');
	                                jQuery('#dialog2').dialog('open');
                            		 
                            	}
                            	
                            }
                        }
                    });
                }
                } 	
            },
            "Cancel": function() {
                jQuery(this).dialog("close");
            }
        }
    });
	
	// Dialog2
	jQuery('#dialog2').dialog({
		autoOpen: false,
		width: 300,
		height:175,
		title:"Search Title",
		modal: true,
		draggable: false,
		hide : 'slide',
		show :'slide',
		resizable: false,
		buttons: {
			"Save": function() {
					var bValid = true;
					var flag = false;
					allFields.removeClass('ui-state-error');
				
					bValid = bValid && checkLength(title,"Title",2,50,"savetitle");
					
					var imgonly=$('#imgonly:checked').val();
					var vronly=$('#vronly:checked').val();
					var golf=$('#golf:checked').val();
					var water=$('#water:checked').val();
					var park=$('#park:checked').val();
					var horse=$('#horse:checked').val();
					var type=jQuery('#type:checked').val();
				
				
					jQuery.ajax({
						type:"POST",
						url:"/mls_search/includes/ajaxfunctions.php?searchtitle="+ title.val() + "&action=savesearch&type="+type+"&bdrms="+bdrms.val()+"&baths="+baths.val()+"&price1="+price1.val()+"&price2="+price2.val()+"&sqft="+sqft.val()+"&acres="+acres.val()+"&imgonly="+imgonly+"&vronly="+vronly+"&golf="+golf+"&water="+water+"&park="+park+"&horse="+horse+"&city="+jQuery("#city").val()+"&savequery="+savequery.val(),
						cache: false,
						success:function(data){
						
					
							if(jQuery.trim(data) == 'success'){
								updateTips2("Title saved successfully.");
								flag = true;
							}else{
								updateTips2("Title already used, use other name..");
								flag=false;
							}		
						},
						complete:function(){
							if(flag){
								jQuery('#dialog2').dialog('close');
								//submit the form 
								jQuery('#frmMLSSearch').submit();
							}
						}
					});
			}, 
			"Cancel": function() { 
				jQuery(this).dialog("close"); 
			}
		}
	});
	
	jQuery('#dialog2_update').dialog({
		autoOpen: false,
		width: 300,
		height:175,
		title:"Search Title",
		modal: true,
		draggable: false,
		hide : 'slide',
		show :'slide',
		resizable: false,
		buttons: {
			"Save": function() {
					var bValid = true;
					var flag = false;
					allFields.removeClass('ui-state-error');
					bValid = bValid && checkLength(title_update,"Title",2,50,"savetitle");
					var imgonly=$('#imgonly:checked').val();
					var vronly=$('#vronly:checked').val();
					var golf=$('#golf:checked').val();
					var water=$('#water:checked').val();
					var park=$('#park:checked').val();
					var horse=$('#horse:checked').val();
					var type=jQuery('#type:checked').val();
				
					jQuery.ajax({
						type:"POST",
						url:"/mls_search/includes/ajaxfunctions.php?hidSearchId="+ hidSearchId.val() + "&searchtitle="+ title_update.val() + "&action=savesearch_update&type="+type+"&bdrms="+bdrms.val()+"&baths="+baths.val()+"&price1="+price1.val()+"&price2="+price2.val()+"&sqft="+sqft.val()+"&acres="+acres.val()+"&imgonly="+imgonly+"&vronly="+vronly+"&golf="+golf+"&water="+water+"&park="+park+"&horse="+horse+"&city="+city.val()+"&savequery="+savequery.val(),
						cache: false,
						success:function(data){
					
							if(jQuery.trim(data) == 'success'){
								updateTips2("Title saved successfully.");
								flag = true;
							}else{
								updateTips5("Title already used, use other name..");
								flag=false;
							}		
						},
						complete:function(){
							if(flag){
								jQuery('#dialog2_update').dialog('close');
								//submit the form 
								jQuery('#frmMLSSearch').submit();
							}
						}
					});
			}, 
			"Cancel": function() { 
				jQuery(this).dialog("close"); 
			}
		}
	});
	
	
	
        	// Dialog
	jQuery('#login').dialog({
		autoOpen: false,
		width: 340,
		height:250,
		title:"Sing In",
		modal: true,
		draggable: false,
		hide : 'slide',
		show :'slide',
		resizable: false,
		buttons: {
			"Login": function() {

				var bValid = true;
				var flag = false;
                                var fav_mlsno=jQuery('input[name=login_mlsno]').val();
				allFields.removeClass('ui-state-error');
                                
				bValid = bValid && checkLength(fav_email,"email",6,80,"favorite_login");
				bValid = bValid && checkLength(fav_password,"password",5,16,"favorite_login");
				bValid = bValid && checkRegexp(fav_email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
				bValid = bValid && checkRegexp(fav_password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");

				if (bValid) {
					jQuery.ajax({
						type:"POST",
						url:"/mls_search/includes/ajaxfunctions.php?emailid="+ fav_email.val() +"&password="+ fav_password.val() + "&action=login",
						cache: false,
						success:function(data){
							if(jQuery.trim(data) == 'success'){
								updateTips4("User name or password matched.");
								flag = true;
							}else{
								updateTips4("User name or password not matched.");
								flag=false;
							}
						},
						complete:function(){
							if(flag){
                                jQuery_addfavorite(fav_mlsno);
								jQuery('#login').dialog('close');
							}
						}
					});
				}
			},
			"Cancel": function() {
				jQuery(this).dialog("close");
			}
		}
	});
});
var arrMlsPro = new Array();
function jQuery_addfavorite(mlsno){
	
	strMlsCheck=mlsno;

    var strWait = "<table border=0 cellspacing=0><tr><td align=right></td><td valign=middle align=right><font size=1> Please wait...</font></td></tr></table>";
    if(mlsno != ""){
        //first check if user already logged in or not
        arrMlsPro["" + mlsno+""] = jQuery("#divFavorite" + mlsno).html();
        jQuery("#divFavorite" + mlsno).html(strWait);
        jQuery.ajax({
           type : "GET",
           url:"/mls_search/includes/ajaxfunctions.php",
           data:"action=addtofavorite&mlsnum=" + mlsno,
           
           success: function(data){
        	
               if(jQuery.trim(data) == 'SessionExpired'){
                   //jQuery('#login_mlsno').attr('value', mlsno);
                   jQuery('#login_mlsno').val(mlsno);
//                   alert(jQuery('input[name=login_mlsno]').val());
                   jQuery('#dialog').dialog('open');
                   jQuery("#divFavorite" + mlsno).html(arrMlsPro[mlsno]);
                }else{
                    jQuery("#divFavorite" + mlsno).html(data);
                }
           },
           complete:function(){
                 jQuery("#favoritestatus_"+mlsno).hide();
                 jQuery("#favoritestatus_"+mlsno).fadeIn(5000);
                 jQuery("#favoritestatus_"+mlsno).fadeOut(5000);
           }
        });
    }
}


function jQuery_removefavorite(mlsno){
   if(confirm("Are you sure you want to remove this property from your favorite list?"))
        {
            var strWait = "<table border=0 cellspacing=0><tr><td align=right></td><td valign=middle align=right><font size=1> Please wait...</font></td></tr></table>";
            if(mlsno != ""){
                //first check if user already logged in or not
                jQuery("#divFavorite" + mlsno).html(strWait);
                jQuery.ajax({
                   type : "GET",
                   url:"/mls_search/includes/ajaxfunctions.php",
                   data:"action=removefavorite&mlsnum=" + mlsno,
                   success: function(data){
                       if(jQuery.trim(data) == 'SessionExpired'){
                           alert("not allowed to perfome this operation");
                        }else{
                            jQuery("#divFavorite" + mlsno).html(data);
                        }
                   },
                   complete:function(){
                     jQuery("#favoritestatus_"+mlsno).hide();
                     jQuery("#favoritestatus_"+mlsno).fadeIn(5000);
                     jQuery("#favoritestatus_"+mlsno).fadeOut(5000);
                   }
                });
            }
        }
}
