/**
 * POLL MODULE OBJECT
 */
var oPollModule = {
    //@var string Post data, used in ajax request
    sQPostData: null,

    /**
     * @var object JSON question data returned on page load
     * Return structure:
     * {  
     *    // Question and question id
     *    q:["It's safer for teens to drive at night because there are fewer drivers on the road.",17], 
     *    // Answers and answer ids
     *    a:[["True" ,39],["False",40]] 
     * }
     */ 
    oQData: null,

    /** 
     * @var object JSON result data returned on quesiton submit
     * Return structure:
     * {  
     *    // Answer, Learn more link text, Learn more link href
     *    txt:["It’s harder for teens to judge distance, location and speed at night. A teen’s risk of having an accident goes up between Midnight and 6 AM.","Learn more...","/teen/xxxxx"],
     *    // Percentages of answers, same order as returned questions
     *    result:[40,60], 
     *    // Id of answer that is correct, and whether user answered correctly
     *    correct:[40,0]
     * }
     */
    oRData: null,

    oWordMap:{
        Correct:["Correct, ","Correcto, "],
        Incorrect:["Incorrect, ","Incorrecto, "],
        AnswerIs:["the answer is ","la respuesta es "]
    },

    oSorryTxt:{
        es:"Lo sentimos.  Por favor intenta tomar la prueba mas tarde.",
        en:"We&#39;re sorry.  Please try the SmartPoll again later."
    },


    /**
     * Method 
     * Init set-up
     */
    init:function() {
        this.sLanguage=(!Language)?"en":Language;

        //Check for cookie used to see if any questions have been voted on
        var sCookieInit = (!$.cookie('nwQIds'))?"":$.cookie('nwQIds');
        //Create post data
        this.sQPostData = "pId="+this.getPId()+"&cId="+sCookieInit+"&lang="+this.sLanguage;
        //Ajax request to get question
        this.ajaxLogic('question');

    },

    /**
     * Method 
     * Poll submit method
     */
    vote:function() {
        //@var string Init vote value
        var sVoteValue = null;
        //Check for and assign value
        $("div.pollModule > div.answers > ul > li > input[@name='radioType']").each(function(i){
            if(this.checked) sVoteValue = this.value;
        });
        //Back up verification
        if(!sVoteValue) return;
        //Create post data, cookie, and post
        else {
            this.createPostData(sVoteValue);
            this.cookieLogic();
            this.ajaxLogic('result');
        }
    },

    /**
     * Method 
     * Build question/results
     * @param sType Type of build to act on, i.e., quesiton or result
     */
    build:function(sType) {
        if(sType=='question') {
            //Insert question
            $('div.pollModule > div.question').html(this.oQData.q[0]);

            $('<ul></ul>').appendTo('div.pollModule > div.answers');

            //Insert answers
            for(var i=0; i < this.oQData.a.length; i++) 
                $('<li><input type="radio" value="'+this.oQData.a[i][1]+'" id="radioType" name="radioType" /> <span>'+this.oQData.a[i][0]+'</span></li>').appendTo('div.pollModule > div.answers > ul');

            //Enable vote on click of answer
            $("div.pollModule > div.answers > ul > li > input").bind("click",function(){
                $($("div.pollModule > input[@type='image']")[0]).removeAttr("disabled")
                $("div.pollModule > div.answers > ul > li > input").unbind("click");
            });

            //Bind vote method to submit button
            $($("div.pollModule > input[@type='image']")[0]).bind("click",function(){oPollModule.vote()});
            $($("div.pollModule > input[@type='image']")[0]).show();
        }else{
            //Result, clear quesitons
            $('div.pollModule > div.answers').html('');
            
            //Correct or incorrect?
            for(var i = 0;i<this.oQData.a.length;i++) {
                if(this.oQData.a[i][1] == this.oRData.correct[0]) {
                    if(this.sLanguage == "es") 
                        $('div.smartPoll > div.title').html(((this.oRData.correct[1])?this.oWordMap["Correct"][1]:this.oWordMap["Incorrect"][1])+this.oWordMap["AnswerIs"][1]+this.oQData.a[i][0]);
                    else
                        $('div.smartPoll > div.title').html(((this.oRData.correct[1])?this.oWordMap["Correct"][0]:this.oWordMap["Incorrect"][0])+this.oWordMap["AnswerIs"][0]+this.oQData.a[i][0]);
                    break;
                }
            }

            //Insert answer text
            $('div.pollModule > div.question').html(this.oRData.txt[0]);

            //Remove button
            $($("div.pollModule > input[@type='image']")[0]).remove();
        }
    },

    /**
     * Method 
     * Cookie checking/setting logic
     */
    cookieLogic:function(){
        // Check for cookie, not there, set with value, expire in one week
        if(!$.cookie('nwQIds'))
            $.cookie('nwQIds',this.oQData.q[1],{expires: 7});
        // Cookie exists
        else{
            //Look for question id in exisiting cookie, if exists reinit cookie w/ question id, return
            if(eval("/^\\b("+this.oQData.q[1]+")\\b/g").test($.cookie('nwQIds'))) {
                $.cookie('nwQIds',null);
                $.cookie('nwQIds',this.oQData.q[1],{expires: 7});
                return;
            }
            // Append question id to existing comma deliminated list of question ids, set to week
            $.cookie('nwQIds',$.cookie('nwQIds') + "," + this.oQData.q[1],{expires: 7});
        }
    },

    /**
     * Method 
     * Create post data for voting
     * @param sVoteValue Value to be inserted in post data
     */
    createPostData:function(sVoteValue){ this.sQPostData = "qId="+this.oQData.q[1]+"&aId="+sVoteValue+"&pId="+this.getPId()+"&lang="+this.sLanguage; },

    /**
     * Method 
     * Return location
     */
    getPId:function(){ return location.href; },

    /**
     * Method 
     * Ajax logic for question retreival and vote 
     * @param sType Type to act upon, i.e., question retreival or vote
     */
    ajaxLogic:function(sType){
        var oSelf = this;

        $.ajax({
            type:"POST",
            url:'/service/poll/default.aspx',
            data:oPollModule.sQPostData,
            success:function(sJSON){
                //Under normal succes - a JSON object is returned, on server side error - a -1 is returned, check here for that
                if(parseInt(sJSON) < 0) {
                    $('div.pollModule > div.answers').html('');
                    $('div.pollModule > div.question').html(oSelf.oSorryTxt[oSelf.sLanguage]);
                    //Remove buttons
                    $($("div.pollModule > input[@type='image']")[0]).remove();
                }else{
                    //Success, act upon data
                    (sType=='question')?oPollModule.oQData = eval('(' + sJSON + ')'):oPollModule.oRData = eval('(' + sJSON + ')');
                    oPollModule.build(sType);
                }
            },
            //Error
            error:function(){
                $('div.pollModule > div.answers').html('');
                $('div.pollModule > div.question').html(oSelf.oSorryTxt[oSelf.sLanguage]);
                //Remove buttons
                $($("div.pollModule > input[@type='image']")[0]).remove();
            }
        })
    }
}

