﻿function validateZipCode(elementValue){
    var zipCodePattern = /(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/;
    return zipCodePattern.test(elementValue);
}    
function isValidEmail(str) {
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}
function validate(jqForm) {
    if (jqForm.context.id=="staf")
        return validateSTAFForm();
    else return validateNewsletterForm();
}
function validateNewsletterForm() {
    var thisForm = document.getElementById('newsletterRegForm');
    var firstName = document.getElementById('firstname');
    var email = document.getElementById('email');
    var zip = document.getElementById('e_user1');
    var test = true;
    if ((zip.value =='')||(!validateZipCode(zip.value))) {
        $("#zip-label").addClass("req").addClass("bold");
        zip.focus();
        test = false;
    } else {
        $("#zip-label").removeClass("req").removeClass("bold");
    }
    if (!isValidEmail(email.value)) {
        $("#email-label").addClass("req").addClass("bold");
        email.focus();
        test = false;
    } else {
        $("#email-label").removeClass("req").removeClass("bold");
    }
    if (firstName.value =="") {
        $("#firstname-label").addClass("req").addClass("bold");
        firstName.focus();
        test = false;
    }  else {
        $("#firstname-label").removeClass("req").removeClass("bold");
    }   
    if (!test) $("#req-fail").show();
    else {
        $("#req-fail").hide();
        $("#newsletter").hide();
    }
    return test;
}
function validateSTAFForm() {
    var thisForm = document.getElementById('staf');
    var actor_email = document.getElementById('actor_email');
    var actor_name = document.getElementById('actor_name');
    var recipient_email = document.getElementById('recipient_email');
    var recipient_name = document.getElementById('recipient_name');
    var actor_emailFail = 'Please enter a valid email address.';
    var actor_nameFail = 'Please enter your name.';
    var recipient_emailFail = 'Please enter a valid recipient email address.';
    var recipient_nameFail = 'Please enter a recipient name.';
    var test = true;

    if (!isValidEmail(actor_email.value)) {
        $("#sender-email-label").addClass("req").addClass("bold");
        actor_email.focus();
        test = false;
    } else {
        $("#sender-email-label").removeClass("req").removeClass("bold");
    }
    if (actor_name.value =="") {
        $("#sender-name-label").addClass("req").addClass("bold");
        actor_name.focus();
        test = false;
    }else {
        $("#sender-name-label").removeClass("req").removeClass("bold");    
    }
    if (!isValidEmail(recipient_email.value)) {
        $("#recipient-email-label").addClass("req").addClass("bold");
        recipient_email.focus();
        test = false;
    } else {
        $("#recipient-email-label").removeClass("req").removeClass("bold");
    }
    if (recipient_name.value =="") {
        $("#recipient-name-label").addClass("req").addClass("bold");
        recipient_name.focus();
        test = false;
    } else {
        $("#recipient-name-label").removeClass("req").removeClass("bold");    
    }
    if (!test) $("#req-fail-staf").show();
    else {
        $("#req-fail-staf").hide();
        $("#share-tool-body-email-back").click();
    }
    return test;
}

function successCallbackFn(msg){
    if (msg=='Error! Please try again later.') {
        alert("That email address has already been registered");
        $("#email").focus();
        return false;
    }            
    if (msg.indexOf('You have successfully submitted your information.') != -1) {
        alert("You have successfully submitted your information");
        $("#newsletter").fadeOut(3000);
        return false;
    }  else {
        // this is for friggin firefox....
        alert("You have successfully submitted your information");
        $("#newsletter").fadeOut(3000);
        return false;                
    }
     //do something with the returned data
}
function errorCallbackFn(msg){
    alert("error:\n\n"+msg);
     //do something with the returned data
}

//  http://jquery.malsup.com/form/
//  prepare Options Object
var options = { 
	target:        '#return-msg',// target element(s) to be updated with server response 
	beforeSubmit:  showRequest,  // pre-submit callback 
	success:       showResponse, // post-submit callback 
	type:           'get'
	// other available options: 
	//url:       url         // override for form's 'action' attribute 
	//type:      type        // 'get' or 'post', override for form's 'method' attribute 
	//dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
	//clearForm: true        // clear all form fields after successful submit 
	//resetForm: true        // reset the form after successful submit 

	// $.ajax options can be used here too, for example: 
	//timeout:   3000 
}; 
// wait for the DOM to be loaded 
$(document).ready(function() { 
    // bind 'myForm' and provide a simple callback function
     
    //$('#newsletterRegForm').ajaxForm(options); 
    //$('#staf').ajaxForm(options); 
    
	// OR, you can bind to the form's submit event 
	//$('#newsletterRegForm').submit(function() { 
		// inside event callbacks 'this' is the DOM element so we first 
		// wrap it in a jQuery object and then invoke ajaxSubmit 
		//$(this).ajaxSubmit(options); 
		// !!! Important !!! 
		// always return false to prevent standard browser submit and page navigation 
		//return false; 
	//}); 
	
    $("#register").click(function(){
        _gaq.push(['_trackPageview', '/newsletter/registration/open']);
        $("#newsletter").show();
        return false;
    });
    $("#newsletter #close-form").click(function(){
        $("#newsletter").hide();
        _gaq.push(['_trackPageview', '/newsletter/registration/close']);
    });       

    
    var url = encodeURIComponent(document.location.href); //encodeURIComponent(window.location);
    var encTitle = encodeURI(document.title);
    var shareTool = $("#share-tool-container");
    //alert(replTitle);
    $("#share-facebook").attr("href","http://www.facebook.com/sharer.php?u="+url+"&src=sp&t="+encTitle);
    $("#share-twitter").attr("href","http://twitter.com/home?status="+window.location.href);
    $("#share-digg").attr("href","http://digg.com/submit?phase=2&url=" + url);
    $("#share-delicious").attr("href",'http://del.icio.us/post?v=2&url=' + url +'&title=' + encTitle +' ');
    $("#share-myspace").attr("href",'http://www.myspace.com/index.cfm?fuseaction=postto&t=' + encTitle + '&c=' + encTitle + '&u=' + url);
    $("#share-stumbleupon").attr("href","http://www.stumbleupon.com/submit?url="+url+"&title="+encTitle);        
    $('a[href^=http]',shareTool).click( function() {
	    window.open(this.href);
	    return false;
    });
    $("#share-email").click(function(){	        
        $("#share-tool-body-email").toggle();  
        $("#share-tool-body-email-cap").toggle();
        $("#share-tool-body-options").toggle();
        $("#share-tool-body-options-cap").toggle();
        return false;
    });
    $("#share-tool-body-email-back").click(function() {
        $("#share-tool-body-email").toggle();
        $("#share-tool-body-email-cap").toggle();
        $("#share-tool-body-options").toggle();
        $("#share-tool-body-options-cap").toggle();
        return false;
    });	   
    var url = window.location.href;
    $("#staf-url").val(url);         
    
    // tracking page views:
    /*
    $('a').click(function() {
        window._gaq = window._gaq || [];
        _gaq.push(['_trackPageView', '/path/to/virtual/url']);
    });*/
    
    //<a onclick="javascript: _gaq.push(['_trackPageview', '/easyidentifier']);" href="http://www.someurl.com/">Click Here</a> 
    
}); 

// pre-submit callback 
function showRequest(formData, jqForm, options) { 
	
	if (validate(jqForm)) {
	
	    // formData is an array; here we use $.param to convert it to a string to display it 
	    // but the form plugin does this for you automatically when it submits the data 
	    var queryString = $.param(formData)+"&fromcart=true"; 
     
	    // jqForm is a jQuery object encapsulating the form element.  To access the 
	    // DOM element for the form do this: 
	    // var formElement = jqForm[0]; 
     
	    alert('About to submit: \n\n' + queryString); 
     
	    // here we could return false to prevent the form from being submitted; 
	    // returning anything other than false will allow the form submit to continue 
	    return true; 
	} else return false;
} 
 
// post-submit callback 
function showResponse(responseText, statusText)  { 
	// for normal html responses, the first argument to the success callback 
	// is the XMLHttpRequest object's responseText property 
 
	// if the ajaxForm method was passed an Options Object with the dataType 
	// property set to 'xml' then the first argument to the success callback 
	// is the XMLHttpRequest object's responseXML property 
 
	// if the ajaxForm method was passed an Options Object with the dataType 
	// property set to 'json' then the first argument to the success callback 
	// is the json data object returned by the server 
 
	alert('status: ' + statusText );
		
	alert('responseText: \n' + responseText + 
		'\n\nThe output div should have already been updated with the responseText.');
}	
function processXml(responseXML) { 
	// 'responseXML' is the XML document returned by the server; we use 
	// jQuery to extract the content of the message node from the XML doc 
	var message = $('message', responseXML).text(); 
	alert(message); 
}

    /*
    $.get("http://lists.groundwavemailer.com/components/insert/triggers/?"+formData, function(data){
        if (data=='Error! Please try again later.') {
            alert("That email address has already been registered");
            return false;
        }        
        alert("Data Loaded: ",data);
        $("#newsletter").html("<h3>Thank you.</h3><p>Your confirmation email will arrive shortly.</p>");
        $("#newsletter").fadeOut(10000);
    });
    */
    /*
    $.get("http://lists.groundwavemailer.com/components/insert/triggers/", formData,
    function (data, textStatus) {
      // data could be xmlDoc, jsonObj, html, text, etc...
      alert(data);
      this; // the options for this ajax request
    },"text");
    return false;
    */
    
            /*
	        $.get("http://lists.groundwavemailer.com/components/insert/triggers/?"+formData, function(data){
                if (data=='Error! Please try again later.') {
                    alert("That email address has already been registered");
                    $("#email").focus();
                    return false;
                }            
                if (data.indexOf('You have successfully submitted your information.') != -1) {
                    alert("You have successfully submitted your information");
                    $("#newsletter").fadeOut(5000);
                    return false;
                }  else {
                    // this is for friggin firefox....
                    alert("You have successfully submitted your information");
                    $("#newsletter").fadeOut(5000);
                    return false;                
                }
                //$("#newsletter").insertBefore("<div id=\"\" style=\"float:left;\"><h3>Thank you.</h3><p>Your confirmation email will arrive shortly.</p></div>");                
            });	        
	        */
	        //alert('btn2 submit\n\n' + formData);
	        /*$.ajax({
                url: "http://lists.groundwavemailer.com/components/insert/triggers/?"+formData,
                type: 'GET',
                data: {},    //  <- set empty data
                success: function(data, textStatus) {
                    alert("Data Loaded: ",data);
                }
            }); */