/*
this script provides a way to test to see if a script has been loaded previously, and if so, does not load it again.
it checks for the object that will be created by a script, if the object exists, the script has been loaded.
*/

function miScriptScheduler() {

    this.scriptCheck = ""; /* value of function check (eg. window.jQuery)*/
    this.scriptPath = ""; /* file path to required script */
    //var cc = this; /*cache a copy of the object for use inside jquery methods*/

    /*
    method checks value of scriptCheck, if undefined a script node is created
    with the src attribute set to scriptPath. This node is then injected into the   DOM
    */
    
    this.scheduleScript = function ()
    {
        if(!this.scriptCheck)
        {
            /* script test function not found, load script with no waiting*/
                var tempElement = document.createElement("script");
                tempElement.src = this.scriptPath;
                var bases = document.getElementsByTagName('base');
                if(bases.length && bases[0].childNodes.length) {
                   bases[0].appendChild(tempElement);
                }
                else {
                  document.getElementsByTagName('head')[0].appendChild(tempElement);
                }
            
        }
        else {
            return(0);
        }
    } /*end scheduleScript method*/
} /* end constructor*/

/*
This javascript is an object oriented version of MI's Story Tools.  Much of the
code here was developed by Lucas Myers.  It has since been slightly modified to
fit into the Reference Site, and some additions have been made.  Gabe Doliner
made it object oriented.

This script is called from and used by the story detail template only
*/

/* object constructor */
function miStoryTool() {
    /* story tool functions */
    this.toolstate = "off";
    this.toolnames = new Array();
    this.toolnames['email'] = "email this story";

    //initialize the story tool
    this.storyTool = function( tool, url ) {
        // set title of tool
        jQuery("#toolname").empty();
        jQuery("#toolname").append(this.toolnames[tool]);
        // clean up tool area
        jQuery("#tool").empty();
        jQuery("#tool").append("loading...");

        // send request for tool, display if loads ok otherwise display error
        jQuery.ajax({
            type: "GET",
            url: url,

            success: function(msg) {
                jQuery("#tool").empty();
                jQuery("#tool").append(msg);
            },
            error: function() {
                jQuery("#tool").empty();
                jQuery("#tool").append("There was a problem loading this tool.");
            }
        });

        // display the toolbox
        if ( this.toolstate == "off" ) {
            jQuery("#toolbox").fadeIn("fast");
            this.toolstate = "on";
        }
    }

    //close the tool
    this.closeTool = function() {
        // hide toolbox
        jQuery("#toolbox").fadeOut("fast");
        this.toolstate = "off";
        //jQuery("#toolbox").css("top","0px");
    }

    
    this.sendStory = function(theForm) {
        // validate form
        if ( this.validate(theForm) === true )
        {
            // clear tool and display message
            jQuery("#tool").empty();
            jQuery("#tool").append("sending...");
		
	// Initialize recaptcha variables
	var recaptcha_response = typeof(theForm.recaptcha_response_field) == 'undefined' ? '' : theForm.recaptcha_response_field.value;
	var recaptcha_challenge = typeof(theForm.recaptcha_challenge_field) == 'undefined' ? '' : theForm.recaptcha_challenge_field.value;
        
	    // send form for processing
            jQuery.ajax({
                type: "POST",
                url: theForm.action,
                data: { domain: theForm.domain.value, url_form: theForm.url_form.value, email_type: theForm.email_type.value, url_html: theForm.url_html.value, url_story: theForm.url_story.value, to_email: theForm.to_email.value, from_email: theForm.from_email.value, from_name: theForm.from_name.value, comments: theForm.comments.value, headline: theForm.headline.value, recaptcha_challenge_field: recaptcha_challenge, recaptcha_response_field: recaptcha_response },
                success: function(msg){
                    // clear tool message, display message from server
                    jQuery("#tool").empty();
                    jQuery("#tool").append(msg);
                    //jQuery("#emailForm").empty();
                    
                    // close tool after delay
                    //jQuery("#toolbox").fadeOut(3000);
                    //this.toolstate = "off";
                },
                error: function(){
                    jQuery("#tool").empty();
                    jQuery("#tool").append("There was a problem sending this story, please try again.");
                }
            });
        }

        return false;
    }

    this.mvForm = function() {
        this.adj = jQuery("#story_body").height() - 150;
        jQuery("#toolbox").css( "top", this.adj );
    }

    this.validate = function (theForm) {
        this.theForm = theForm;
        with(this.theForm)
        {
            // CHECK NAME
            if (from_name.value == "") {
                alert("Please enter your name.");
                from_name.focus();
                return false;
            }

            // Check "To" email address(es)
            if ( to_email.value == "" ) {
                alert( "Please enter a 'To' email address!" );
                to_email.focus();
                return false;
            }
            this.emailArr = to_email.value.split(',');
            if ( this.emailArr.length > 5 ) {
                alert( "Only 5 'To' email addresses are allowed!" );
                to_email.focus();
                return false;
            }
            for (var i = 0; i < this.emailArr.length; i++) {
                if ( !this.validateEmail( this.emailArr[i] ) ) {
                    alert( "'To' email address [" + this.emailArr[i] + "] is invalid" );
                    to_email.focus();
                    return false;
                }
            }

            // Check "From" email address
            if ( from_email.value == "" ) {
                alert("Please enter a 'From' email address!");
                from_email.focus();
                return false;
            }
            if ( !this.validateEmail ( from_email.value ) ) {
                alert("Please enter a valid 'From' email address!");
                from_email.focus();
                return false;
            }

            return(true);
        }  //  with(theForm)
    }  //  END  validate()

    this.trim = function(str) {
        this.str = str;
        return this.str.replace(/^\s+|\s+$/g, '');
    }

    this.validateEmail = function(valfield) {
        this.tfld = this.trim( valfield );  // value of field with whitespace trimmed off
        this.email = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
        return ( !this.email.test( this.tfld ) ) ? false : true;
    }
}
/* end object constructor */

/* instantiate the object */
mi_story_tool = new miStoryTool();
/* mailafriend.js *************************************************************
 * loads the mail-a-friend tool into the storyTool box
 * @minify true
 */
var rscriptloaded = 0;
function displayEmailForm(url) {
	if(rscriptloaded) {
		mi_story_tool.storyTool("email", url);
	} else {
		$.getScript("http://api.recaptcha.net/js/recaptcha_ajax.js", function() {
			mi_story_tool.storyTool("email", url);
			rscriptloaded = 1;
		});
	}
}
/* ^ mailafriend.js ******************************************************** */

