var Pristiq = window.Pristiq || {};
Pristiq.Commercial = (function(){
    
    function DisplayVideo(xmlURL, videoName) {
        var flashvars = {XMLData:xmlURL,playerName:videoName};
		var params = {wmode:"opaque", quality:"high"};
        swfobject.switchOffAutoHideShow();
        swfobject.embedSWF("/assets/flash/video_player.swf", "flashcontent", "508", "308", "9.0.0", "/assets/flash/expressInstall.swf", flashvars, params);
    }
     
    function ThumbClickHandler(e) {
		if ($(this).parent().hasClass('active'))
		{
			return false;
		}
			
		$('.video-list li').removeClass('active');
		$(this).parent().addClass('active');
		DisplayVideo($(this).attr('rel'), $(this).attr('tag'));
		
		return false;
    }



    return {
        Init:function() {
			$('.video-thumb').click(ThumbClickHandler);
			$first = $('.video-thumb:first');
			if ($first)
			{
				$first.parent().addClass('active');
				DisplayVideo($first.attr('rel'), $first.attr('tag'));
			}
        }
    };
})();

Pristiq.Validation = (function(){
    var errorMessage = ['Unfortunately, the Card is not valid for prescriptions that are eligible to be reimbursed, in whole or in part, by Medicaid, Medicare, or other federal or state health care programs including any state prescription drug assistance programs and the Government Health Insurance Plan available in Puerto Rico (formerly known as "La Reforma de Salud"). But you can get free information from an educational program <a href="/register.aspx">here</a>. ',
                        'Unfortunately, the Card is not valid for Massachusetts residents whose prescriptions are covered in whole or in part by third-party insurance, or where otherwise prohibited by law. But you can get free information from an educational program <a href="/register.aspx">here</a>.',
                        'Sorry, you need to be 18 or older to qualify for this offer.'];
                        
    var errorControls = ['ctl00_ctl00_content_content_pfikfForm_firstYes','ctl00_ctl00_content_content_pfikfForm_secondYes','ctl00_ctl00_content_content_pfikfForm_ageNo'];
    var correctControls = ['ctl00_ctl00_content_content_pfikfForm_firstNo','ctl00_ctl00_content_content_pfikfForm_secondNo','ctl00_ctl00_content_content_pfikfForm_ageYes'];
    var errorMessageEmail = 'You will need to enter your e-mail address, above, in order to receive information from the <i>A New DayŽ</i> program. ';
    
    var reqControls = ['ctl00_ctl00_content_content_pfikfForm_firstNo', 'ctl00_ctl00_content_content_pfikfForm_secondNo',
        'ctl00_ctl00_content_content_pfikfForm_ageYes','ctl00_ctl00_content_content_pfikfForm_firstName',
        'ctl00_ctl00_content_content_pfikfForm_lastName','ctl00_ctl00_content_content_pfikfForm_confirmEmail',
        'ctl00_ctl00_content_content_pfikfForm_address1','ctl00_ctl00_content_content_pfikfForm_city',
        'ctl00_ctl00_content_content_pfikfForm_state','ctl00_ctl00_content_content_pfikfForm_zip',
        'request-info-form-field',
        'ctl00_ctl00_content_content_pfikfForm_confirmCheck'    
	];
    var reqMessages = ['Please specify "Do you purchase your prescription medication through Medicare, Medicaid, or a similar federal or state prescription drug program?"',
        'Please specify "Do you live in Massachusetts and/or have insurance coverage for prescriptions in Massachusetts?"',
        'Please specify "Are you 18 years or older?"','First Name','Last Name','Confirm E-mail must match','Address Line 1',
        'City','State','Zip'
    ];

    var noValidationError = true;
    
    var validateReqFields = function(){
        var reqEmptyControl = [];
        var isError = false;
        
        for(i=0;i<reqControls.length;i++){
            //check input control type
            var controlType = $('#'+reqControls[i]).attr('type');
            
            switch(controlType){
                //control type radio
                case 'radio':
                    var isRadioGroupCheck = false;
                    $('input[name=' + $('#'+reqControls[i]).attr('name') + ']').each(function(index) {
                        //alert(index + ': ' + $(this).text());
                        
                        if ($(this).is(':checked')) { 
                            isError = false;
                            isRadioGroupCheck = true;
                        }
                    });
                    
                    if(!isRadioGroupCheck){
                        reqEmptyControl[i] = "yes";
                        isError = true;
                    }                
                break;
                
                // control type text
                case 'text':
                    // first check for confirm email field
                    if( reqControls[i] == 'ctl00_ctl00_content_content_pfikfForm_confirmEmail'){
                        if($('#'+reqControls[i]).val() != $('#ctl00_ctl00_content_content_pfikfForm_email').val()){
                            reqEmptyControl[i] = "yes";
                            isError = true;
                        }else{
                            isError = false;
                        }
                    }               
                    else if ($('#'+reqControls[i]).val() == ""){
                        reqEmptyControl[i] = "yes";
                        isError = true;
                    }
                    else{
                        isError = false;
                    }
                break;
                
                //control type select
                case 'select-one':
                    if($('#'+reqControls[i]).attr("selectedIndex") == 0){
                        reqEmptyControl[i] = "yes";
                        isError = true;
                    }
                    else{
                        isError = false;
                    }
                break;
                
                //control type checkbox
                case 'checkbox':
                    if(!$('#'+reqControls[i]).is(':checked')){
                        reqEmptyControl[i] = "yes";
                        isError = true;
                    }
                    else{
                        isError = false;
                    }
                break;
            }



           // Display error summary
            if(isError){
                $('.errorSummary').show();
                
                if($('#reqError' + reqControls[i]).length == 0){
                    $('.errorSummary').append('<p id="reqError'+ reqControls[i] +'" class="errorDisplay">' + reqMessages[i] + '</p>');
                }
                
                $('input[id='+ $('#'+reqControls[i]).attr('id') +']').addClass('error');
                if(controlType == 'select-one'){
                    $('select[id='+ $('#'+reqControls[i]).attr('id') +']').addClass('error');
                }
                $('.errorSummary').attr('tabindex',-1).focus();
                noValidationError=false;
            }
            else{   
                if($('#reqError' + reqControls[i]).length > 0){
                    $('.errorSummary > #reqError' + reqControls[i]).remove();
                    $('input[id='+ $('#'+reqControls[i]).attr('id') +']').removeClass('error');
                    if(controlType == 'select-one'){
                        $('select[id='+ $('#'+reqControls[i]).attr('id') +']').removeClass('error');
                    }
                }
                if($('.errorDisplay').length < 1){
	                noValidationError = true;
	                $('.errorSummary').hide();
	            }
            }
            
        }

//        validate form email -
        if ($('.form_email').val()){
            function validateEmail(email) {
                var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                return email.match(re);
            }
            var emailField = $('.form_email');
            var emailAddress = emailField.val();
            if (validateEmail(emailAddress) == null || $('.form_email').val() == ''){
                $('.form_email').addClass('error');
                $('.errorSummary').show();


                var lastNameElem = '#reqErrorctl00_ctl00_content_content_pfikfForm_lastName';
                var firstNameElem = '#reqErrorctl00_ctl00_content_content_pfikfForm_firstName';
                var radio03 = '#reqErrorctl00_ctl00_content_content_pfikfForm_ageYes';
                var radio02 = '#reqErrorctl00_ctl00_content_content_pfikfForm_secondNo';
                var radio01 = '#reqErrorctl00_ctl00_content_content_pfikfForm_firstNo';

                var addressElem = '#reqErrorctl00_ctl00_content_content_pfikfForm_address1';
                var cityElem = '#reqErrorctl00_ctl00_content_content_pfikfForm_city';
                var stateElem = '#reqErrorctl00_ctl00_content_content_pfikfForm_state';
                var zipElem = '#reqErrorctl00_ctl00_content_content_pfikfForm_zip';
                var specialElem = '#special-form-fields';
                var confirmEmailElem = '#reqErrorctl00_ctl00_content_content_pfikfForm_confirmEmail';

                var emailSnippet = '<p class="errorDisplay" id="email-error-notification">Email</p>';

                if (!$('#email-error-notification').length) {
                    if ($(lastNameElem + ':visible').length) {
                        $(lastNameElem).after(emailSnippet);
                    }
                    else if ($(firstNameElem + ':visible').length) {
                        $(firstNameElem).after(emailSnippet);
                    }
                    else if ($(radio03 + ':visible').length) {
                        $(radio03).after(emailSnippet);
                    }
                    else if ($(radio02 + ':visible').length) {
                        $(radio03).after(emailSnippet);
                    }
                    else if ($(radio01 + ':visible').length) {
                        $(radio03).after(emailSnippet);
                    }

                    else if ($(addressElem + ':visible').length) {
                        $(addressElem).before(emailSnippet);
                    }
                    else if ($(cityElem + ':visible').length) {
                        $(cityElem).before(emailSnippet);
                    }
                    else if ($(stateElem + ':visible').length) {
                        $(stateElem).before(emailSnippet);
                    }
                    else if ($(zipElem + ':visible').length) {
                        $(zipElem).before(emailSnippet);
                    }
                    else if ($(specialElem + ':visible').length) {
                        $(specialElem).before(emailSnippet);
                    }
                    else if ($(confirmEmailElem + ':visible').length) {
                        $(confirmEmailElem).before(emailSnippet);
                    }
                    else {
                        $('.errorSummary').append(emailSnippet);
                    }
                }
                noValidationError = false;
            }
            else if (validateEmail(emailAddress).length > 0) {
                $('.form_email').removeClass('error');
				
				
				
            }
        }

        function validateOptEmailField() {
				
				
				
                if ($('#ctl00_ctl00_content_content_pfikfForm_optEmailYes').attr('checked')) {
                    //check email input is valid
                    function validateEmail(email) {
                        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                        return email.match(re);
                    }
                    var emailField = $('#ctl00_ctl00_content_content_pfikfForm_email');
                    var emailAddress = emailField.val();
                    if (validateEmail(emailAddress) == null){
                        $(emailField).addClass('error');
                        $('#ctl00_ctl00_content_content_pfikfForm_email');

                        var errorMessageEmail = 'You will need to enter your e-mail address, above, in order to receive information from the <i>A New DayŽ</i> program. ';
                        $('.errorSummary').show();
                        $('.errorSummary').focus();


                        noValidationError = false;
                        optEmail = 0;
                        return false;
                    }
                    if (validateEmail(emailAddress).length > 0) {
                        $(emailField).removeClass('error');
//                        noValidationError = true;
                        optEmail = 1;
                    }

                }
                else {
                    var optEmail = 0;
                }
//                else if ($('.optEmailNo').attr('checked')) {
                if ($('#ctl00_ctl00_content_content_pfikfForm_optEmailNo').attr('checked')) {
                    var optEmail = 1;
                }

                if (optEmail == 0) {
                    $('.questionOption').addClass('error');
                    noValidationError = false;
                }
                if (optEmail == 1){
                    $('.questionOption').removeClass('error');
                    $('.errorSummary #reqErrorrequest-info-form-field').remove();
                }
//                alert(optEmail);

                var selectOneErr = 'These fields must be selected in order to receive the PRISTIQ Savings Card';
                if (($('#ctl00_ctl00_content_content_pfikfForm_confirmCheck').attr('checked') == false) ||
                        (optEmail == 0)) {
                    if (!$('.special-form-fields').length){
                        $('.errorSummary').append('<p  class="special-form-fields">' + selectOneErr + '</p>');
                    }
                }
                if ($('#ctl00_ctl00_content_content_pfikfForm_confirmCheck').attr('checked') &&
                        (optEmail == 0)){
                    $('.special-form-fields').remove();
                    $('.errorSummary').hide();
                }
                return noValidationError;
            }
        validateOptEmailField();

        function validateRadioGroups(){
            // must check no

//            alert('validateRadioGroups()')



            var radioGroup1 = $('.radioGrp').eq(0);
            var yes1 = radioGroup1.children('input').eq(0);
            var no1 = radioGroup1.children('input').eq(1);
            if (yes1.attr('checked')){
                noRadioErr1 = false;
                no1.addClass('error');
                $('.errorSummary').show();
            }
            else if (no1.attr('checked')){
                noRadioErr1 = true;
                no1.removeClass('error');
            }

            var radioGroup2 = $('.radioGrp').eq(1);
            var yes2 = radioGroup2.children('input').eq(0);
            var no2 = radioGroup2.children('input').eq(1);
            if (yes2.attr('checked')){
                noRadioErr2 = false;
                no2.addClass('error');
                $('.errorSummary').show();
            }
            else if (no2.attr('checked')){
                noRadioErr2 = true;
                no2.removeClass('error');
            }

            var radioGroup3 = $('.radioGrp').eq(2);
            var yes3 = radioGroup3.children('input').eq(0);
            var no3 = radioGroup3.children('input').eq(1);
            if (no3.attr('checked')){
                noRadioErr3 = true;
                yes3.addClass('error');
            }
            else if (yes3.attr('checked')){
                noRadioErr3 = true;
                yes3.removeClass('error');
                $('.errorSummary').show();
            }


            if (noValidationError && noRadioErr1 && noRadioErr2 && noRadioErr3){
                noValidationError = true;
            }
            else {
                noValidationError = false;
            }



        }
        validateRadioGroups();


        $('#reqErrorrequest-info-form-field,#reqErrorctl00_ctl00_content_content_pfikfForm_confirmCheck,#reqErrorctl00_ctl00_content_content_pfikfForm_additionalCheck').remove();
    };
    
    var validateOnLoad = function(){
        for(i=0;i<errorControls.length;i++){
            if($('#'+errorControls[i]).is(':checked')){
                $('.errorSummary').show();
                var groupNum = i+1;
                
                if($('#errorgroup' + groupNum).length == 0){
                    $('.errorSummary').append('<p id="errorgroup' + groupNum +'" class="errorDisplay">' + errorMessage[i] + '</p>');
                }                   
                $('input[id='+ correctControls[i] +']').addClass('error');
                noValidationError = false;
            }
        }
    };
    
    var validationQuestionsError = function(obj) {
        var errorMsg = '';
        var isError = false;
        var groupName;
        var id;
        
        id = $(obj).attr('id');
        groupName = $(obj).attr('name');
        groupName = groupName.substr(groupName.lastIndexOf('$')+1, groupName.length-1);
        


//        if(id == 'ctl00_ctl00_content_content_pfikfForm_optEmailYes' && $(obj).is(':checked')){
//            if($('#ctl00_ctl00_content_content_pfikfForm_email').val() == ""){
//                errorMsg = errorMessageEmail;
//                isError = true;
//                $('input[id=ctl00_ctl00_content_content_pfikfForm_email]').addClass('error');
//                noValidationError = false;
//            }else{
//                $('input[id=ctl00_ctl00_content_content_pfikfForm_email]').removeClass('error');
//                noValidationError = true;
//            }
//        }else{
//            for(i=0;i<errorControls.length;i++){
//                if(id == errorControls[i]){
//                    errorMsg = errorMessage[i];
//                    isError = true;
//                    $('input[id='+ id +']').addClass('error');
//                }
//            }
//        }


        if(isError){
            $('.errorSummary').show();

            noValidationError = false;
		    if($('#error' + groupName).length == 0)
		    {
		        $('.errorSummary').append('<p id="error' + groupName +'" class="errorDisplay">' + errorMsg + '</p>');
		    }
		    $('.errorSummary').attr('tabindex',-1).focus();

		}
		
		if(!isError){
		    $('input[name=ctl00$ctl00$content$content$pfikfForm$'+ groupName +']').removeClass('error');
		    if(id == 'ctl00_ctl00_content_content_pfikfForm_optEmailNo'){$('input[id=ctl00_ctl00_content_content_pfikfForm_email]').removeClass('error');}
		    if($('#error' + groupName).length > 0)
		    {	
		        $('.errorSummary > #error' + groupName).remove();
		    }
		    if($('.errorDisplay').length < 1){
	            noValidationError = true;
	            $('.errorSummary').hide();
	        }
		}
    }
    
    return {
        Init:function() {
            validateOnLoad();
        },
        ValidateError:function(obj){
            validationQuestionsError(obj);
        },
        SubmitCheck:function(){
            
            //validate business rules
//            validationQuestionsError($('#ctl00_ctl00_content_content_pfikfForm_optEmailYes'));

            //validate require fields
            validateReqFields();
            
            validateOnLoad();
            
            function validateConfirmCheckbox(){
                var $confirmCheck = $('#ctl00_ctl00_content_content_pfikfForm_confirmCheck');
                if ($($confirmCheck).attr('checked')){
                    $confirmCheck.removeClass('error');
                }
                else {
                    $confirmCheck.addClass('error');
                }
            }
            validateConfirmCheckbox();

            function validateQuestionOption(){
                if ($('.questionOption input').eq(0).attr('checked') ||
                        $('.questionOption input').eq(1).attr('checked')) {
                    $('.questionOption').removeClass('error');
                }
                else {
                    $('.questionOption').addClass('error');
                }
            }
            validateQuestionOption();



            if(!noValidationError){
                $('.errorSummary').attr('tabindex',-1).focus();
                window.tracker.track('Save on Pristiq Error');
            }
            if(noValidationError){
                window.tracker.track('Save on Pristiq Register');
            }   
            
            return noValidationError;
        }
    };


})();

