﻿

//behaviour to log the beginning questions
var scotiaRules = {
                    "input[type=radio]":function(el){
                        el.onclick = function(){
                            logBeginningAnswers();
                        }
                    }
};

// behaviour to toggle visibility of the results contact sheet
var scotiaResult = {
                    "input#contact":function(el){
                        el.onclick = function(){
                            $$$('#contactInfo').toggle();
                            $$$('#handbookInfo').css("display",$$$('#contactInfo').css("display"));
                        };
                        
                    },
                    "input#handbook":function(el){
                        el.onclick = function(){ $$$('#handbookInfo').toggle()
                        };
                    }
};

//assign the link behaviour to the bottom HREF and SWF
var hrefBehaviourExternal =
{
    "a#contactHREF":function(el){
        if( window.obj.profile[2] ){
            //previously answered questions
            switch(window.obj.profile[2]){
                case '0': // < 50000
                    el.href = "http://locator.scotiabank.com/ScotiaExt/default.asp";
                    el.target = "_blank"
                break;
                case '1': // 50000 ~ 250000 +
                case '2':
                    el.href = "results.asp?contact=checked&username="+$F('username');
                break;
            }
        }else{
            //never answered questions
            el.onclick = function(){
                //validate the form first
               var validInvest = false;
               var validClient = false;
               $$$("//input[@name='investment']").each(function(){
                    if(this.checked){
                        validInvest = true;
                    }
                });
                if(!validInvest){

                    $$$("//label[@for='investment']").each(function(){
                        this.className += "error Red";
                        $('error').innerHTML = "Fields marked in <span class='Red error'>RED</span> with an * are mandatory";$$$('#error').show();
                    });
              
                }
                $$$("//input[@name='scotiaclient']").each(function(){
                    if(this.checked){
                        validClient= true;
                    }
                });
                if(!validClient){
                    $$$("//label[@for='scotiaclient']").each(function(){
                        this.className += "error Red";
                    });          
                }
                if(!validInvest ||  !validClient){
                    $$$("//label[@for='investment']").each(function(){
                        this.className += "error Red";
                        $('error').innerHTML = "Fields marked in <span class='Red error'>RED</span> with an * are mandatory";$$$('#error').show();
                    });
                    return false;
                }
                $$$("//input[@name='investment']").each(function(){
                    if(this.checked){
                        valid = this.value;
                    }
                });
                if(valid != '0'){
                    location.href = "results.asp?contact=checked&username="+$F('username');
                }
                else{
                    window.open("http://locator.scotiabank.com/ScotiaExt/default.asp","Scotiabank_locator");
                }                    
            }              
        }

    },
    "a#handbookHREF":function(el){
        //external customer
        if(window.obj.profile[2]){
            //previously answered questions
            switch(window.obj.profile[2]){
                case '0': //  < 50
                    el.href = "PDF/sbg_perspectives_1030.pdf";
                    el.target = "_blank"
                break;
                case '1': // >50
                case '2':
                    el.href = "results.asp?handbook=checked&username="+$F('username');
                break;
            }
        }else{
            //never answered questions
            el.onclick = function(){
                //validate the form first
               var validInvest = false;
               var validClient = false;
               $$$("//input[@name='investment']").each(function(){
                    if(this.checked){
                        validInvest = true;
                    }
                });
                if(!validInvest){

                    $$$("//label[@for='investment']").each(function(){
                        this.className += "error Red";
                        $('error').innerHTML = "Fields marked in <span class='Red error'>RED</span> with an * are mandatory";$$$('#error').show();
                    });
              
                }
                $$$("//input[@name='scotiaclient']").each(function(){
                    if(this.checked){
                        validClient= true;
                    }
                });
                if(!validClient){
                    $$$("//label[@for='scotiaclient']").each(function(){
                        this.className += "error Red";
                    });          
                }
                if(!validInvest ||  !validClient){
                    $$$("//label[@for='investment']").each(function(){
                        this.className += "error Red";
                        $('error').innerHTML = "Fields marked in <span class='Red error'>RED</span> with an * are mandatory";$$$('#error').show();
                    });
                    return false;
                }
                $$$("//input[@name='investment']").each(function(){
                    if(this.checked){
                        valid = this.value;
                    }
                });
                if(valid != '0'){
                    location.href = "results.asp?handbook=checked&username="+$F('username');
                }
                else{
                    window.open("PDF/sbg_perspectives_1030.pdf","Scotiabank_PDF");
                }                    
            }
        }
    }
}