/**
 * COMMON VOTE COMPONENTS
 * Prototyped in Assessment and Quiz modules
 * @param string Directory of service location
 */
var oVoteComponents = function(sWhereTo) {
    //@var string Scope it
    this.sWhereTo =  sWhereTo;

    /**
     * Method 
     * AJAX post on vote
     */
    this.submitLogic = function() {
        //Object ref
        var oSelf = this;

        $.ajax({
            type:"POST",
            url:"/service/"+oSelf.sWhereTo+"/default.aspx",
            data:oSelf.createPostData(),
            success:function(sTxt){ oSelf.build(sTxt);},
            error:function(){ oSelf.buildError(); }
        })
    }

    /**
     * Method 
     * Create post data for request
     */
    this.createPostData = function(){
        var sPostData='';
        //Step through keys of QA Tally object
        for(var p in this.oQATally) sPostData+=p+'='+this.oQATally[p]+"&";
        //Clean-up
        /^(.*)\&$/g.test(sPostData);
        return RegExp.$1;
    }
}

/**
 * ASSESSEMENT MODULE
 */
var oAssessmentModule= function(){

    //@var Language type
    this.sLanguage=(!Language)?"en":Language;
    //@var Parent Object
    this.oR={};

    //@var object Stores radio values
    this.oQATally={};

    /**
     * Method 
     * Init and set-up
     */
    this.init=function(){
        //Object reference
        var oSelf=this;

        //Some set-up to get necessary result objects
        $.ajax({
            type:"GET",
            url:"/includes/assessmentCopy.inc",
            data:"",
            success:function(sJSON){ 
                var o = eval('(' + sJSON + ')');
                if(oSelf.sLanguage=='en')
                    oSelf.oR=o.en;
                else if(oSelf.sLanguage=='es')
                    oSelf.oR=o.es;
            },
            error:function(){oSelf.buildError(); }
        })

        //Make request
        $($("div.assessmentModule > input[@type='button']")[0]).bind("click",function(){oSelf.submitLogic()});

        /**
         * Set-up Question/Answer tally, loop through all radio inputs w/in LI
         * Grab first radio button, set as prop of object
         */
        $("div.assessmentModule > ul > li[input]").each(function(){ oSelf.oQATally[this.getElementsByTagName('input')[0].name.toString()] = null; });

        //Enable vote on click of all answers
        $("div.assessmentModule > ul > li > input").bind("click",function(){
            oSelf.oQATally[$(this).attr('name').toString()] = this.value;
            for (var p in oSelf.oQATally){ if(oSelf.oQATally[p]==null) return; }
            //All values accounted for - enable button
            $($("div.assessmentModule > input[@type='button']")[0]).removeAttr("disabled")
            $("div.assessmentModule > ul > li > input").unbind("click");
        });
    }

    /**
     * Method 
     * Build results
     * @param string Response text
     */
    this.build=function(sTxt){ 
        var txt = this.oR.sResultTxt.replace(/\^\=PERCENTAGE\=\^/,sTxt);
        $('div.assessmentModule').html("<div class='percent'>"+txt+"</div>");
        $('p.hideTrigger').css({display:'none'});
        $('p.displayNone').removeClass('displayNone');
    }

    /**
     * Method 
     * Build error
     */
    this.buildError =function(){ $('div.assessmentModule').html("<p><strong>"+this.oR.sErrorTxt+"</strong></p>"); }
}
//Commont components
oAssessmentModule.prototype = new oVoteComponents('goodpartner');