// preps tracker
Pristiq.Tracking = (function(){

    // return public methods
    return {
         Init: function () {
			window.tracker = new $.TrackIt("omniture", {
				XmlUrl: '/assets/xml/trackit.xml',
				Settings: { ShowDebugInfo: true },
				Holders: {
				    'pagename': function () {  return 'Pristiq/' + $('#trackitPageName').val() + ' - Pristiq.com'; }
				}
			});
			
			if($('#trackitPageName').length > 0 ){
				window.tracker.track($('#trackitPageName').val());
			}
			
		}
    }
})();

(function($) {
	$(function() {
        if($('#saveForm').length > 0){
            Pristiq.Validation.Init();
        }
        
        Pristiq.Tracking.Init();
    });


    Pristiq.siteUI = {
        init: function(){
            Pristiq.siteUI.assignClassBrowser();
            Pristiq.siteUI.triggerFix();
            Pristiq.siteUI.showWarningIE6();
            Pristiq.siteUI.validateEmailField();
        },
        assignClassBrowser: function(){
            if ($.browser.msie){
                $('html').addClass('ie');
                if ($.browser.version == '7.0'){
                    $('html').addClass('ie7');
                }
            }
        },
        fixSuperscriptIE: function(){
            $('.box.side-by-side h1 sup').addClass('boxh1sup');
        },
        triggerFix: function(){
            setTimeout('Pristiq.siteUI.fixSuperscriptIE()',1500);
        },
        triggerSuperscriptFix: function(){
            setTimeout('Pristiq.siteUI.fixSuperscriptIE()',2000);
        },
        showWarningIE6: function(){            
            if ($.browser.msie) {                               
                if ($.browser.version == '6.0') {
                    $('.browserWarning').show();
                }
            }
        },
        validateEmailField: function(){
            function validateEmail(email) {
                var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                return email.match(re);
            }
            var emailField = $('.form_email');
            $('.optEmailYes').click(function() {
                if ($(this).attr('checked')) {
                    $('#ctl00_ctl00_content_content_pfikfForm_email').blur(function() {
                        var emailAddress = emailField.val();
                        if (validateEmail(emailAddress) == null){
                            $('#ctl00_ctl00_content_content_pfikfForm_email').addClass('error');
                            $('.errorSummary').show();
                            noValidationError = true;
                        }
                        if (validateEmail(emailAddress).length > 0) {
                            $(emailField).removeClass('error');
                            noValidationError = false;
                        }
                    })
                }
            });
            $('.optEmailNo').click(function(){
                $('.form_email').unbind();
            });
        }
    }
    Pristiq.siteUI.init();
    return Pristiq;
})(jQuery);

$(document).ready(function(){
    if ($.browser.msie) {                               
        if ($.browser.version == '6.0') {
            $('.browserWarning').show();
        }
    }
});
    
