/** MYAR-905 functions needed for registration forms **/
function checkProfession(profession) {
    $('.spinner').hide();
    if (profession == null || profession == "") {
        // MYAR-1156 - reg. form usability update - show practice phone initially, when there is no profession
        $('#practice_details').hide();
        $('#school_fieldset').hide();
    } else if ((profession.indexOf('Student') > -1 || profession.indexOf('Faculty') > -1)) {
        $('#practice_fieldset').hide();
        $('#practice_details').hide();
        $('#school_fieldset').show();
        // MYAR-1156 - reg. form usability update
        // only show practice address fields: if phone# is entered, if not; hide all fields so phone# is the only field required
        if ($('#schoolName').val().length > 0) {$('#school_details').show();} else {$('#school_details').hide();}
        // MYAR-1156 - reg. form usability update - don't reset phone field
        //$('#practicePhone').val('');
        clearPracticeInfo();
        $('#student').val('true');
        $('label[for="email"]').html($('label[for="email"]').html().replace("Personal ",""));
        $('label[for="email"]').html($('label[for="email"]').html().replace("Email","Personal Email"));
        // facutly hide graduationDate; student show
        if (profession.indexOf('Faculty') > -1) {$('div.graduationDate').hide();} else {$('div.graduationDate').show();}
    } else { // else practice info is needed
        $('#school_fieldset').hide();
        $('#school_details').hide();
        $('#practice_fieldset').show();
        // MYAR-1156 - reg. form usability update
        // only show practice address fields: if phone# is entered, if not; hide all fields so phone# is the only field required
        if ($('#practicePhone').val().length > 0) {$('#practice_details').show();} else {$('#practice_details').hide();}
        // MYAR-1156 - reg. form usability update - don't reset schoolName
        //$('#schoolName').val('');
        clearSchoolInfo();
        $('#student').val('false');
        $('label[for="email"]').html($('label[for="email"]').html().replace("Personal Email","Email"));
    }
}

function clearPracticeInfo() {
	//$('#practicePhone').val('');
    $('.ro').unbind('focus');
    // MYAR-1156 - reg. form usability update - don't reset for validation errors
    if (formHasErrors == true) {return; /* no clear */}
    $('#practiceName').val('').removeClass('ro').removeAttr('readonly');
    $('#practiceAddress\\.street1').val('').removeClass('ro').removeAttr('readonly');
    $('#practiceAddress\\.street2').val('').removeClass('ro').removeAttr('readonly');
    $('#practiceAddress\\.city').val('').removeClass('ro').removeAttr('readonly');
    $('#practiceAddress\\.region').val('').removeClass('ro').removeAttr('readonly');
    $('#practiceAddress\\.postalCode').val('').removeClass('ro').removeAttr('readonly');
}

function clearSchoolInfo() {
	//$('#schoolName').val('');
    $('.ro').unbind('focus');
    // MYAR-1156 - reg. form usability update - don't reset for validation errors
    if (formHasErrors == true) {return; /* no clear */}
    $('#schoolAddress\\.street1').val('').removeClass('ro').removeAttr('readonly');
    $('#schoolAddress\\.street2').val('').removeClass('ro').removeAttr('readonly');
    $('#schoolAddress\\.city').val('').removeClass('ro').removeAttr('readonly');
    $('#schoolAddress\\.region').val('').removeClass('ro').removeAttr('readonly');
    $('#schoolAddress\\.postalCode').val('').removeClass('ro').removeAttr('readonly');
}

function foundOrganization(data) {
    handleFoundOrganization(data, true, 0);
}
function foundSchool(data) {
    handleFoundOrganization(data, false, 0);
}
function handleFoundOrganization(data, isOrganization, level) {
    if (data != null) {
        //http://willcode4beer.com/tips.jsp?set=jsonInvalidLabel
        var obj = eval('(' + data + ')');
        if (obj != null && obj.organization != null) {
            if (isOrganization) {
                $('#practiceName').val(obj.organization.name).addClass('ro').attr('readonly', true);
                $('#practiceAddress\\.street1').val(obj.organization.street1).addClass('ro').attr('readonly', true);
                $('#practiceAddress\\.street2').val(obj.organization.street2).addClass('ro').attr('readonly', true);
                $('#practiceAddress\\.city').val(obj.organization.city).addClass('ro').attr('readonly', true);
                $('#practiceAddress\\.region').val(obj.organization.region).addClass('ro').attr('readonly', true);
                $('#practiceAddress\\.postalCode').val(obj.organization.postalCode).addClass('ro').attr('readonly', true);
                // if street1 is missing, enable all fields so address can be edited
                if ($('#practiceAddress\\.street1').val()==""){
                    $('#practice_details input, #practice_details select').each(function(){
                        $(this).removeClass('ro').removeAttr('readonly');
                    });
                }
                // set same values in student address fields
                if (level==0) handleFoundOrganization(data, false, 1);
            } else if (!isOrganization) {
                $('#schoolAddress\\.street1').val(obj.organization.street1)/*.addClass('ro').attr('readonly', true)*/;
                $('#schoolAddress\\.street2').val(obj.organization.street2)/*.addClass('ro').attr('readonly', true)*/;
                $('#schoolAddress\\.city').val(obj.organization.city)/*.addClass('ro').attr('readonly', true)*/;
                $('#schoolAddress\\.region').val(obj.organization.region)/*.addClass('ro').attr('readonly', true)*/;
                $('#schoolAddress\\.postalCode').val(obj.organization.postalCode)/*.addClass('ro').attr('readonly', true)*/;
                // if street1 is missing, enable all fields so address can be edited
                if ($('#schoolAddress\\.street1').val()==""){
                    $('#school_details input, #school_details select').each(function(){
                        $(this).removeClass('ro').removeAttr('readonly');
                    });
                }
                // set same values in student address fields
                if (level==0) handleFoundOrganization(data, true, 1);
            }
            //if the practice was found, the fields are marked READ-ONLY
            $('.ro').focus(function(){$(this).blur()});
        } else {
        	if (isOrganization) {clearPracticeInfo();}
            if (!isOrganization) {clearSchoolInfo();}
        }
    } else {
        if (isOrganization && !formHasErrors) {clearPracticeInfo();}
        if (!isOrganization && !formHasErrors) {clearSchoolInfo();}
        $('.ro').removeAttr('readonly');
    }
    if (isOrganization) {$('#practice_details').show();}
    if (!isOrganization) {$('#school_details').show();}
    $('.spinner').hide();
}

