//jquery example plugin
/**/
(function(a){
    a.fn.example=function(e,c){
        var d=a.isFunction(e);
        var b=a.extend({},c,{
            example:e
        });
        return this.each(function(){
            var f=a(this);
            if(a.metadata){
                var g=a.extend({},a.fn.example.defaults,f.metadata(),b)
            }else{
                var g=a.extend({},a.fn.example.defaults,b)
            }
            if(!a.fn.example.boundClassNames[g.className]){
                a(window).unload(function(){
                    a("."+g.className).val("")
                });
                a("form").submit(function(){
                    a(this).find("."+g.className).val("")
                });
                a.fn.example.boundClassNames[g.className]=true
            }
            if(a.browser.msie&&!f.attr("defaultValue")&&(d||f.val()==g.example)){
                f.val("")
            }
            if(f.val()==""&&this!=document.activeElement){
                f.addClass(g.className);
                f.val(d?g.example.call(this):g.example)
            }
            f.focus(function(){
                if(a(this).is("."+g.className)){
                    a(this).val("");
                    a(this).removeClass(g.className)
                }
            });
            f.change(function(){
                if(a(this).is("."+g.className)){
                    a(this).removeClass(g.className)
                }
            });
            f.blur(function(){
                if(a(this).val()==""){
                    a(this).addClass(g.className);
                    a(this).val(d?g.example.call(this):g.example)
                }
            })
        })
    };

    a.fn.example.defaults={
        className:"example"
    };

    a.fn.example.boundClassNames=[]
})(jQuery);