// < 50,000$
var behaviourA =
{
    "div#handbookDL":function(el){
        $$$(el).show();
    },
    "form":function(el){
        el.onsubmit = function(){
            return;
        }
    }
};

//> 50,000$
var behaviourB =
{
    "div#handbookBTN":function(el){
        $$$(el).show();
    },
    "div#contactBTN":function(el){
        $$$(el).show();
    },
    "input#contact":function(el){
    $$$("#divPhone").show();
        el.onclick = function(){ 
            $$$('#contactInfo').toggle();
            this.checked || $('handbook').checked ? $$$('#continue_button').show() : $$$('#continue_button').hide() ;
            this.checked || $('handbook').checked ? $$$('#handbookInfo').show() : $$$('#handbookInfo').hide() ;
        };
    },
    "input#handbook":function(el){
        el.onclick = function(){
            $$$('#handbookInfo').toggle();
            this.checked || $('contact').checked ? $$$('#continue_button').show() : $$$('#continue_button').hide() ;
            this.checked || $('contact').checked ? $$$('#handbookInfo').show() : $$$('#handbookInfo').hide() ;
        };
    },
    "form":function(el){
        el.onsubmit = function(){
            $$$("//label.error").each( function(){ this.className = this.className.replace(/error/gi,"") } );
            if($('contact').checked){
                $$$("#contactInfo input.manadatory").each( function(){ this.validate();})
                $$$("//#handbookInfo//input.phonenumber").each( function(){ this.valPhone();})
                $$$("#handbookInfo input.manadatory").each( function(){ this.validate();})
            }
            if( $('handbook').checked){
                $$$("#handbookInfo input.manadatory").each( function(){ this.validate();})
                $$$("//#handbookInfo//input.phonenumber").each( function(){ this.valPhone();})          
            }
            var go = true            
            if($$$("//label.error").length){ go = false; $('error').innerHTML = "Please correct the fields marked in <span class='error'>RED</span>";$$$('#error').show(); } ;
            if(go){
                var data = "id="+window.obj.id+"&"+Form.serialize('takeAction'); 
                $$$.ajax({
                    type: "POST",
                    url: "ajaxFunctions/updateContact.asp",
                    data: data,
                    success: function(msg) {
                        $$$(".hide").each(function(){ $$$(this).hide(); })
                        if(window.obj.answers.length >= 41 ){ $$$('#incomplete').hide(); $$$('#complete').show(); }else{$$$('#incomplete').show(); $$$('#complete').hide();}
                        $$$(".col_1").hide();
                        $('handbook').checked && $('contact').checked ? $$$('#bothTHX').show() : $('handbook').checked ? $$$('#mailedTHX').show() : $$$('#contactTHX').show() ;
                    },
                    error: function(msg) { var obj = $E({tag:"div"});obj.innerHTML = "Error: "+msg.responseText ;$$$('#container').append(obj);}
                });  
            }
            
            return false;
                        
        }
    }
}

var scotiaGeneralResultsBehaviours = 
{
    "input.manadatory":function(el){
        el.validate = function(){
            if(this.type == "text"){ !this.value.length ? $$$("//label[@for='"+this.id+"']")[0].className += " error": $$$("//label[@for='"+this.id+"']")[0].className = $$$("//label[@for='"+this.id+"']")[0].className.replace(/error/gi,"")  ;}
            if(this.type == "radio"){ Form.serialize('takeAction').indexOf("timetocall") == -1 ? $$$("//label[@for='"+this.id+"']")[0].className += " error": $$$("//label[@for='"+this.id+"']")[0].className = $$$("//label[@for='"+this.id+"']")[0].className.replace(/error/gi,"")  ;}
        }
    },
    "input.postalcode":function(el){
        el.valPC = function(){
            if(this.type == "text"){ !checkPhone(this.value) ? $$$("//label[@for='"+this.id+"']")[0].className += " error red": $$$("//label[@for='"+this.id+"']")[0].className = $$$("//label[@for='"+this.id+"']")[0].className.replace(/[error|Red]/gi,"")  ;}
        }
    },
    "input.phonenumber":function(el){
        el.valPhone = function(){
            if(this.type == "text"){ !checkPhone(this.value) ? $$$("//label[@for='"+this.id+"']")[0].className += " error Red": $$$("//label[@for='"+this.id+"']")[0].className = $$$("//label[@for='"+this.id+"']")[0].className.replace(/[error|Red]/gi,"")  ;}
        }
    }
}