/**
 * QUIZ MODULE OBJECT
 */
var oQuizModule = function(){

    //@var Language type
    this.sLanguage=(!Language)?"en":Language;
    //@var Parent Object
    this.oR={};

    /**
     * @var object Tally results for each questions
     * TODO Make object on the fly - per question - like Assessment mod
     */
    this.oQATally={'Q1':null,'Q2':null,'Q3':null,'Q4':null};

    /**
     * Method 
     * Init set-up
     */
    this.init=function() {
        //Object ref
        var oSelf = this;

        //Some set-up to get necessary result objects
        $.ajax({
            type:"GET",
            url:"/includes/quizCopy.inc",
            data:"",
            success:function(sJSON){ 
                var o = eval('(' + sJSON + ')');
                if(oSelf.sLanguage=='en')
                    oSelf.oR = o.en;
                else if(oSelf.sLanguage=='es')
                    oSelf.oR = o.es;

                //Taken quiz? Check for session cookie.  If so build and return
                if($.cookie('nwSRQR') && /qb=1/.test(location.search)){ 
                    oSelf.build($.cookie('nwSRQR'));
                    //Added a hidden class to content - because of flicker before content replaced in IE
                    $("div.quizModule > div.content").removeClass('hidden');
                }
            },
            error:function(){oSelf.buildError(); }
        })


        //Taken quiz? Check for session cookie.  If so build and return
        if(($.cookie('nwSRQR') && !/qb=1/.test(location.search)) || (!$.cookie('nwSRQR') && /qb=1/.test(location.search)) || !$.cookie('nwSRQR')){

            //Else: attach vote method to input button
            $($("div.quizModule > div.content > input[@type='button']")[0]).bind("click",function(){oSelf.submitLogic()});

            //Enable vote on click of all answers
            $("div.quizModule > div.content > ul > li > input").bind("click",function(){
                oSelf.oQATally[$(this).attr('name')] = this.value;
                for (var p in oSelf.oQATally) if(oSelf.oQATally[p]==null) return;
                $($("div.quizModule > div.content > input[@type='button']")[0]).removeAttr("disabled")
                $("div.quizModule > div.content > ul > li > input").unbind("click");
            });

            //Added a hidden class to content - because of flicker before content replaced in IE
            $("div.quizModule > div.content").removeClass('hidden');
        }

    }

    /**
     * Method 
     * Build results, or error
     * @param sResultType Type of build to act on, i.e., low, avg, high risk
     */
    this.build=function(sResult) {
        var sResultType = sResult.split(" ")[0].toLowerCase();

        if(/(low)|(average)|(high)/i.test(sResultType)){

            $('div.quizModule > div.content').html("<p>"+this.oR.aResultGen[0]+"</p>");
            $('div.quizModule > div.content > p > strong').html(this.oR.oResultSpec[sResultType][0]);
            $('div.quizModule > div.content').append("<p>"+this.oR.oResultSpec[sResultType][1]+"</p>");
            $('div.quizModule > div.content').append("<p>"+this.oR.aResultGen[1]+"</p>");

            //Cookie quiz result
            $.cookie('nwSRQR', sResultType);
        }else{
            alert('eh');
            $('div.quizModule > div.content').html(this.oR.sErrorTxt);
        }
    }

    this.buildError = function(){ $('div.quizModule > div.content').html("<p><strong>"+this.oR.sErrorTxt+"</strong></p>"); }
}
oQuizModule.prototype = new oVoteComponents('quiz');