$(document).ready(function(){  

    $("#submit_lead").ajaxForm();

    $("#contactSubmit").click(
        function() {
            var messages = validateForm('#submit_lead .required');
            if(messages.length == 0){
                _gaq.push(['_setAccount', 'UA-8877323-2']);
                _gaq.push(['_trackEvent', 'Form', 'Submission', 'Home Evaluation Request']);
                $("form#submit_lead").submit();
                afterHomeContactSubmission();
            } else {
                alert(messages);
            }
        }
        );

    var afterHomeContactSubmission = function() {
        $("#info").html("<h1>Thank you for choosing SeniorLiving.Net!</h1><p style=\"font-size:12pt;\">A Senior Care Advisor will be contacting you within (1) business day.  They will ask a few additional questions so that we can provide community information that is the best fit for your care needs, location and budget.  As always, our assistance will be at no cost to you and your family.<br/><br/>If you have any questions, please call us at 866.342.4297.</p>");

        $("#info h1").css({
            "padding-top" : "100px",
            "width" : "300px",
            "text-align" : "center",
            "color" : "white",
            "margin" : "auto"
        });
        $("#info p").css({
            "padding-top" : "10px",
            "width" : "400px",
            "color" : "white",
            "margin" : "auto"
        });

    } ;

    $("#askTheExperts").ajaxForm();

    $("#askExpertSubmit").click(
        function() {
            var messages = validateForm('#askTheExperts .required');
            if(messages.length == 0){
                _gaq.push(['_setAccount', 'UA-8877323-2']);
                _gaq.push(['_trackEvent', 'Form', 'Submission', 'Ask The Experts']);
                $("form#askTheExperts").submit();
                afterExpertsSubmission();
            } else {
                alert(messages);
            }
        }
        );

    var afterExpertsSubmission = function() {
        $("#askExpertForm").html("<h1>Thank you for your question!</h1>");

        $("#askExpertForm h1").css({
            "padding-top" : "50px",
            "text-align" : "center",
            "color" : "#608613",
            "margin" : "0px"
        });


    } ;

    $("#shareThoughts").ajaxForm();

    $("#shareThoughtsSubmit").click(
        function() {
            var messages = validateForm('#shareThoughts .required');
            if(messages.length == 0){
                _gaq.push(['_setAccount', 'UA-8877323-2']);
                _gaq.push(['_trackEvent', 'Form', 'Submission', 'Share Your Thoughts']);
                $("form#shareThoughts").submit();
                afterShareThoughtsSubmission();
            } else {
                alert(messages);
            }
        }
        );

    var afterShareThoughtsSubmission = function() {
        $("#letUsKnowForm").html("<h1>Thank you for your comments!</h1>");

        $("#letUsKnowForm h1").css({
            "padding-top" : "100px",
            "padding-left" : "50px",
            "text-align" : "center",
            "color" : "#608613",
            "margin" : "auto"
        });


    } ;

    $("#articleContact").ajaxForm();

    $("#articleContactSubmit").click(
        function() {
            var messages = validateForm('#articleContact .required');
            if(messages.length == 0){
                _gaq.push(['_setAccount', 'UA-8877323-2']);
                _gaq.push(['_trackEvent', 'Form', 'Submission', 'Marketing Contact Form']);
                $("form#articleContact").submit();
                afterArticleContactSubmission();
            } else {
                alert(messages);
            }
        }
        );

    var afterArticleContactSubmission = function() {
        
        $("#articleContactForm").html("<h1>Thank you, one of our representatives will be in touch.</h1>");

        $("#articleContactForm h1").css({
            "padding-top" : "100px",
            "padding-bottom" : "300px",
            "text-align" : "center",
            "color" : "#608613",
            "margin" : "auto"
        });


    } ;

    $("#requestInfo").ajaxForm();
    $("#requestInfo").submit(        function() {
            var messages = validateForm('#requestInfo .required');
            if(messages.length == 0){
                _gaq.push(['_setAccount', 'UA-8877323-2']);
                _gaq.push(['_trackEvent', 'Form', 'Submission', 'RequestInfo Contact Form']);
                $("form#RequestInfo").submit();
                afterRequestInfoSubmission();
            } else {
                alert(messages);
            }
        });
    $("#newRequestInfo").submit(        function() {
            var messages = validateForm('#newRequestInfo .required');
            if(messages.length == 0){
                _gaq.push(['_setAccount', 'UA-8877323-2']);
                _gaq.push(['_trackEvent', 'Form', 'Submission', 'RequestInfo Contact Form']);
                $("form#newRequestInfo").submit();
                //afterRequestInfoSubmission();
            } else {
                alert(messages);
                return false;
            }
        });

    var afterRequestInfoSubmission = function() {

        $("#requestInfoContent").html("<h1>Thank you, one of our representatives will be in touch.</h1>");



    } ;

    /*
		Hold a default value for a field, 
	*/
    var defaultFormValueCache = Array();
	 
    function id_in_array(id,theArray) {
        var ret = -1;
	 	
        for (var i = 0; i < theArray.length; i++)
        {
            if (theArray[i][0] == id) {
                ret = i;
                break;
            }
        }
	 	
        return ret;
    }
	 
    $("input[type='text']").each(function() {
	 	
        if ($(this).parent().parent().parent().attr("class") != "customKwForm") {
            $(this).addClass("x-form-text");
        }
    }
    )
	 
    $("input[type='text']").focus( function() {
        //If we don't have a default cached, store it.
        /*   if($(this).attr("title") != "") {
            return false;
        }*/
        if ($(this).attr("id") == "searchBox" && $(this).attr("title") != "") {
            if (id_in_array($(this).attr("id"),defaultFormValueCache) < 0) {

                if ($(this).attr("id") == "") {
                    $(this).attr("id","input_id_" + $(this).attr("value").toString().replace(/ /g,""));
                }

                defaultFormValueCache[defaultFormValueCache.length] = new Array($(this).attr("id"), $(this).attr("value"));

                $(this).attr("value","");
            } else {
                //Look to see if the value is the cached default
                if (defaultFormValueCache[id_in_array($(this).attr("id"),defaultFormValueCache)][1] == $(this).attr("value"))
                {
                    $(this).attr("value","");
                }
            }
        } else {
            if (id_in_array($(this).attr("id"),defaultFormValueCache) < 0) {

                defaultFormValueCache[defaultFormValueCache.length] = new Array($(this).attr("id"), $(this).attr("title"));

                $(this).attr("value","");
            } else {
                //Look to see if the value is the cached default
                if (defaultFormValueCache[id_in_array($(this).attr("id"),defaultFormValueCache)][1] == $(this).attr("title"))
                {
                    $(this).attr("value","");
                }
            }
        }
    });
	 
    $("input[type='text']").blur( function() {
        /* if($(this).attr("title") != "") {
            return false;
        }
	 */
        if (jQuery.trim($(this).attr("value")) == "")
        {
            $(this).attr("value",defaultFormValueCache[id_in_array($(this).attr("id"),defaultFormValueCache)][1]);
        }
	  				
    });

    /*
    $("input[type='text']").example(function() {
        return $(this).attr('title');
    });
    */
    var myRequestInfoJSON = {
        "firstName" : null,
        "lastName"  : null,
        "city"  : null,
        "state"  : null,
        "phone"  : null,
        "email"  : null,
        "budget": null,
        "howsoon": null,
        "resident": null,
        "relationship": null
    };

	 
    var options = {
        beforeSubmit:  showRequest,  // pre-submit callback
        success:       showResponse  // post-submit callback
    };
	 
    $("#myRequestsSubmit").click(function() {
        var messages = validateForm("#myRequestForm .required");
        if(messages.length == 0){
            return true;
        }else{
            alert(messages);
        }
        return false;
    }
    );
    $('#submit_myrequests').submit(function() {
        $(this).ajaxSubmit(options);
        //alert("inside submit_myrequests submit");
        afterMyRequestsSubmission();
        return false;
    });

    /*
    $("#communityrequestsform #communityRequestsFormSubmit").click(function() {
        var messages = validateForm("#communityrequestsform .required");
        //alert("got here");
        if(messages.length == 0){
            return true;
        }else{
            alert(messages);
        }
        return false;
    }
    );
    */
     
    $('#submit_requests').submit(function() {
        options = {
            beforeSubmit:  showRequest  // pre-submit callback
        };

        var messages = validateForm("#communityrequestsform .required");
        //alert("got here");
        if(messages.length == 0){
            $(this).ajaxSubmit(options);
            $('#ModalFirstName').val($('#FirstName').val());
            $('#ModalLastName').val($('#LastName').val());
            $('#ModalPhone').val($('#Phone').val());
            $('#ModalEmail').val($('#Email').val());
            $('#ModalCity').val($('#City').val());
            $('#ModalState').val($('#State').val());
            try {
                loadForm("#dialog2 #communityform .requestForm");

                if (myRequestInfoJSON.email) {
                    setRequestData(myRequestInfoJSON);
                }
            } catch (e) {
            //alert(e);
            }

            //alert("inside submit_requests submit");
            afterCommunityFormSubmission();
        }else{
            alert(messages);
        }


        return false;
    });
     
    // bind to the form's submit event
    $('#submit_lead_request').submit(function() {
        alert(1);
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        var messages = validateForm("#dialog2 #communityform .required");
        if(messages.length == 0){
            try {
                translateFormToJSON("#dialog2 #communityform .requestForm");
                if (myRequestInfoJSON.email) {
                    setRequestData(myRequestInfoJSON);
                }
            } catch (e) {
                alert(e);
            }
	  		
            $(this).ajaxSubmit(options);
 
            // !!! Important !!!
            // always return false to prevent standard browser submit and page navigation
            afterCommunityRequestFormSubmission();
        }else{
            alert(messages);
        }

        return false; 
    }); 	 
    /*
    $('#submit_lead_request2').submit(function() {
        alert(2);
        // inside event callbacks 'this' is the DOM element so we first
        // wrap it in a jQuery object and then invoke ajaxSubmit
        var messages = validateForm("#submit_lead_request2 .required");
        if(messages.length == 0){
            try {
                translateFormToJSON("#submit_lead_request2");
                if (myRequestInfoJSON.email) {
                    setRequestData(myRequestInfoJSON);
                }
            } catch (e) {
                alert(e);
            }

            $(this).ajaxSubmit(options);

            // !!! Important !!!
            // always return false to prevent standard browser submit and page navigation
            //afterCommunityRequestFormSubmission();
        }else{
            alert(messages);
        }
        return false;
    });
    */

    var afterMyRequestsSubmission = function() {		
        $("#myRequestFormElements").html("<h1>Thank you for choosing SeniorLiving.Net!</h1><p>A Senior Care Advisor will be contacting you within (1) business day.  They will ask a few additional questions so that we can provide community information that is the best fit for your care needs, location and budget.  As always, our assistance will be at no cost to you and your family.  If you have any questions, please call us at 866.342.4297.</p>");
        $("#myRequestSubmit").fadeOut("fast");
    };
	 
    var afterCommunityRequestFormSubmission =  function() {
			
        $("#dialog2 #communityform").html("<h1>Thank you!</h1><h5>Your information has been saved.</h5>");
        $("#standAloneContactSubmit").fadeOut("fast");
    };
		 
    var afterCommunityFormSubmission =  function() {
		
        $("#requestItems").html("<h2 style=\"color:#38b5c1; font-size: 14pt; text-align=center;\">Thank you for choosing SeniorLiving.Net!</h2><p style=\"font-size:10pt;\">A Senior Care Advisor will be contacting you within (1) business day.  They will ask a few additional questions so that we can provide community information that is the best fit for your care needs, location and budget.  As always, our assistance will be at no cost to you and your family.  If you have any questions, please call us at <b>866.342.4297</b>.</p>");
        $("#communityRequestsFormSubmit").fadeOut("fast");
    };
	 
	  
    function translateFormToJSON(selector){
        $(selector).each(function(){

            switch($(this).attr("id"))
            {
                case "FirstName":
                    myRequestInfoJSON.firstName = $(this).val();
                    break;
                case "LastName":
                    myRequestInfoJSON.lastName = $(this).val();
                    break;
                case "Phone":
                    myRequestInfoJSON.phone = $(this).val();
                    break;
                case "Email":
                    myRequestInfoJSON.email = $(this).val();
                    break;
                case "City":
                    myRequestInfoJSON.city = $(this).val();
                    break;
                case "State":
                    myRequestInfoJSON.state = $(this).val();
                    break;
                case "ModalFirstName":
                    myRequestInfoJSON.firstName = $(this).val();
                    break;
                case "ModalLastName":
                    myRequestInfoJSON.lastName = $(this).val();
                    break;
                case "ModalPhone":
                    myRequestInfoJSON.phone = $(this).val();
                    break;
                case "ModalEmail":
                    myRequestInfoJSON.email = $(this).val();
                    break;
                case "ModalCity":
                    myRequestInfoJSON.city = $(this).val();
                    break;
                case "ModalState":
                    myRequestInfoJSON.state = $(this).val();
                    break;
                case "Budget":
                    myRequestInfoJSON.budget = $(this).val();
                    break;
                case "Howsoon":
                    myRequestInfoJSON.howsoon = $(this).val();
                    break;
                case "ResidentsName":
                    myRequestInfoJSON.resident = $(this).val();
                    break;
                case "Relationship":
                    myRequestInfoJSON.relationship = $(this).val();
                    break;
                case "ModalBudget":
                    myRequestInfoJSON.budget = $(this).val();
                    break;
                case "ModalHowsoon":
                    myRequestInfoJSON.howsoon = $(this).val();
                    break;
                case "ModalResidentsName":
                    myRequestInfoJSON.resident = $(this).val();
                    break;
                case "ModalRelationship":
                    myRequestInfoJSON.relationship = $(this).val();
                    break;
            }
        });
    }
	 
    function validateForm(selector){
        var messages = "";
        $(selector).each(function(){
            if ($(this).attr("title") == "I can afford this") {
                if ($(this + ':checked').val() == undefined) {
                    messages += "'I can afford this' must be checked. \n"
                }
            } else {
                if(is_default_or_blank($(this).val())){
                    if ($(this).attr("id") == "") {
                        messages += "The " + $(this).attr("title") + " field is required. \n";
                    } else {
                        messages += "The " + $(this).attr("id") + " is required. \n";
                    }
                }
            }
        });
        return messages;
    }
	 
    function is_default_or_blank(value){
        switch(value)
        {
            case 'City':
                return true;
                break;
            case 'City* (Location of Care)':
                return true;
                break;
            case 'City*':
                return true;
                break;
            case 'State':
                return true;
                break;
            case 'State*':
                return true;
                break;
            case 'Zip Code':
                return true;
                break;
            case 'First Name':
                return true;
                break;
            case 'First Name*':
                return true;
                break;
            case 'Last Name':
                return true;
                break;
            case 'Last Name*':
                return true;
                break;
            case 'Name':
                return true;
                break;
            case 'Email':
                return true;
                break;
            case 'Email*':
                return true;
                break;
            case 'Email Address*':
                return true;
                break;
            case 'Phone':
                return true;
                break;
            case 'Phone*':
                return true;
                break;
            case 'Phone Number*':
                return true;
                break;

            case '':
                return true;
                break;
            default:
                return false;
        }
    }

});