/*
    function to Log the answers into the DB so that
    we can build a report and resume the session
    @question: current question number
    @answer: the value of the answer
*/
function populateAnswers(Question,Answer){
    $$$.ajax({
        type: "POST",
        url: "ajaxFunctions/logQuestions.asp",
        data: "id="+window.id+"&Q="+Question+"&A="+Answer,
        error: function(msg,error) { alert("Error: Problems Communicating with server\n"+msg.responseText+"\n"+error);}
    });
}

/*
    function to login the user. Will return XML to Flash if
    the user is resuming the session. Will show an error if the user
    entered an invalid ID
    @id: user id
*/
function logIn(){
    
    $('Error_label').innerHTML = "";
    $('Error_label').style.display = "none";
    //if(ID == "") { $$$("//label[@for='username']")[0].className = "error"; return;}else{$$$("//label[@for='username']")[0].className = ""}
    var loginAJX = new Ajax.Request("ajaxFunctions/login.asp",{
        method: "POST",
        onSuccess: function(msg,json){
            json.update();
            window.id = json.id;
            Behaviour.register(hrefBehaviourExternal);
            Behaviour.apply();
           
        },
        onFailure: function(msg){
            alert("Error: "+msg.responseText);
        }
    });
}

function begin(){
    $$$('#flashCheck').slideUp('fast',function(){$$$('#title').slideDown('fast');logIn();});
    $$$('#TMLegal').slideUp('fast');
}

function logBeginningAnswers(){
    $$$.ajax({
        type: "POST",
        url: "ajaxFunctions/logBeginningQuestions.asp",
        data: Form.serialize('BeginForm'),
        error: function(msg) { alert("Error: "+msg.responseText);}
    });

}

function FirstTimeLogin(){
    $$$('#continue_button').hide();
    $$$('#contactCall').hide();
    $$$('#BeginSection').slideDown('slow',function(){         
         window.obj.profile.clear();
         Behaviour.apply();
        $('BeginForm').action = 'javascript:generateFlash()';
         $('type').value = window.obj.type;
         $$$('#contactCall').slideDown('fast');
    });
}

function callToAction(type){
    if(typeof document.getElementById(type+"HREF").onclick == "function"){
        document.getElementById(type+"HREF").onclick();
    }else{
        if(document.getElementById(type+"HREF").href.indexOf("PDF") == -1){
            location.href = document.getElementById(type+"HREF").href;
        }else{
            window.open(document.getElementById(type+"HREF").href,"Scotiabank_locator");
        }
    }
}

function resume(ID){
    $$$('div#container').hide();
    var loginAJX = new Ajax.Request("ajaxFunctions/getAnswers.asp",{
        method: "POST",
        parameters: "id="+ID,
        onSuccess: function(msg,json){
            window.id = json.id;
            window.obj = json;
            $('username').value =   window.obj.id;
            var fo = new FlashObject("flash/assessment_tool.swf", "assessment_tool_swf", "770", "650", "7", "#ffffff");
            if(window.obj.profile[2]){
                var answers = "";
                $A(window.obj.answers).each(function(item){answers += item})
                fo.addVariable("importedAnswers",answers);
            }
            fo.addParam("scale","noscale");
            fo.addParam("wmode","opaque");
            fo.addParam("swLiveConnect",true);
            fo.addParam("play",false);
            fo.write("assessment_tool");
            setTimeout("$$$('#assessment_tool').slideDown('slow')",500);
            setTimeout("$('assessment_tool_swf').Play()",1500);
            Behaviour.register(hrefBehaviourExternal);
            Behaviour.apply();                             
        },
        onFailure: function(msg){
            alert("Error: "+msg.responseText);
        }
    });    
   
}

function ResumeQuestions(){
    $$$('#continue_button').hide();
    $$$('#contactCall').hide();
    $$$('#loginSection').slideUp('fast',function(){
        $$$('#returnSection').slideDown('fast',function(){$$$('#contactCall').slideDown('fast');});
         window.obj.profile.clear();
         Behaviour.apply();
        $('BeginForm').action = 'javascript:generateFlash()';
        $('type').value = window.obj.type;
    });
}