/**
 * INVITE MODAL OBJECT
 * Called on modal load into HTML page
 */
var oInvite = {

    /**
     * Method 
     * Init logic
     * @param sType Article, Parent, or Friend
     */
    init:function(sType) {

        //Global language value
        this.sLanguage=(!Language)?"en":Language;
        //@var Parent Object
        this.oR={};
        //Object ref
        var oSelf = this;



        //Set hidden value of type
        this.formatType(sType);

        //Bind logic to modal submit button 
        $($("input[@name='inviteSubmit']")[0]).bind("click",function(){

            //Error checking logic - return
            if (!oInvite.validateEmail(oSelf.oR)) return;

            //Make request for send to a friend
            $.ajax({
                url: '/sendtofriend/default.aspx',
                type: 'post',
                data: $("input:text", $('div#fauxInviteForm')).serialize()+"&"+$("input:hidden", $('div#fauxInviteForm')).serialize()+"&pId="+location.href,
                dataType:'html',
                error: function(){
                    if(sType == 'Article')
                        $('div.send'+sType+'Modal > div.content > div.target > div').html("<strong>"+oSelf.oR.sErrorArticleTxt+"</strong>");
                    else
                        $('div.invite'+sType+'Modal > div.content > div.target > div').html("<strong>"+oSelf.oR.sErrorInviteTxt+"</strong>");
                },
                success: function(sInt){
                    //Success returns a value larger than 0, anthing less is server error - act accordingly
                    if(parseInt(sInt)< 0){
                        if(sType == 'Article')
                            $('div.send'+sType+'Modal > div.content > div.target > div').html("<strong>"+oSelf.oR.sErrorArticleTxt+"</strong>");
                        else
                            $('div.invite'+sType+'Modal > div.content > div.target > div').html("<strong>"+oSelf.oR.sErrorInviteTxt+"</strong>");
                    }else{
                        if(sType == 'Article') {
                            var txt =  oSelf.oR.sSuccessArticleTxt.replace(/\^\=TYPE\=\^/,(oSelf.sLanguage=='en')?oSelf.oR.wordMap[sType][0]:oSelf.oR.wordMap[sType][1]);
                            $('div.send'+sType+'Modal > div.content > div.target > div').html("<strong>"+txt+"</strong>");
                        }else{
                            var txt =  oSelf.oR.sSuccessInviteTxt.replace(/\^\=TYPE\=\^/,(oSelf.sLanguage=='en')?oSelf.oR.wordMap[sType][0]:oSelf.oR.wordMap[sType][1]);
                            $('div.invite'+sType+'Modal > div.content > div.target > div').html("<strong>"+txt+"</strong>");
                        }
                    }
                }
            });
        });

        //Some set-up to get necessary result objects
        $.ajax({
            type:"GET",
            url:"/includes/inviteCopy.inc",
            data:"",
            success:function(sJSON){ 
                var o = eval('(' + sJSON + ')');
                if(oSelf.sLanguage=='en') {
                    oSelf.oR = o.en;
                }else if(oSelf.sLanguage=='es'){
                    oSelf.oR = o.es;
                }

                oSelf.oR.wordMap = o.wordMap;
            },
            error:function(){oSelf.buildError(sType); }
        });
    },

    /**
     * Method
     * Valideate emails/empty fields
     */
    validateEmail:function(oErrs) {
        var regExEmail = /^[\w\.\-]+\@([\w+\-]+\.)+[a-z]{0,4}$/i;
        var bEmailResult    = true;
        var bNameResult     = true;

        //Check for improperly formatted emails
        $("input[@type='text']", $('div#fauxInviteForm')).each(function(i){
            if(/^\s*$/i.test(this.value)) { 
                bNameResult=false;
            }
        });

        $("input[@class^='email']", $('div#fauxInviteForm')).each(function(i){
            if(!regExEmail.test(this.value)) { 
                bEmailResult=false;
            }
        });

        if (!bNameResult) {
            $("div#fauxInviteForm > div.error").html(oErrs.sEmailErrFields);
            return false;
        }

        if (!bEmailResult) {
            $("div#fauxInviteForm > div.error").html(oErrs.sEmailErrMismatch);
            return false;
        }
        return true;
    },

    /**
     * Method
     * Custom hide method for jqModal plugin - hash object 
     * holds data needed, passed from instantiation of jq Modal on load
     */
    clear:function(hash){
        hash.w.hide();
        $("div.jqmWindow > div.content > div.target").html(" "); 
        hash.o.remove();
    },

    /**
     * Method
     * @param sType 
     * Friend modal code HTML base is the same for each parent in teen,
     * so to handle the difference, check to see where modal is being
     * launched from, i.e., parent or teen areas.  To do this, run a 
     * regex on the href, checking for top level roots and acting
     * accordingly, i.e., /parent.* or /teen.
     */
    formatType:function(sType){
        if(sType == 'Friend') 
            $("div#fauxInviteForm > input[@name='type']").attr({value: (/^http\:\/\/.*?\/parent.*/i.test(location.href)) ? '2' : '1'});
    },

    buildError:function(sType){ 
        $("div#fauxInviteForm > div.error").html("Please try again later.");
        $('div.invite'+sType+'Modal > div.content > div.target > div#fauxInviteForm > table').remove();
    }
}


