
$(document).ready(function() {
    $('div#shadow-layer').click(function(){ closePops(); });
    $('a[type="pdf"]').wrap('<span class="no-break" />').after('&nbsp;<img class="link-img" src="/images/icon_pdf.png" alt="" />').attr('target','_blank');
    $('a[rel="external"]').wrap('<span class="no-break" />').after('&nbsp;<img class="link-img" src="/images/icon_external.gif" alt="" />');
    $("a.share-link").attr('href', function(){
        var service = $(this).attr('href');
        // var link = "http://api.addthis.com/oexchange/0.8/forward/" + service + "/offer?url=http://www." + window.location.host + ".com";
        var link = "";
        if (service == 'twitter') {
            link = 'http://twitter.com/share?url=http://www.purplepill.com&text=Visit the Web site for NEXIUM (esomeprazole magnesium)';
        } else if (service == 'facebook') {
            link = 'http://www.facebook.com/sharer.php?u=http://www.purplepill.com';
        }            
        
        return link;
    });
	
	$("a.share-link").attr('target', '_blank');
});

function closePops(){
    $('div.popup').hide();
    $('div#shadow-layer').hide();
    var pageflash = $("#flashwrap");
    if(pageflash){
        $("#flashwrap").show();
    }
    var tempVidPlayer =  document.getElementById('vidPlayer');
    if(tempVidPlayer){
        var tempInnerHTML = tempVidPlayer.innerHTML;
        tempVidPlayer.innerHTML = '';
        tempVidPlayer.innerHTML = tempInnerHTML;
    };
};

function setTitle(vidID) {
    var vidTitle = document.getElementById('vidTitle');
    switch(vidID)
    {
        case 'video1':
            vidTitle.innerHTML = 'How <span class="nex">Nexium</span> Heals';
        break;
        case 'video2':
            vidTitle.innerHTML = 'About Acid Reflux Disease';
        break;
        case 'video3':
            vidTitle.innerHTML = 'Acid Reflux Damage and Erosive Esophagitis (EE)';
        break;
   }
}

function showVid(vidID){
    var flashvars = {
        configPath: "/swf/divPlayer/config.xml",
        callVideo: vidID
    };
    var params = {wmode: "transparent"};
	swfobject.embedSWF("/swf/divPlayer/NEX301_Div.swf", "flashcontent", "580", "280", "9.0.0", "/swf/expressInstall.swf", flashvars, params);
	
    var docHeight = $(document).height();
    var docWidth = $(document).width();
    var scrollY = $(document).scrollTop();
    
    $('div#shadow-layer').height(docHeight);
    $('div#shadow-layer').show();
    $('div#vidPlayer').css('left',(docWidth - 651)/2 + 'px').css('top', scrollY + 100 + 'px');
    setTitle(vidID);
    $('div#vidPlayer').show();
};

function showPop(popID){
    var docHeight = $(document).height();
    var docWidth = $(document).width();
    var scrollY = $(document).scrollTop();
    var popup = document.getElementById(popID);
    var popWidth = $(popup).width();
    
    var pageflash = $("#flashwrap");
    if(pageflash){
        $("#flashwrap").hide();
    };
    
    $('div#shadow-layer').height(docHeight);
    $('div#shadow-layer').show();
    $(popup).css('left',(docWidth - popWidth)/2 + 'px').css('top', scrollY + 100 + 'px');
    $(popup).show();

};
function showMail()
{   
    closePops();
    
    // Clear popup inputs
    $("#mailpop #email-form input").val("");
    
	// Show popup
    $("#mailpop #email-form").show();
    $("#mailpop #email-confirm").hide();
    showPop('mailpop');
};