function checkPhone(phone) {
    if (phone == null) {
        phone = $('#practicePhone').val();
    } else {
        phone = $(phone.target).val();
    }
    var result = validatePhone(phone);
    if (result) {
        //find the organization with the given phone number
        $('.spinner', $('#practicePhone').parent()).show();
        $.get('/api/organization/find.html', {phone: phone}, foundOrganization);
    } else {
        $('#practice_details').hide();
    }   
}

function checkSchoolName(name) {
    if (name == null) {
        name = $('#schoolName').val();
    } else {
        name = $(name.target).val();
    }
    if (name != null && name.trim() != '') {
        $('.spinner', $('#schoolName').parent()).show();
        $.get('/api/organization/find.html', {name: name}, foundSchool);
    } else {
        $('#school_details').hide();
    }
}
/** END functions needed for registration forms **/

function closePopup() {
    jQuery.unblockUI();
}

$(function() {
    $('form#register_form').submit(function(){
        if ($('#practice_details:visible').length != 0) {
            // copy practice info to student form
            $('#schoolAddress\\.street1').val($('#practiceAddress\\.street1').val());
            $('#schoolAddress\\.street2').val($('#practiceAddress\\.street2').val());
            $('#schoolAddress\\.city').val($('#practiceAddress\\.city').val());
            $('#schoolAddress\\.region').val($('#practiceAddress\\.region').val());
            $('#schoolAddress\\.postalCode').val($('#practiceAddress\\.postalCode').val());

        } else if ($('#school_details:visible').length != 0) {
            // copy school info to practice form
            $('#practiceAddress\\.street1').val($('#schoolAddress\\.street2').val());
            $('#practiceAddress\\.street2').val(obj.organization.street2).addClass('ro').attr('readonly', true);
            $('#practiceAddress\\.city').val($('#schoolAddress\\.city').val());
            $('#practiceAddress\\.region').val($('#schoolAddress\\.region').val());
            $('#practiceAddress\\.postalCode').val($('#schoolAddress\\.postalCode').val());
        }
    });

    // if a link has a <sup></sup> element remove it. It does not look fine in all browsers when underlined.
    $('a').each(function(){
        if ($(this).css('text-decoration') == 'underline' && $(this).html().indexOf('<sup>') >= 0) {
            var thisHtml = $(this).html();
            thisHtml = thisHtml.replace("<sup>", "<span>").replace("</sup>", "</span>");
            $(this).html(thisHtml);
        }
    });

    $("a.popup").click(function() {
        //winpops=window.open($(this).attr('href'),'MyArestin','width=780,height=400,status=0,scrollbars=1,resizable=0');
        //return false;
        });

    //make all external links open in a new window (page 57)
    $("a[href^=http]").attr("target","_blank");

    //make all links to PDFs open a new window (p23 and 57)
    $("a[href*=.pdf]").addClass('pdf').attr("target","_blank");
    $("a[href*=.PDF]").addClass('pdf').attr("target","_blank");
    $("a[href*=.doc]").addClass('doc').attr("target","_blank");
    $("a[href*=.DOC]").addClass('doc').attr("target","_blank");
      
    //make all links to PDFs and DOCs call Google Analytics (also requires 4 lines of code above, which open new window, to function properly)
    $("a[href*=.pdf]").attr("onclick","pageTracker._trackPageview($(this).attr('href'));");
    $("a[href*=.PDF]").attr("onclick","pageTracker._trackPageview($(this).attr('href'));");
    $("a[href*=.doc]").attr("onclick","pageTracker._trackPageview($(this).attr('href'));");
    $("a[href*=.DOC]").attr("onclick","pageTracker._trackPageview($(this).attr('href'));");

    // MYAR-1291
    // secure assets will goto /login page for anonymous
    if (!is_logged_in) {
        // remove all targets, rel, click events
        $("a[href*='/assets/secure/']").each(function(){
            $(this).removeAttr("target");
            $(this).removeAttr("rel");
            $(this).removeAttr("onclick");
            $(this).unbind("click");
        });
        $("a[href*='login.html?target_path=']").each(function(){
            $(this).removeAttr("target");
            $(this).removeAttr("rel");
            $(this).removeAttr("onclick");
            $(this).unbind("click");
        });
    }

    //Exit Disclaimer
    $("a[href^=http]").click(function() {
        var href=$(this).attr("href");
        if (href != null && href.indexOf('myarestin') == -1 && href.indexOf('arestin') == -1 && href.indexOf('rackspacecloud.com') == -1 && href.indexOf('mosso.com') == -1) {
            jQuery.blockUI({
                message: "<div class=\"exitPopup\"><p class=\"exitThankyou\">Thank you for visiting MyArestin.com</p><p class=\"exitImg\"><img src='/images/v3/info16_1.gif'><span class=\"exitSpan\">By clicking 'Continue', you will be taken to:</span></p><p class=\"exitSpan\"><b>" + href + "</b></p><p class=\"exitTxt\">This is a Web site to which our Privacy Policy does not apply. You are solely responsible for your interactions with such Web sites.</p><p class=\"exitRight\"><a href=\"" + href + "\" target=\"_blank\" onclick=\"closePopup();\"><img src='/images/v3/exit_btn_continue.png'></a> &nbsp; &nbsp;<a href=\"javascript:closePopup();\"><img src='/images/v3/exit_btn_cancel.png'></a></p></div>",
              
                css: {
                    width:          '400px',
                    padding:        '0px',
                    margin:         0,
                    color:          '#333',
                    textAlign:      'left',
                    border:         '1px solid #999',
                    backgroundColor:'#F2F2F2',
                    cursor:         'wait',
                    left:			'40%'
                },
              
                // styles for the overlay
                overlayCSS:  {
                    backgroundColor:'#F2F2F2',
                    opacity:        '0.1',
                    width:			'400px'
                }
            });
            return false;
        }
    });
    
    //MYAR-1159
    $('a.share-dis-link').hover(function() {
        $('.share-on').show();
      }, function() {
        $('.share-on').hide();
    });

    /** generic popup using blockui */
    jQuery(".popup-message-trigger-confirm,.popup-message-trigger-alert").click(function() {
        var classList = $(this).attr("class");
        if(((typeof onBeforePopup == 'function') ? onBeforePopup(classList) : true)) {
            var mesgHtml = $(".popup-message-html", $(this).parents(".popup-message-container")).html();
            var closeBtnBar = mesgHtml.indexOf("popup-buttonbar") < 0 ? classList.indexOf("trigger-confirm")>=0
                ? classList.indexOf("popup-btn-reverse")>=0
                  ? "<p style=\"padding-left:30px;\" class=\"popup-buttonbar\"><a href=\"#\" onclick=\"closePopupMessage('"+classList+"',1);return false;\"><img src=\"/images/v2/btn_okay_light.jpg\" /></a> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href=\"#\" onclick=\"closePopupMessage('"+classList+"',0);return false;\"><img src=\"/images/v2/btn_cancel_dark.jpg\" /></a></p>"
                  : "<p style=\"padding-left:30px;\" class=\"popup-buttonbar\"><a href=\"#\" onclick=\"closePopupMessage('"+classList+"',1);return false;\"><img src=\"/images/v2/btn_okay.jpg\" /></a> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href=\"#\" onclick=\"closePopupMessage('"+classList+"',0);return false;\"><img src=\"/images/v2/btn_cancel.jpg\" /></a></p>"
                : "<p style=\"padding-left:30px;\" class=\"popup-buttonbar\"><a href=\"#\" onclick=\"closePopupMessage('"+classList+"',0);return false;\"><img src=\"/images/v2/btn_close_window.jpg\" /></a>"
                : "";
            jQuery.blockUI({ 
                message: "<div class=\"close_popup_x\"><a href=\"#\" onclick=\"closePopupMessage('"+classList+"',0);return false;\">X</a></div><div class=\"popupMessage\"><div class=\"popupHtml\">"+mesgHtml+"</div>"+closeBtnBar+"</div>",

                css: {  
                  width:          '545px', 
                  //height:         '270px',
                  padding:        '10px', 
                  margin:         'auto',
                  color:          '#333', 
                  textAlign:      'left', 
                  border:         '1px solid #999', 
                  backgroundColor:'#F2F2F2',
                  cursor:         'wait',
                  left:           '30%'
                }, 

                // styles for the overlay 
                overlayCSS:  {  
                    backgroundColor:'#FFF',
                    opacity:        '0.1'
                }
            });
        }
        return false;
    });
    /** generic popup using blockui */

});

/** generic popup using blockui */
function closePopupMessage(classList, retVal) {
    jQuery.unblockUI({
        onUnblock: function(element, options) {
            if (typeof onUnblockPopup == 'function') {
                onUnblockPopup(classList, retVal);
            }
        }
    });
}
/** generic popup using blockui */

