$.fn.clearForm = function() {
    return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

$.maxZIndex = $.fn.maxZIndex = function(opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>    
    /// <param name="opt" type="object">
    /// inc: increment value, 
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);    
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

$(function() {

    $( "#sms-form" ).dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        resizable: false,
        draggable: false,
        closeOnEscape: true,
        buttons: {
            "Start Process": function() {
                                        
                $.ajax({
                    type: "POST",
                    url: "/register/checksms",
                    data: {
                        receiver : $('#cellPhone').val()
                        },
                    success: function(msg){
                        //Timed poll for text
                        //ajaxTime.php is called every second to get time from server
                        var refreshId = setInterval(function() {
                            var phone = $('#cellPhone').val();
                            $('#txt-message').load('/register/retrievesms?phone='+phone+'&code='+msg);
                        }, 1000);

                    //alert(msg);
                    }
                });
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        }
    });

    $("#error").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        closeOnEscape: true
    });

    $("#info").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        closeOnEscape: true
    });

    $("#detail").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        closeOnEscape: true
    });

    $("#tabs").tabs();

    $("#signup-form").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        width: 450,
        closeOnEscape: true,
        buttons: {
            'Continue to Step 2': function() {
                formdata = $('#signup-form form').serialize();
                $.ajax({
                    type: "POST",
                    url: "/login/signup",
                    dataType: 'json',
                    data: formdata,
                    success: function(msg){
                        allowed = msg.success;
                        if (allowed == "true"){
                            $("#signup-form").dialog('close');
                            $("#mobile-form").dialog('open');
                        }
                        else{
                            $.each(msg, function(index, value) {
                                $("#error").append(value+"<br />");
                            });
                            $("#error").dialog('open');
                        }

                    }
                });
            }
        }
        
    });


    $("#dialog-login" ).dialog({
        zIndex: 99999,
        resizable: false,
        autoOpen: false,
        position: 'top',
        modal: true
    });
    
    $("#dialog-password" ).dialog({
        zIndex: 999999,
        resizable: false,
        autoOpen: false,
        position: 'top',
        modal: true,
        buttons: {"Send password": function (){
                          formdata = $('#forgot-form').serialize();
                $.ajax({
                    type: "POST",
                    url: "/login/forgotpassword",
                    dataType: 'json',
                    data: formdata,
                    success: function(msg){
                        allowed = msg.success;
                        //alert (msg.success);
                        if (allowed == true){
                        $("#dialog-password-response").html("<p>We've emailed your password to your home email address.</p>");
                        $("#dialog-password-response").dialog('open');
                        $("#dialog-password").dialog('close');
                        }
                        else{
                        $("#dialog-password-response").html("<p>That email address isn't on Cardless Contact.</p>");
                        $("#dialog-password-response").dialog('open');
                        $("#dialog-password").dialog('close');    
                        }

                    }
                });
            }  
        }
    });
    
    $("#dialog-password-response").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        closeOnEscape: true
    });

    $("#mobile-form").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        closeOnEscape: true,
        buttons: {
            'Finish Sign Up': function() {
                formdata = $('#mobile-form form').serialize();
                $.ajax({
                    type: "POST",
                    url: "/login/signup2",
                    dataType: 'json',
                    data: formdata,
                    success: function(msg){
                        allowed = msg.success;
                        if (allowed == "true"){
                            $("#info").html("You're done! <a href='/login'>Click here to login</a>");
                            $("#info").dialog('open');
                            $("#mobile-form").dialog('close');
                        }
                        else{
                            $.each(msg, function(index, value) {
                                $("#error").append(value+"<br />");
                            });
                            $("#error").dialog('open');
                        }

                    }
                });
            }
        }
    });

    $("button").button();



    // send clicks where they need to go right here (aka the click handler secrion)
    $("#forgotpassword").click(function() {
        $("#dialog-login").dialog('close');
        $("#dialog-password").dialog('open');
        return false;
    });
    
    $("#login_button").click(function() {
        login();
        return false;
    });
    $("#signup_button").click(function() {
        $("#signup-form").dialog('open');
        return false;
    });
    $("#salesforce").click(function() {
      salesforceExport();
    });
    $("#salesforce_export").click(function() {
      salesforceExportLogin();
    });
    $("#google").click(function() {
      googleExport();
    });
    $("#google_export").click(function() {
      googleExportLogin();
    });

});


function login(){
    //alert ("Test");
    url = "/login/authenticate/";
    formdata = $("#login-form").serialize();
    $.ajax({
        type: "POST",
        url: url,
        data: formdata,
        success: function(msg){
            //alert(msg.allow);
            if (msg.allow == true){
                //alert("Validated");
                window.location="http://www.cardlesscontact.com/";
            }
            else
            {

                $.colorbox({inline: true, href:"#forgot_password", overlayClose: true, opacity: 0, height: 250, width: 350});
                //$(".ui-dialog-titlebar").hide();
                return false;
            //alert('Username or password is incorrect');

            }
        }
    });
}


function deleteContact(id){
    var answer = confirm("Are you sure you want to 'un-contact' this person?")
    if (answer){
                   var url = "/index/deletecontact/contactId/"+id;
                    $.ajax({
                    type: "POST",
                    url: url,
                    success: function(msg){
                      window.location = '/index/dashboard';     
                    }
                });
         
    }
    
    return false;      
}

function forgotPassword(){
                formdata = $('#forgot-form').serialize();
                $.ajax({
                    type: "POST",
                    url: "/login/forgotpassword",
                    dataType: 'json',
                    data: formdata,
                    success: function(msg){
                        allowed = msg.success;
                        //alert (msg.success);
                        if (allowed == true){
                        alert("We've emailed your password to your home email address.");
                        $.colorbox.close();
                        }
                        else{
                        alert("We can't find that email address in our database");
                        $.colorbox.close();   
                        }

                    }
                });
}

function salesforceExport(){
                    $.colorbox({inline: true, href:"#salesforce_login_window", overlayClose: true, opacity: 0, height: 300, width: 350});
}

function googleExport(){
                    $.colorbox({inline: true, href:"#google_login_window", overlayClose: true, opacity: 0, height: 300, width: 350});
}