function submitMail(){

    var valid = true;
 
    // Validate input
    if (!validateInput(validateName, "#senderName",
            "Your name is required.",
            "Please enter your name using letters only.")) {
          valid = false;  
    }
    if (!validateInput(validateEmail, "#senderEmail",
            "Your e-mail address is required.",
            "Please enter a valid e-mail address.")) {
          valid = false;  
    }
    if (!validateInput(validateName, "#recipientName",
            "Recipient's name is required.",
            "Please enter recipient's name using letters only.")) {
          valid = false;  
    }
    if (!validateInput(validateEmail, "#recipientEmail",
            "Recipient's e-mail address is required.",
            "Please enter a valid e-mail address.")) {
          valid = false;  
    }
    
    if (valid) {
	postSharePage();


//        var eh = new ShareEmailHandler();
//        var result = eh.sendEmail({ "senderName": $("#senderName").val(),
//                                    "senderEmail": $("#senderEmail").val(),
//                                    "recipientName": $("#recipientName").val(),
//                                    "recipientEmail": $("#recipientEmail").val(),
//                                    "pageUrl": window.location.href
//                                  });
//        if (ajaxSuccess(result)) {
            // Show confirmation
//            $("#mailpop #recptName").html($("#recipientName").val());
//            $("#mailpop #recptEmail").html($("#recipientEmail").val());
//            $("#mailpop #email-confirm").show();
//            $("#mailpop #email-form").hide();
////        } else {
//            // There was a problem
//            alert("Your request could not be completed:\n\n" + result);
//        }
   }
};

function postSharePage(){
    //disable form while the ajax is processing
    $("#mailPop #recptName").attr("disabled", "disabled");
    $("#mailPop #recptEmail").attr("disabled", "disabled");
    $("#mailPop #senderName").attr("disabled", "disabled");
    $("#mailPop #senderEmail").attr("disabled", "disabled");

    //sends post data to the ShareSite service with does validation & sends email if it passes
    //when the ajax is finish it goes to the processShare function
    $.post("/services/ShareSite.ashx", {
            "senderName": $("#senderName").val(),
	    "senderEmail": $("#senderEmail").val(),
	    "recipientName": $("#recipientName").val(),
	    "recipientEmail": $("#recipientEmail").val(),
	    "currentPage": window.location.href
        },function(data){processShare(data);});
};
function processShare(data){
    //when this function triggers, the ajax is over so we can reenable the form.
    $("#mailPop #recptName").removeAttr("disabled");
    $("#mailPop #recptEmail").removeAttr("disabled");
    $("#mailPop #senderName").removeAttr("disabled");
    $("#mailPop #senderEmail").removeAttr("disabled");

    //data returned from service is delimited by |,
    // so we split that to see which fields failed/passed validation
    var validationArray = data.split("|");
    var validationSuccess = true;

    //checked if the user email box passed validation, shows error box if it didn't
    if(validationArray[0] != "true"){
        validationSuccess = false;
        $("#shareErrorUserEmail").css({ display: "block" });    //Need .css() for IE6
    }else{
        $("#shareErrorUserEmail").css({ display: "none" });     //Need .css() for IE6
    }

    //checked if the friend email box passed validation, shows error box if it didn't
    if(validationArray[1] != "true"){
        validationSuccess = false;
        $("#shareErrorFriendEmail").css({ display: "block" });  //Need .css() for IE6
    }else{
        $("#shareErrorFriendEmail").css({ display: "none" });   //Need .css() for IE6
    }

    //checks validationSuccess boolean to see if either email boxes failed validation
    //if they did, show the global error message
    //if not, show thank you message
    if(validationSuccess){
	niEvent("Form",'Email To Friend','SendEmail','ServerResponse','Success');
    }else{
	niEvent("Form",'Email To Friend','SendEmail','ServerResponse','Fail');
    }
    $("#mailpop #recptName").html($("#recipientName").val());
    $("#mailpop #recptEmail").html($("#recipientEmail").val());
    $("#mailpop #email-confirm").show();
    $("#mailpop #email-form").hide();
};