/**
 * SPLASH PAGES OBJECT
 * Called on teen and parent splash pages
 */
var oSplashPage = {
    //@var object Stores anonymous object passed in on init
    oData:null,

    /**
     * Method
     * @param oData object
     * Anonymous object with necessary info to act accordingly,
     * i.e., teen or parent.
     */
    init:function(oData){

        this.sLanguage=(!Language)?"en":Language;

        //Store object to object scope
        this.oData = oData;

        var sLangAppend= (this.sLanguage=="es")?"_es":"";

        $(document).ready(function(){

            //SWF object set-up
            var so = new SWFObject("/assets/flash/"+oSplashPage.oData.type+sLangAppend+".swf", "mymovie", oSplashPage.oData.w, oSplashPage.oData.h, "8", "#336699");
            so.addParam("allowScriptAccess", "sameDomain");
            so.addParam("wmode", "transparent");
            so.addParam("quality", "high");
            so.addVariable('xmlPath', oSplashPage.oData.xmlPath+oData.type+sLangAppend+'.xml');
            so.addVariable("animateLP", oSplashPage.oData.animate);
            so.write("flashReplace");

            //Check if flash is in
            if($('div#flashReplace > ul').length != 0) { 
                $('div#flashReplace').css({background:'url(/assets/images/splash-'+oSplashPage.oData.type.substring(0,oSplashPage.oData.type.length-1)+'_flash-bg.jpg) top left no-repeat'});
                $('div#flashReplace').css({visibility:'visible'});
                oSplashPage.removeAnimation();
            }else{
                $('div#flashReplace').css({visibility:'visible'});
                if(!oSplashPage.oData.animate) { oSplashPage.removeAnimation(); }
            }
        });

        return this.lpAnimationComplete;
    },

    removeAnimation:function () {
        /**
         * 'Pop' animation - no fade
         */
        $('div.inviteTabs').removeClass('wayOut');
        $('div.inviteTabs > div > div').removeClass('wayOut');
        $('div.inviteFooter').removeClass('wayOut');
        if(this.oData.type == 'parents') {
            $('div#drivingTutorials').show();
            $('div#getAQuote').show();
            $('div.inviteTabs').show();
        }
        $('ul.invitenav').show();
    },

    setAnimation:function () {
        /**
         * Fade in footer w/ tabs
         */
        $('div.inviteTabs').fadeIn('slow');
        $('div.inviteTabs').removeClass('wayOut');
        $('div.inviteTabs > div > div').removeClass('wayOut');
        $('div.inviteTabs > div > div').fadeIn('slow');
        $('div.inviteFooter').fadeIn('slow');
        $('div.inviteFooter').removeClass('wayOut');
        $('ul.invitenav').fadeIn('slow');
        
        if(this.oData.type == 'parents') {
            $('div#drivingTutorials').fadeIn('slow');
            if($.browser.msie) { $('form#state > select').addClass('hidden'); }
            $('div#getAQuote').fadeIn('slow',function(){$('form#state > select').removeClass('hidden')});
            $('div.inviteFooter > div.footerTabs').fadeIn('slow');
        }
    },

    lpAnimationComplete:function() { 
        var oAgent=navigator.userAgent.toLowerCase(); 
        ((oAgent.indexOf("mac") > -1)||oAgent.indexOf("msie 6.") > -1) ? oSplashPage.removeAnimation(): oSplashPage.setAnimation();
    }
}

