/*******************************************************************************

	CSS on Sails Framework
	Title: Getting Covered
	Author: XHTMLized (http://www.xhtmlized.com/)
	Date: August 2010

*******************************************************************************/

var Site = {
	Common: {
		init: function(e) {
			$('body').addClass('js');
			$('.autoclear').click(function() {
				$(this).attr('value','');
			});
		},
		/* Label propagator */
		accessibleInputValues: function(e) {
			labeltxt = $(e).prev().html();
			if ($(e).val() == '') $(e).val(labeltxt);
			$(e)
				.focusin(function() {
					labeltxt = $(this).prev().html();
					if ($(this).val() == labeltxt) $(this).val('');
					$(this).addClass('focus');
				}).focusout(function() {
					if ($(this).val() == '') $(this).val(labeltxt).removeClass('focus');
				});
		},
		cufonInit: function(e) {
			if (typeof Cufon != 'undefined') {
				Cufon.replace('#maintabs a, #navigation a, .view-full-story, .intro, .page-info #content h1, .go-to-quiz, .page-info .left h3, .page-info .right h3 strong, .nav li a, .prescription-section .title, .prescription-section p.title, #share-your-story h2, #feature .left h2, #feature .right a, #employer-nav h2 span, #employer-nav li, #employer-answers .left h2, #employer-pledge .left h2, #pledge-header, #pledge-text h2, #pledge-text h3, #pledge-footer h2, #pledge-footer h3, #pledge-thanks h3, #pledge-sidebar h2, #pledge-sidebar h3, #toolkit-header h2, #toolkit-header h3, #toolkit-popup h2, #toolkit-popup h3', { fontFamily: 'impact', hover: true });
				Cufon.replace('.footnote, .page-info .left h2', { fontFamily: 'Dakota' });
				Cufon.replace('.tip, .tip-quiz', { fontFamily: 'default' });
				Cufon.replace('.tip-header', { fontFamily: 'impact' });
				Cufon.replace('.prescription-section cite', { fontFamily: 'jellyka'});
			};
		},
		mailPopupInit: function(e) {
			$('a#opensendmail').click(function() {
				$("#sendmail").show();
				return false;
			});
			$('#sendmail .close').click(function() {
				$('#sendmail').hide();
				return false;
			});
		}
	}
};

function show_checkmark(n)
{
    $("#employer-informed .check").hide();
    $("#employer-informed #check" + n).show();
}

function bind_checklist_areas()
{
    $("#check_area1").hover(function(event) { show_checkmark(1); });
    $("#check_area2").hover(function(event) { show_checkmark(2); });
    $("#check_area3").hover(function(event) { show_checkmark(3); });
    $("#check_area4").hover(function(event) { show_checkmark(4); });
    $("#check_area5").hover(function(event) { show_checkmark(5); });
    $("#checklist-img").mouseleave(function(event) {
        $(".check").hide();
        $(".check.current").show();
    });
}