function generateFlash(){
    var fo = new FlashObject("flash/assessment_tool.swf", "assessment_tool_swf", "770", "650", "7", "#ffffff");
    if(window.obj.profile[2]){
        var answers = "";
        $A(window.obj.answers).each(function(item){answers += item})
        fo.addVariable("importedAnswers",answers);
    }else{
        $$$("//label.error").each(function(){
            this.className = this.className.replace(/error Red/ig,"");
        });       
       var validInvest = false;
       var validClient = false;
       $$$("//input[@name='investment']").each(function(){
            if(this.checked){
                validInvest = true;
            }
        });
        if(!validInvest){

            $$$("//label[@for='investment']").each(function(){
                this.className += "error Red";
                $('error').innerHTML = "Fields marked in <span class='Red error'>RED</span> with an * are mandatory";$$$('#error').show();
            });
      
        }
        $$$("//input[@name='scotiaclient']").each(function(){
            if(this.checked){
                validClient= true;
            }
        });
        if(!validClient){
            $$$("//label[@for='scotiaclient']").each(function(){
                this.className += "error Red";
            });          
        }
        if(!validInvest ||  !validClient){
          
            $('error').innerHTML = "Fields marked in <span class='Red error'>RED</span> with an * are mandatory";$$$('#error').show();
            return;
        }
    }

    fo.addParam("scale","noscale");
    fo.addParam("wmode","opaque");
    fo.addParam("swLiveConnect",true);
    fo.addParam("play",false);
    $$$('div#container').slideUp('slow',function(){
        fo.write("assessment_tool");
        setTimeout("$$$('#assessment_tool').slideDown('slow')",500);
        setTimeout("$('assessment_tool_swf').Play()",1500);
    });
    
    return;
}

function restartAssessment(){
    window.obj.answers.clear();
    window.obj.profile.clear();
    
    $$$("#assessment_tool").slideUp('slow',function(){
        $$$("#assessment_tool_swf").remove();
        $$$('#returnSection').hide();
        $$$('#flashCheck').hide();
        $$$('#TMLegal').hide();
        $$$('#title').show();
        $$$('#contactCall').show();
        $$$('#BeginSection').show();
        $$$.ajax({
            type: "POST",
            url: "ajaxFunctions/restartQuestions.asp",
            data: Form.serialize('BeginForm'),
            error: function(msg) { alert("Error: "+msg);}
        });
        $$$('div#container').slideDown('slow');
        $('BeginForm').action = 'javascript:generateFlash()';
        
        Behaviour.register(hrefBehaviourExternal);
        Behaviour.apply();          
    })

    
    
}

function showResults(answers){
    location.href = "results.asp?username="+$F('username');
}

function getAnswers(ID){
    
    if(ID == "") {location.href = "index.asp"}
    var loginAJX = new Ajax.Request("ajaxFunctions/getAnswers.asp",{
        method: "POST",
        parameters: "id="+ID,
        onSuccess: function(msg,json){
            window.obj = json;
            $$$(".hide").each(function(){ $$$(this).hide(); });
            
                switch(window.obj.profile[2]){
                    case '0': // external < 50
                        Behaviour.register(behaviourA)
                        break;
                    case '1': // external 50 ~ 250 +
                    case '2':
                        Behaviour.register(behaviourB);
                        break;
                }
         
            Behaviour.register(scotiaGeneralResultsBehaviours);
            $('generatePDF').href += "?results="+window.obj.answers.toString().replace(/\,/gi,"")
            Behaviour.apply();
            $$$(".hide").each(function(){ this.style.visibility = "visible"; });
            if(window.obj.answers.without(0).length >= 41 ){ $$$('#incomplete').hide(); $$$('#complete').show(); }else{$$$('#incomplete').show(); $$$('#complete').hide();}
            if($('handbook').checked && typeof $('handbook').onclick == 'function'){$('handbook').onclick()}
            if($('contact').checked && typeof $('contact').onclick == 'function'){$('contact').onclick()}
        },
        onFailure: function(msg){
            alert("Error: "+msg.responseText);
        }
    });
}       

function checkIt(string)
{
    place = detect.indexOf(string) + 1;
    thestring = string;
    return place;
}   

$$$(document).ready(
    function(){
        if(typeof sIFR == "function"){
            // This is the preferred "named argument" syntax
            sIFR.replaceElement(named({sSelector:".SIFR-frutiger45light",sWmode:"opaque", sFlashSrc:"js/sIFR/frutiger45light.swf", sColor:"#FFFFFF",  sBgColor:"#ed1b2d"}));
            sIFR.replaceElement(named({sSelector:".SIFR-frutiger65BoldC", sWmode:"opaque",sFlashSrc:"js/sIFR/frutiger65BoldC.swf", sColor:"#ed1b2d",  sBgColor:"#ffffff"}));
        }
        
    }
);


function checkPhone(to_check) {
	if(to_check!=""){	
		var pattern_phone = /[^\d\s()# -]/;
		if (to_check.match(pattern_phone)) {
			return false;
		}else{
			return true;
		}
	}else{
		return false;
	}
}