/**
 * TRACK OBJECT
 */
var track = {
    autoWidget:function(sStVal){
        $.ajax({
            url: '/autoquote/track.aspx',
            type: 'post',
            data: "pId="+location.href+"&state="+sStVal,
            dataType:'html',
            error: function(){},
            success: function(){}
        });
    },

    findAgent:function(sURL){
        $.ajax({
            url: '/findagent/track.aspx',
            type: 'post',
            data: "pId="+location.href,
            dataType:'html',
            error: function(){location.href=sURL;},
            success: function(){location.href=sURL;}
        });
    },

    listDMV:function(sStVal){
        $.ajax({
            url: '/teen/licensing/track.aspx',
            type: 'post',
            data: "state="+sStVal,
            dataType:'html',
            error: function(){},
            success: function(){}
        });
    }
}

/**
 * BASE LINE OBJECT
 */
var oBaseLineIt = {
    /**
     * Method 
     * Init set-up :: Look for article, take action, base line 
     * handled by class relative to article title
     */
    init:function() {
        if($('h2.article_title'))
            $('h2.article_title').html("<span class='bl'>"+$('h2.article_title').html()+"</span>");
    }
}


/**
 * ACCORDIAN MODULE
 */
var oAccordian = function(){
    //@var object Open object ref
    this.oOpen=null;
    //@var boolean  XXX Used? XXX
    this.bOpen=null;
    //@var object Current element object ref
    this.oCurrEl=null;
    //@var string
    this.sParentEl=null;
    //@var object
    this.oTip=null;
    //@var object
    this.oTitles=new Object();
    //@var object
    this.oItoS={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten'};
    
    /**
     * Method 
     * Init set-up 
     * @param sEl: Where to start from, JQuery formatted string, i.e., 'div.<BLAH>' 
     * @param o: Reference to self
     * @param bTip: Include tips?
     */
    this.init=function(sEl,o,bTip) {
        //Check
        if(!$('div.sEl')) return;

        //Set - see definitions above
        this.sParentEl = sEl;
        
        //Tips?
        if(bTip) { 
            //Instantiate new tip
            this.oTip = new oToolTip();
            oTip = this.oTip;
            
            //Bind methods
            $(sEl+'> div.accordian > div.content > ul > li > a').each(function(i){
                //No title no tip
                if(!$(this).attr('title')) return;
                //Store title in object
                o.oTitles[i] = $(this).attr('title');
                $(this).bind("mouseover",function(e){ 
                    //See tip object for description
                    oTip.show(e,o,i); 
                });
                $(this).bind("mouseout",function(e){oTip.hide(e,o,i);});
                $(this).removeAttr('title');
            });
        }
        /**
         * Do we have an expanded by default?
         * If so - set all appropriate references
         */
        $(sEl+'> div.accordian >div.content').each(function(){
            if(/\bexpanded\b/i.test(this.className)){
                var sClassName = this.className.split(' ')[0];
                o.oCurrEl=this.parentNode;
                o.oOpen = $(o.sParentEl+'> div.accordian > div.'+sClassName);
                $(o.oCurrEl).addClass('down');
                o.sCNStored = sClassName;
            }
        });
        
        //Bind toggle action to span titles, passing the parent node as reference
        for(var i=1;i<10;i++) {
            var sI = this.oItoS[i];
            if(!$(sEl+'> div.'+sI)[0]) return;
            $(sEl+'> div.'+sI+'>span').bind("click",function(){o.toggle(this.parentNode);});
        }
    }

    /**
     * Method 
     * Toggle magic
     * @param object Element reference of title parent node
     */
    this.toggle=function(oEl) {
        var sClassName = oEl.className.split(' ')[0] + "Content";

        //Clicking open?  Return
        if(sClassName == this.sCNStored) return;

        //If reference to object open - close
        if(this.oOpen) {
            $(this.oCurrEl).removeClass('down');
            this.oOpen.slideUp('fast');
        }

        //Set references - open and such
        this.oCurrEl = oEl;
        this.oOpen = $(this.sParentEl+'> div.accordian > div.'+sClassName);
        this.oOpen.slideDown('fast');
        $(oEl).addClass('down');
        this.sCNStored = sClassName;
    }
}

/**
 * TOOL TIPS 
 */
var oToolTip = function(){
    //Create tool tip on instantiation
    this.oTip = $("<div class='tooltip'></div>").appendTo('body');;

    /**
     * Method:Show tip logic
     * @param e Event
     * @param o Reference to object which tip was instantiated in
     * @param i Integer value for reference to tool tip text in oTitles object
     */
    this.show= function(e,o,i){
        //Get mouse position
        var oPos = this.mousePos(e);
        //Set accordingly
        this.oTip.css({top:oPos.y-10,left:oPos.x+10});
        //Set text
        this.oTip.html(o.oTitles[i]);
        //Turn on
        this.oTip.show();
    }

    /**
     * Method: Hide tip
     */
    this.hide= function(o,i){ this.oTip.hide(); }

    /**
     * Method: Get mouse position from event 
     * QuirksMode quickie 
     */
    this.mousePos = function (e) {
        var oPos = new Object();
        oPos.x = 0;
        oPos.y = 0;

        if (!e) var e = window.event;
        if (e.pageX || e.pageY) {
            oPos.x = e.pageX;
            oPos.y = e.pageY;
        }else if (e.clientX || e.clientY){
            oPos.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            oPos.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
        return oPos;
    }
}

/* Search form scripts
----------------------

Basic validation to make sure a field is not empty */
function validateForm(whichform) {
    for (var i=0; i<whichform.elements.length; i++){
        var element = whichform.elements[i];
        /* checks to for a class="required" */
        if (element.className.indexOf("required") != -1) {
            if (!isFilled(element)) {
                alert("Please enter a search term.");
                return false; 
            }
        }
    }
}

/* check field length */
function isFilled(field){
    if (field.value.length < 1 || field.value == field.defaultValue) {
        return false;
    }else {
        return true;
    }
}

/* change button img on text entry */
function btnImg() {
    var button = document.getElementById("btnSearchButton");
    button.setAttribute("src","/assets/images/search_btn.gif");
}


/* Init some magic */
$(document).ready(function(){ 
    $('div.inviteFriendModal').jqm({ ajax:'@href', onHide: oInvite.clear, onLoad:function(){oInvite.init('Friend')},  modal:1, overlay:75, closeClass:'jqmCloseIt', trigger:'a.invFriendOpen', target:'.target' }); 
    $('div.inviteParentModal').jqm({ ajax:'@href', onHide: oInvite.clear, onLoad:function(){oInvite.init('Parent')},  modal:1, overlay:75, closeClass:'jqmCloseIt', trigger:'a.invParentOpen', target:'.target' }); 
    $('div.inviteTeenModal').jqm({ ajax:'@href', onHide: oInvite.clear, onLoad:function(){oInvite.init('Teen')},  modal:1, overlay:75, closeClass:'jqmCloseIt', trigger:'a.invTeenOpen', target:'.target' }); 
    $('div.sendArticleModal').jqm({ ajax:'@href', onHide: oInvite.clear, onLoad:function(){oInvite.init('Article')},  modal:1, overlay:75, closeClass:'jqmCloseIt', trigger:'a.sendArticleOpen', target:'.target' }); 

    var oAccordianOne = new oAccordian();
    oAccordianOne.init('div.accordianMenu',oAccordianOne,true);
});

window.onunload=function(){lpAnimationComplete = null;}