$(document).ready(function() {
	Site.Common.init();
	Site.Common.accessibleInputValues('#send_mail #your_email_address');
	Site.Common.accessibleInputValues('input#rx-name');
	Site.Common.accessibleInputValues('input#rx-email');
	Site.Common.accessibleInputValues('input#emailresults');
	Site.Common.accessibleInputValues('#share-your-story #First_Name');
	Site.Common.accessibleInputValues('#share-your-story #Last_Name');
	Site.Common.accessibleInputValues('#share-your-story #Email');
	Site.Common.accessibleInputValues('#share-your-story #Phone');
	Site.Common.accessibleInputValues('#share-your-story #Zip');
	Site.Common.accessibleInputValues('#share-your-story #hometown');
	Site.Common.accessibleInputValues('#share-your-story #dce_dob');
	Site.Common.accessibleInputValues('#share-your-story #BLOB0');
    Site.Common.accessibleInputValues('#employer-answers .left #First_Name');
    Site.Common.accessibleInputValues('#employer-answers .left #Organization');
    Site.Common.accessibleInputValues('#employer-answers .left #Email');
    Site.Common.accessibleInputValues('#employer-answers .left #State');
    Site.Common.accessibleInputValues('#employer-answers .left #BLOB0');
    Site.Common.accessibleInputValues('#employer-pledge .right #First_Name');
    Site.Common.accessibleInputValues('#employer-pledge .right #Last_Name');
    Site.Common.accessibleInputValues('#employer-pledge .right #Email');
    Site.Common.accessibleInputValues('#employer-pledge .right #Organization');
    Site.Common.accessibleInputValues('#employer-pledge .right #Phone');
    Site.Common.accessibleInputValues('#employer-pledge .right #City');
    Site.Common.accessibleInputValues('#employer-pledge .right #State');
    Site.Common.accessibleInputValues('#employer-pledge .right #Zip');
    Site.Common.accessibleInputValues('#employer-pledge .right #BLOB0');
    Site.Common.accessibleInputValues('#pledge-form #First_Name');
    Site.Common.accessibleInputValues('#pledge-form #Email');
    Site.Common.accessibleInputValues('#pledge-form #Zip');
    Site.Common.accessibleInputValues('#pledge-thanks #share-email #name');
    Site.Common.accessibleInputValues('#pledge-thanks #share-email #email');
    Site.Common.accessibleInputValues('#pledge-thanks #share-email #recipients');
    Site.Common.accessibleInputValues('#pledge-thanks #share-email #body');
    Site.Common.accessibleInputValues('#toolkit-popup-email');
	Site.Common.cufonInit();
	Site.Common.mailPopupInit();
    bind_checklist_areas();
    $("#share-your-story form").submit(function(event) {
        var valid = true;
        var fields = {
             "First_Name": "First Name",
             "Last_Name": "Last Name",
             "Email": "Email",
             "hometown": "Your Hometown",
             "dce_dob": "Date of Birth YYYY-MM-DD" };
        for (var field in fields) {
            if ($("#" + field).val() == fields[field]) {
                $("#" + field + "_error").show();
                valid = false;
            } else {
                $("#" + field + "_error").hide();
                // Secondary validation on email addresses
                if (field == "Email") {
                    if ($("#Email").val().indexOf("@") == -1) {
                        $("#Email_invalid").show();
                        valid = false;
                    } else {
                        $("#Email_invalid").hide();
                    }
                }
            }
        }
        return valid;
    });
    $('#feature-nav span').click(function() {
      buttonVal = this.innerHTML - 1; // get 0-index
      current = $("#posters .poster:visible")[0]
      next = $("#posters .poster")[buttonVal]
      $(current).fadeOut(function() {
          $(next).fadeIn();
      });

    });
    $("#employer-answers form").submit(function(event) {
        var valid = true;
        var fields = {
             "First_Name": "Your Name*",
             "Organization": "Company Name*",
             "Email": "Email Address*",
             "State": "Location (Your State)*" };
        for (var field in fields) {
            if ($("#" + field).val() == fields[field]) {
                $("#" + field + "_error").show();
                valid = false;
            } else {
                $("#" + field + "_error").hide();
                // Secondary validation on email addresses
                if (field == "Email") {
                    if ($("#Email").val().indexOf("@") == -1) {
                        $("#Email_invalid").show();
                        valid = false;
                    } else {
                        $("#Email_invalid").hide();
                    }
                } else if (field == "State") {
                    if ($("#State").val().length != 2) {
                        $("#State_invalid").show();
                        valid = false;
                    } else {
                        $("#State_invalid").hide();
                    }
                }
            }
        }
        return valid;
    });
    $("#employer-pledge form").submit(function(event) {
        var valid = true;
        var fields = {
             "First_Name": "First Name*",
             "Last_Name": "Last Name*",
             "Email": "Email Address*",
             "Organization": "Company*",
             "Phone": "Phone Number*",
             "City": "City*",
             "State": "State*",
             "Zip": "Zip*" };
        for (var field in fields) {
            var value = $("#" + field).val();
            if (value.length == 0 || value == fields[field]) {
                $("#" + field + "_error").show();
                valid = false;
            } else {
                $("#" + field + "_error").hide();
                // Secondary validation on email addresses
                if (field == "Email") {
                    if (value.indexOf("@") == -1) {
                        $("#Email_invalid").show();
                        valid = false;
                    } else {
                        $("#Email_invalid").hide();
                    }
                } else if (field == "State") {
                    if (value.length != 2) {
                        $("#State_invalid").show();
                        valid = false;
                    } else {
                        $("#State_invalid").hide();
                    }
                }
            }
        }
        if (valid) { 
            return sendPledgeThanks();
        } else {
            return valid;
        }
    });
    $("#pledge-form form").submit(function(event) {
        var valid = true;
        var fields = {
             "First_Name": "Name",
             "Email": "Email",
             "Zip": "Zip Code" };
        for (var field in fields) {
            var value = $("#" + field).val();
            if (value.length == 0 || value == fields[field]) {
                $("#" + field + "_error").show();
                valid = false;
            } else {
                $("#" + field + "_error").hide();
                // Secondary validation on email addresses
                if (field == "Email") {
                    if (value.indexOf("@") == -1) {
                        $("#Email_invalid").show();
                        valid = false;
                    } else {
                        $("#Email_invalid").hide();
                    }
                }
            }
        }
        return valid;
    });
});

function sendPledgeThanks()
{
    $.ajax({
        type: "POST",
        url: "/send_pledge_thanks/",
        async: false,
        data: { 
            email: $("#Email").val()
        },
        beforeSend: function(data) {
            $('#pledge-submit').hide();
            $('#pledge-spinner').show();
        },
        complete: function(data) {
            $('#pledge-submit').show();
            $('#pledge-spinner').hide();
            return true;
        }
    });
}

function showToolkitPopup()
{
    $(document).openDOMWindow({
        windowSourceID:'#toolkit-popup-wrapper',
        width: 600,
        height: 400,
        windowPadding: 0,
        borderSize: 0
    }); 
}

$("#toolkit-email-submit").click(function() {
    email_val = $("#toolkit-popup-email").val()
    if (email_val.indexOf("@") == -1) {
        alert("Please enter a valid email address.");
    } else {
        $.ajax({
            type: "POST",
            url: '/toolkit_popup_join/',
            data: { 
                email:    email_val,
                page_url: window.location.href
            },
            success: function(data) {
                alert("Thanks for joining!");
                $.closeDOMWindow();
            }
        });
    }
});

// Include CSRF token with any Ajax POST requests (via Django documentation)
$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        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;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});


