var flag_signupdialog_close = false;
var go_back_page_signup = true;
var go_back_page_login = false;
var show_loading = false;
var flagRequestCheck=true;
function showLogin()
{
	go_back_page_login = false;
	go_back_page_signup = false;
    jQuery('#login').dialog('open');
    jQuery('#detail_signupform').dialog('close');
}

jQuery(document).ready(function(){

if(isUserLogged)
    open_signup_dialog();

var dl_email = jQuery("#login #login_txtemail"),
    dl_password = jQuery("#login #login_txtpassword"),
    tips4 = jQuery("#login #validateTips4");

tips5 = jQuery("#AdditionalInfoForm #validateTips4");

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

    function checkLength(o,n,min,max) {

        if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
                updateTips4("Length of " + n + " must be between "+min+" and "+max+".");

            return false;
        } else {
            return true;
        }
    }
    function checkRegexp(o,regexp,n) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass('ui-state-error');

                updateTips4(n);

            return false;
        } else {
            return true;
        }
    }

    jQuery('#AdditionalInfoForm').dialog({
    	autoOpen: false,
        width: 600,
        minWidth: 600,
        modal: true,
        title:'Schedule a Time to View Home',
        draggable: false,
        resizable: false,
        buttons: {
            "Cancel": function() {
                //jQuery(this).dialog("close");
                jQuery('#AdditionalInfoForm').dialog('close');
            },
            "Send": function() {
            	
                jQueryUiDialogTips = jQuery('#AdditionalInfoForm #validateTipsArrangeViewing');
                var bValid = true;
                jQuery('#AdditionalInfoForm #validateTipsArrangeViewing').html("");
                var txtname = jQuery('#AdditionalInfoForm #txtName');
                var txtemail = jQuery('#AdditionalInfoForm #txtMail');
                var txtphone = jQuery('#AdditionalInfoForm #txtPhone');
                var txtMLS = jQuery('#txtMLS').val();
                var txtUserID = jQuery('#txtUserID').val();
                
                var txtmsg = jQuery('#AdditionalInfoForm #txtMessage');
                var allFields = jQuery([]).add(txtemail).add(txtname).add(txtphone);
                allFields.removeClass('ui-state-error');

                bValid = bValid && checkLength(txtname,"Name",2,50);
                bValid = bValid && checkLength(txtemail,"txtemail",6,80);
                bValid = bValid && checkRegexp(txtemail,/^((([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");
                bValid = bValid && checkLength(txtphone,"Phone",10,12);
                if (bValid) {

                //jQuery(".ui-dialog-buttonpane").append(dialog_loader);
                    jQuery.ajax({
                        type:"POST",
                        url:"/ajax_addLead.php",
                        data: "name="+txtname.val()+"&email="+ txtemail.val() + "&phone="+txtphone.val()+"&message="+txtmsg.val()+"&MLS="+txtMLS+"&userID="+txtUserID+"&flag=req_additional_info",
                        success:function(data){
                    		jQuery("#AdditionalInfoForm").dialog("close");
                    	},
                    });
                }
            }
        }
    });

    jQuery('#login').dialog({
        autoOpen: false,
        width: 330,
        height:230,
        title:"Sing In",
        modal: true,
        draggable: false,
        hide : 'slide',
        show :'slide',
        resizable: false,
        closeOnEscape: false,
        open: function() {
    		jQuery('body').css({overflow:'hidden'});
    		jQuery('html').css({overflow:'hidden'});
    	},
    	  close:function(){
    		//alert(go_back_page_signup);
            if(go_back_page_login){
            	show_loading = true;
            	/*alert(goBackPageflag);
            	alert(goBackPageURL);
            	 show_loading = true;
                if(goBackPageflag)
                    history.go(-1);
                else*/
                    window.location = goBackPageURL;
            }
        },
        buttons: {
            "Login": function() {
                var bValid = true;
                var flag = false;
                go_back_page_login = true;

                allFields.removeClass('ui-state-error');
                bValid = bValid && checkLength(dl_email,"email",6,80);
                bValid = bValid && checkLength(dl_password,"password",5,16);
                bValid = bValid && checkRegexp(dl_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");
                bValid = bValid && checkRegexp(dl_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="+ dl_email.val() +"&password="+ dl_password.val() + "&action=login",
                        cache: false,
                        success:function(data){
                            if(jQuery.trim(data) == 'success'){
                                updateTips4("User name or password matched.");
                                flag = true;
                                go_back_page_login = false;

                                jQuery('html').css("overflow", "");
                                jQuery('body').css("overflow", "");

                            }else{
                                updateTips4("User name or password not matched.");
                                flag=false;
                            }
                        },
                        complete:function(){
                            if(flag){
                            	
                                jQuery('#login').dialog('close');
                            }
                        }
                    });
                }
            },
            "Cancel": function() {
            	 go_back_page_login = true;
                jQuery(this).dialog("close");
                jQuery('body').css({overflow:'auto'});
        		jQuery('html').css({overflow:'auto'});
        		// go_back_page_login = true;
                
                //jQuery("#detail_signupform").dialog('open');
            }
        }
    });


    jQuery('#signuplink').click(function(){
        go_back_page_login = false;
        jQuery('#login').dialog('close');
        jQuery('#detail_signupform').dialog('open');
        //open_signup_dialog();
    });
});

function open_signup_dialog(){
    
/*    jQuery("#detail_signupform").everyTime(1000,function() {
     if(flag_signupdialog_close){
        jQuery(this).dialog('close');
        flag_signupdialog_close = false;
    }
 });*/
    /*jQuery("#detail_signupform").everyTime(1000,function() {*/
        if(show_loading)
        {
            show_loading = false;
            jQuery("#pleasewait").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();
            jQuery("#pleasewait").dialog('open');
        }
        if(flag_signupdialog_close){
            jQuery(this).dialog('close');
            flag_signupdialog_close = false;
        }
    /* });*/
    go_back_page_signup = true;
    var ds_firstname = jQuery("#detail_signupform #txtFirstName"),
    ds_lastname = jQuery("#detail_signupform #txtLastName"),
    ds_phone = jQuery("#detail_signupform #txtHomePhone"),
    ds_email = jQuery("#detail_signupform #txtEmail"),
    ds_password = jQuery("#detail_signupform #txtPassword"),
    ds_cpassword = jQuery("#detail_signupform #txtConfirmPassword"),
    ds_note =  jQuery("#detail_signupform #txtNote"),
    tips5 = jQuery("#detail_signupform #validateTips5");
    tips3 = jQuery("#detail_signupform #validateTips3");

    allFields = jQuery([]).add(ds_firstname).add(ds_lastname).add(ds_phone).add(ds_email).add(ds_password).add(ds_cpassword).add(ds_note);

    function updateTips5(t) {
        tips5.text(t).effect("highlight",{},1500);
    }
    function updateTips3(t) {
        tips3.text(t).effect("highlight",{},1500);
    }

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

        if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
                updateTips5("Length of " + n + " must be between "+min+" and "+max+".");
            return false;
        } else {
            return true;
        }
    }
    function checkRegexp(o,regexp,n) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass('ui-state-error');
                updateTips5(n);
            return false;
        } else {
            return true;
        }
    }
    jQuery('#detail_signupform').dialog({
        autoOpen:true,
        width:720,
        height:520,
        title:strSignupTitel,
        modal:true,
        draggable:false,
        hide:'slide',
        show:'slide',
        resizable: false,
        closeOnEscape: false,
        open: function() {
    		jQuery('body').css({overflow:'hidden'});
    		jQuery('html').css({overflow:'hidden'});
    	},
        close:function(){
            if(go_back_page_signup){
            	 show_loading = true;
                if(goBackPageflag)
                    history.go(-1);
                else
                    window.location = goBackPageURL;
            }
        },
        buttons: {
            "START VIEWING HOMES RIGHT NOW!": function() {
                var bValid = true;
                go_back_page_signup = true;
                allFields.removeClass('ui-state-error');
                bValid = bValid && checkLength(ds_firstname,"first name",2,80);
                bValid = bValid && checkLength(ds_lastname,"last name",2,80);
                bValid = bValid && checkRegexp(ds_phone,/\d/,"Phone field only allow : 0-9",0,7,"signup");
                bValid = bValid && checkLength(ds_email,"email",2,80);
                bValid = bValid && checkRegexp(ds_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");
                bValid = bValid && checkLength(ds_password,"password",5,16);
                bValid = bValid && checkLength(ds_cpassword,"password",5,16);
                bValid = bValid && checkRegexp(ds_password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
                bValid = bValid && matchPassword(ds_password, ds_cpassword);

                if (bValid) {
                	if(flagRequestCheck)
                	{
                	flagRequestCheck=false;
                    jQuery.ajax({
                        type:"POST",
                        data:"userEmail="+ ds_email.val() + "&FirstName="+ds_firstname.val()+"&LastName="+ds_lastname.val()+"&PhoneNo="+ds_phone.val()+"&Password="+ds_password.val()+"&Note="+ds_note.val()+"&action=checkRegEmail",
                        url:"/mls_search/includes/ajaxfunctions.php",
                        success:function(data){
                    	        if(jQuery.trim(data) == 'success'){
                                flag_signupdialog_close=true;
                                go_back_page_signup = false;
                                flagRequestCheck=false;

                                jQuery('html').css("overflow", "");
                                jQuery('body').css("overflow", "");
                            }
                    	        else if (jQuery.trim(data) == 'invalidGeoPhon')
                                {
                                	updateTips3("Phone is invalide..");
                                	flagRequestCheck=true;
                                }
                    	        else{
                                updateTips5("Email is already in used, use other..");
                                flag_signupdialog_close=false;
                                flagRequestCheck=true;
                            }
                        },
                        complete:function(){
                            if(flag_signupdialog_close){
                            	jQuery('#detail_signupform').dialog('close');
                            }
                        }
                    });
                	}
                	}
            },
            "Cancel": function() {
                //window.location = backURL;
                go_back_page_signup = true;
                jQuery(this).dialog("close");
                jQuery('body').css({overflow:'auto'});
        		jQuery('html').css({overflow:'auto'});
            }
        }
    })
}

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;

			if (jQuery.isFunction(label)) {
				if (!times)
					times = fn;
				fn = label;
				label = interval;
			}

			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}

			times = times || 0;
			belay = belay || false;

			if (!element.$timers)
				element.$timers = {};

			if (!element.$timers[label])
				element.$timers[label] = {};

			fn.$timerID = fn.$timerID || this.guid++;

			var handler = function() {
				if (belay && this.inProgress)
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};

			handler.$timerID = fn.$timerID;

			if (!element.$timers[label][fn.$timerID])
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);

			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );

		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;

			if ( timers ) {

				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}

					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}

				for ( ret in timers ) break;
				if ( !ret )
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.timer.global;
		for ( var label in global ) {
			var els = global[label], i = els.length;
			while ( --i )
				jQuery.timer.remove(els[i], label);
		}
	});

function init_lead_formAdditionalInfo_dialogbox(){
	jQuery('#AdditionalInfoForm').dialog('open');
}