//pre-submit callback 
function showRequest(formData, jqForm, options) { 
    var queryString = $.param(formData); 
 
    //alert('About to submit: \n\n' + queryString); 
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
    //alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.');
    //window.location.href = window.location.href;
    setTimeout("doReload()", 5000);
} 

function doReload()
{
    window.location.reload(true);
}

function removeRequest(id,link,name){
    //alert(id);
    //var id=$("#id").attr("value");

    $.post("/remove_lead_request", {
        id: id
    },
    function(data){
        //alert("Data Loaded: " + data);
        //window.location.reload(true);

        //if (window.location.href.indexOf("#REQUESTITEMS") != -1)
        //        window.location.reload(true);
        //else
        //{
        //try {


        var x=document.getElementById("request-"+id);

        x.parentNode.removeChild(x);

        backToRequestInfo(id,link,name)
    //y.removeChild(x);
    //alert(x.getAttribute("name"));
    //x.setAttribute("name","R2");
    //alert(x.getAttribute("name"));
				
    //} catch (Exception) {}
    //alert('failed');
    //window.location = window.location.href + "#REQUESTITEMS";
    //window.location.hash="REQUESTITEMS";
    // window.location.reload(true);
    //}
    /*
		   if (!(window.location.href.indexOf("REQUESTITEMS") != -1))
	            window.location = window.location.href.replace("#", "") + "#REQUESTITEMS";		
	        
	        window.location.reload(true);
         	*/
    });
	
    return false;
}


function getY( oElement )
{
    var iReturnValue = 0;
    while( oElement != null ) {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return [curleft,curtop];
    }
}