// Validates input and sets/clears error messages
// validatorFunction: function which takes user input as a parameter and returns true/false
// inputID: ID of the html INPUT tag containing the user input
// emptyMessage: message displayed when user input is empty
// invalidMessage: message displayed when user input is invalid
function validateInput(validatorFunction, inputID, emptyMessage, invalidMessage) {
    var value = $.trim($(inputID).val());
  
    if (validatorFunction(value)) {
        $(inputID)
            .parent("li").removeClass("error")
            .find("div.errorMessage").hide();
        return true;
    } else if (value == "") {
        $(inputID)
            .parent("li").addClass("error")
            .find("div.errorMessage").html(emptyMessage).show();
        return false;
    } else {
        $(inputID)
            .parent("li").addClass("error")
            .find("div.errorMessage").html(invalidMessage).show();
        return false;
    }
}
// Returns whether the input is a valid name
function validateName(value) {
    return /^[a-zA-Z ]+$/.test(value);
}
// Returns whether the input is a valid email address
function validateEmail(value) {
    return /^[a-zA-Z\.\-_]+@([a-zA-Z\.\-_]+\.)+[a-zA-Z]{2,4}$/.test(value);
}


////////////////
// AJAX code for popups
//Used to determine success/failure from AJAX calls
var AJAX_SUCCESS = "SUCCESS";
//Returns boolean indicating whether 'result' is the AJAX success string
function ajaxSuccess(result){
    try {
        if (result.substring(0, AJAX_SUCCESS.length) == AJAX_SUCCESS){
            return true;
        } else {
            return false;
        }
    } catch (e) {
        return false;
    }
}
//Extracts the value returned from our custom AJAX calls
function extractAjaxResult(result){
    return result.substring(AJAX_SUCCESS.length);
}

// Doctor Discussion Guide functionality
function showDdg(){
    $('.slider').slider({ min: 1, max: 5, animate: true});
    resetDdg();
    setStep(0);
    $('#ddgPop a.next').click(function(){
        var step = $(this).parents('.step').attr('id').substr(8);
        var step = parseInt(step) + 1;
        setStep(step);
    });
    $('#ddgPop a.back').click(function(){
        var step =$(this).parents('.step').attr('id').substr(8);
        var step = parseInt(step) - 1;
        setStep(step);
    });
    $('#ddg-step1 #body a').click(function(){
        $(this).toggleClass('on');
    });
    $('#ddg-step2 a.chk').click(function(){
        $(this).toggleClass('on');
        $(this).siblings('.jNiceWrapper').toggleClass('active');
        if($(this).hasClass('on')){
            $(this).siblings('.slider').slider("enable");
        }else{
            $(this).siblings('.slider').slider("disable");
        };
    });
    $('#ddg-step2 a#other-chk').click(function(){
        if($(this).hasClass('on')){
            $(this).siblings('input').attr('disabled','');
        }else{
            $(this).siblings('input').attr('disabled','disabled');
        };
    });
    $('#ddg-step4 span.jNiceRadio').click(selectAllQs);
    $('#ddg-step4 span.jNiceCheckbox').click(deselectRadios);
    showPop('ddgPop');
};

function setStep(step){
    var newStep = document.getElementById('ddg-step' + step);
    $('.steps ul').removeClass().addClass('step'+step);
    $('.step').hide();
    $('.buttons').css('visibility','hidden');
    $(newStep).find('.buttons').css('visibility','visible');
    $(newStep).show();
    if(step == 4){
    	var pane = $('.scroll-pane');
	    pane.jScrollPane({verticalDragMinHeight: 33});
	    
	    // Resets the scrolled pane to the top every time it is displayed
	    var api = pane.data('jsp');
	    api.scrollToY(0);
    };
};

// In step 4, the "Select" and "Unselect All" functionality
var selectAllQs = function(){
    if($(this).hasClass('jNiceChecked') && ($(this).siblings('input').val() == 1)){
        $('#ddg-step4 span.jNiceCheckbox').addClass('jNiceChecked').siblings('input').attr('checked',true);;
    }else{
        $('#ddg-step4 span.jNiceCheckbox').removeClass('jNiceChecked').siblings('input').attr('checked',false);;
    };
};

// In step 4, deselects radio buttons when user is selecting or deselecting questions individually.
var deselectRadios = function(){
    $('#ddg-step4 span.jNiceRadio').removeClass('jNiceChecked').siblings('input').attr('checked',false);;
};

function resetDdg(){
    $("#ddgPop .step").hide();
    $("#ddgPop .steps ul").removeClass();
    
    // Unbinding click events to keep multiple handlers from piling up on single actions.
    $("#ddgPop #body a, #ddgPop a.chk").removeClass('on').unbind('click');
    $("#ddgPop .buttons a").unbind('click');
    $('#ddg-step4 .jNiceRadio').unbind('click', selectAllQs);
    $('#ddg-step4 .jNiceCheckbox').unbind('click', deselectRadios);
    
    // Clearing all inputs/selects
    $("#ddgPop input[type='text']").val('');
    $("#ddgPop #ddg-step2 .jNiceWrapper").removeClass('active');
	$('.jNiceCheckbox, .jNiceRadio').removeClass('jNiceChecked').siblings('input').attr('checked',false);
    var sel = 0;
	$('.jNiceWrapper select').each(function(){
	    $('ul', $(this).parent()).each(function(){
	        $('a:eq('+ sel +')', this).click();
	    });
	});
	
	$('.slider').slider({ disabled: true, value: 1});
};

function printDdg(){
    resetDdgPrint();
    // Symptom locations from Step 1
    var symptCount = 0;
    $('#ddg-step1 #body a.on').each(function(){
        symptCount = symptCount + 1;
        var bodyCell = "#print-body td#print-" + $(this).parent().attr('id');
        $(bodyCell).addClass('on');
    });
    if(symptCount>1){
        $('td#body-text').html('I am experiencing symptoms in these locations.');
    } else if (symptCount == 0) {
        $('td#body-text').html('Location of symptoms not indicated.');
    } else{
        $('td#body-text').html('I am experiencing symptoms in this location.');
    };
    var tempSymptoms = '';
    // Symptom info from Step 2
    $('#ddg-step2 a.chk').each(function(){
        var symptom = $(this).html().toLowerCase();
        var symID = $(this).attr('id');
        var verb;
        if(symID=='other-chk' && $('input#other-txt').val().length>0){
            symptom = $('input#other-txt').val();
        };
        if($(this).hasClass('on')){
            if(symID == 'heartburn-chk'){
                verb = 'have';
            }else if(symID=='taste-chk'){
                verb = 'experience a';
            }else{
                verb = 'experience'
            };
            var severity = $(this).siblings('.slider').slider('value');
            switch(severity){
                case 1:
                    severity = 'mild';
                    break;
                case 2:
                    severity = 'mild-to-moderate';
                    break;
                case 3:
                    severity = 'moderate';
                    break;
                case 4:
                    severity = 'moderate-to-severe';
                    break;
                case 5:
                    severity = 'severe';
                    break;
            };
            var frequency = $(this).siblings('.jNiceWrapper').find('span.jNiceSelectText').html();
            if(frequency == 1){frequency = '1 day';}
            else{ frequency = frequency + ' days';};
            
            tempSymptoms += '<li>I ' + verb + ' ' + severity + ' ' + symptom + ' ' + frequency + ' per week.</li>';
        }else{
            if(symID=='other-chk'){
            }else{
                if(symID == 'heartburn-chk'){
                    verb = 'do not have';
                }else if(symID == 'taste-chk'){
                    verb = 'am not experiencing a';
                }else{
                    verb = 'am not experiencing';
                };
                tempSymptoms += '<li>I ' + verb + ' ' + symptom + '.</li>';
            };
        };
    });
    // Addt'l info from Step 3
    // Q1
    var hbFreq = '';
    if($('select#hb-frequency').val() > 0){
        hbFreq = $('select#hb-frequency').siblings('.jNiceSelectWrapper').find('span.jNiceSelectText').html();
    }
    tempSymptoms += '<li>My heartburn occurs most often: ' + hbFreq;
    // Q2
    var tempRx = '';
    $('#meds-list li').each(function(){
        var medName = $(this).find('input').val() || '';
        if(medName.length > 0){
            var medFreq = '';
            if($(this).find('select').val()>0){
                medFreq = ' - ' + $(this).find('span.jNiceSelectText').html();
            };
            tempRx += '<li>' + medName + medFreq + '</li>';
        }
    });
    if(tempRx.length > 0){
        tempRx = '<li>I am taking the following over-the-counter and/or prescription heartburn medications:<ul>' + tempRx + '</ul></li>';
    }else{
        tempRx = '<li>I am not taking any over-the-counter and/or prescription heartburn medications.</li>'
    };
    tempSymptoms += tempRx;
    // Q3
    var otherMeds = $('input#other-meds').val();
    tempSymptoms += '<li>In addition to heartburn medication, I am taking the following over-the-counter and/or prescription medications and/or vitamin supplements: ' + otherMeds;
    // Q4
    var tests = $('#ddg-step3 li.radios span.jNiceChecked').parent().parent().find('.radio-label').html();
    switch(tests){
        case 'Yes':
            tempSymptoms += '<li>I have had a diagnostic test to evaluate my heartburn symptoms.</li>';
            break;
        case 'No':
            tempSymptoms += '<li>I have not had any diagnostic tests to evaluate my heartburn symptoms.</li>';
            break;
        default:
            tempSymptoms += '<li>I\'m not sure if I\'ve had any diagnostic tests to evaluate my heartburn symptoms.</li>';
    };
    // Q5
    var changes = ''
    $('#ddg-step3 li.checks span.jNiceChecked').each(function(){
        changes += '<li>' + $(this).parent().parent().text() + '</li>';
    });
    if(changes.length > 0){
        tempSymptoms += '<li>I am trying to relieve my heartburn symptoms by making the following lifestyle changes:<ul>' + changes + '</ul></li>';
    }else{
        tempSymptoms += '<li>I have not made any lifestyle changes to relieve my heartburn symptoms.</li>'
    };
    // Add all this to pg 1 of the printout
    tempSymptoms = '<ul>' + tempSymptoms + '</ul>';
    $('#print-symptoms').html(tempSymptoms);
    
    // Questions from step 4
    if($('#ddg-step4 .left input#questions-all').siblings('.jNiceRadio').hasClass('jNiceChecked')){
        var tempHtml = $('#ddg-step4 .jspPane ol').html();
        $('#print-questions ul').html(tempHtml);
    }else{
        var tempQuestions = '';
        $('#ddg-step4 .jspPane ol').children('li').each(function(){
            var anySelected = $(this).find('.jNiceCheckbox').hasClass('jNiceChecked');
            if(anySelected){
                var innerList = '';
                $(this).find('.jNiceChecked').each(function(){
                    var question = $(this).parent().parent().html(); 
                    innerList += '<li>' + question + '</li>';
                });
                var category = $(this).find('.category').html();
                tempQuestions += '<li>' + category + '<ul>' + innerList + '</ul></li>'
            };
        });
        $('#print-questions ul').html(tempQuestions);
    };
    
    var content = $('#ddg-print').html();
    
    //Use first of these two to troubleshoot in html
    var pwin=window.open('','print_content','width=616,scrollbars=yes');
    //var pwin=window.open('','print_content','width=100,height=100');

    pwin.document.open();
    
    //Use first of these two to troubleshoot in html
    pwin.document.write('<html><head><link rel="stylesheet" type="text/css" href="/includes/css/ddg-print.css" /></head><body onload="window.print()"><div id="print-ddg-content">'+content+'</div></body></html>');
    //pwin.document.write('<html><head><link rel="stylesheet" type="text/css" href="/includes/css/ddg-print.css" media="print" /></head><body onload="window.print()"><div id="print-ddg-content">'+content+'</div></body></html>');
    
    pwin.document.close();
    
    //Comment the following to troubleshoot in html
    //setTimeout(function(){pwin.close();},1000);
};

function resetDdgPrint(){
    $('table#print-body td').removeClass();
    $('#print-symptoms').html('');
    $('#print-questions ul').html('');
};
