
$(document).ready(function() {

    // simple browser detect
    var thisIsIe = false;
    if($.browser.msie) {
        thisIsIe = true;
    }

    // custom selects & checkboxes
    $("select, input:checkbox, input:radio, input:file").uniform();

    // homepage features
    var activeFeat = 'app';

    if (thisIsIe) {
        $('.feat-' + activeFeat).css('visibility', 'visible');
    } else {
        $('.feat-' + activeFeat).css('opacity', '1');
        $('.feat-' + activeFeat).css('visibility', 'visible');
    }

    bindHomeFeat('.featicn-app', 'app');
    bindHomeFeat('.featicn-social', 'social');
    bindHomeFeat('.featicn-search', 'search');
    bindHomeFeat('.featicn-cart', 'cart');
    bindHomeFeat('.featicn-beauty', 'beauty');

    function bindHomeFeat(selector, state) {

        $(selector).bind({

            click: function() {
                setTimeout(function() {
                    (function() {
                        if (state != activeFeat) {
                            // remove selected from old icon
                            $('.featicn-' + activeFeat).removeClass('featsel');
                            // fade out old selected
                            if (thisIsIe) {
                                $('.feat-' + activeFeat).css('visibility', 'hidden');
                                $('.feat-' + state).css('visibility', 'visible');
                                $('.featicn-' + state).addClass('featsel');
                                activeFeat = state;
                            } else {
                                $('.feat-' + activeFeat).stop(true).animate({opacity: 0}, 150, function() {
                                    $('.feat-' + activeFeat).css('visibility', 'hidden');
                                    // fade in new selected
                                    $('.feat-' + state).css('visibility', 'visible');
                                    $('.feat-' + state).stop(true).animate({opacity: 1}, 300);
                                    // add selected to new icon
                                    $('.featicn-' + state).addClass('featsel');
                                    // update active state
                                    activeFeat = state;
                                });
                            }
                        }
                    }).apply(this);
                }, 50);
                return false;
            }

        });
    }

    // jobs list
    $('.jobs-post h4 a').each(
        function() {
            $(this).bind({
                'click': function(e) {
                    e.preventDefault();
                    $(this).parent().parent().toggleClass('jobs-post-shown');
                    $(this).parent().parent().children(".jobs-post-list").slideToggle(400);
                }
            })
        }
    );

    // about features
    var aboutVidLocked = false;
    var aboutVidType = '';
    $('.about-features .btn-watch-video').each(
        function() {
            $(this).bind({
                'click': function(e) {
                    e.preventDefault();
                    curPos = $(this).parent().parent().position();

                    if (curPos.left > 0) {
                        thisOverlay = $('.about-overlay-r');
                    } else {
                        thisOverlay = $('.about-overlay-l');
                    }

                    if ($(this).parent().parent().hasClass('feat-locked')) {
                        // hide video
                        clearAboutVid();
                    } else {
                        // hide old selection
                        if (aboutVidLocked) {
                            clearAboutVid();
                        }

                        $(document).one('mousedown', clearAboutVid);
                        $(document).one('touchstart', clearAboutVid);

                        // show video
                        $(this).parent().parent().addClass('feat-locked');
                        aboutVidLocked = true;
                        aboutVidType = thisOverlay;
                        thisOverlay.css('top', (curPos.top-108));
                        thisOverlay.css('display', 'block');

                        var videourl = $(this).attr('href');

                        if ($.support.opacity) {
                            thisOverlay.stop(true).animate({opacity: 1}, 150, function() {
                                createVideo(videourl);
                            });
                        } else {
                            createVideo(videourl);
                        }

                    }

                },
                'mouseenter': function() {
                    $(this).parent().parent().stop(true).addClass('feat-over');
                },
                'mouseleave': function() {
                    $(this).parent().parent().stop(true).removeClass('feat-over');
                }
            })
        }
    );

    // features page
    if ($('.overview-features').length > 0) {
                
        var ovSwitching = false;
        var ovShown = '1-1';
        
        // check for page anchor
        var thisPageHash = location.hash;
        if (thisPageHash.length > 0) {
            
            // the 5 page anchors
            // /keep-change/ (default)
            // /less-search/
            // /unfair-advantage/
            // /eyes-ears/
            // /learning-network/
                        
            if (thisPageHash.indexOf("less-search") > -1) {
                var ovShown = '2-1';
            } else if (thisPageHash.indexOf("unfair-advantage") > -1) {
                var ovShown = '3-1';
            } else if (thisPageHash.indexOf("eyes-ears") > -1) {
                var ovShown = '4-1';
            } else if (thisPageHash.indexOf("learning-network") > -1) {
                var ovShown = '5-1';
            }
        }
                
        // show first overview text
        ovText = $('.overview-exp').get(parseInt(ovShown.substr(0,1) - 1));
        $(ovText).show();

        // add selected class to first overview thumb
        if (($(ovText).children('.features-thumbs').length) > 0) {
            ovThumb = $(ovText).children('.features-thumbs').children('a').get(0);
            $(ovThumb).addClass('sel-link');
        }

        // add selected class to first overview link
        ovLink = $('.overview-features .col-l h3 a').get(parseInt(ovShown.substr(0,1) - 1));
        $(ovLink).addClass('sel-link');

        // show first overview screenshot
        $('#features-lrg-' + parseInt(ovShown.substr(0,1)) + '-1').show();

        // add click event to overview thumbnails
        $('.features-thumbs a').each(
            function() {
                $(this).bind({
                    'click': function(e) {
                        e.preventDefault();
                        if ((!($(this).hasClass('sel-link'))) && (!ovSwitching)) {
                            ovSwitching = true;
                            $('#overview-note').hide();
                            thisEle = $(this);
                            thisPar = $(this).parent().parent('.overview-exp');
                            thisEleIndex = $(thisPar).children('.features-thumbs').children('a').index(thisEle);
                            thisParIndex = $('.overview-exp').index(thisPar);
                            // hide old screenshot
                            $('#features-lrg-'+ovShown).stop(true).fadeOut('fast', function() {
                                $('#features-lrg-'+ovShown).css('opacity',1); // to fix rapid-clicking
                                $('.overview-features .features-thumbs a').removeClass('sel-link');
                                // show new screenshot
                                thisEle.addClass('sel-link');
                                $('#features-lrg-'+(1+thisParIndex)+'-'+(1+thisEleIndex)).stop(true).fadeIn('fast', function() {
                                    ovShown = (1+thisParIndex)+'-'+(1+thisEleIndex);
                                    ovSwitching = false;
                                });
                            });
                        }
                    }
                })
            }
        );

        // add click events to overview links
        $('.overview-features .col-l h3 a').each(
            function() {
                $(this).bind({
                    'click': function(e) {
                        e.preventDefault();
                        thisEle = $(this);
                        thisPar = $(thisEle).parent().parent().children('.overview-exp');
                        thisParIndex = $('.overview-exp').index(thisPar);
                        if (($(thisPar).css('display') != 'block') && (!ovSwitching)) {
                            ovSwitching = true;
                            $('#overview-note').hide();
                            prevPar = $('.overview-exp').get((ovShown.substr(0,1) - 1));
                            $('.overview-features .col-l h3 a').removeClass('sel-link');
                            $(thisEle).addClass('sel-link');

                            // hide old expanded
                            $(prevPar).stop(true).slideUp('fast');
                            
                            // show new expanded
                            $(thisPar).stop(true).slideDown('fast', function() {
                                ovShown = (1+thisParIndex)+'-1';
                                ovSwitching = false;
                            });

                            // hide old screenshot
                            $('#features-lrg-'+ovShown).stop(true).fadeOut('fast', function() {
                                $('#features-lrg-'+ovShown).css('opacity',1); // to fix rapid-clicking
                                $('.overview-features .features-thumbs a').removeClass('sel-link');
                                // show new screenshot
                                if (($(thisPar).children('.features-thumbs').length) > 0) {
                                    thisThumb = $(thisPar).children('.features-thumbs').children('a').get(0);
                                    $(thisThumb).addClass('sel-link');
                                }
                                $('#features-lrg-'+(1+thisParIndex)+'-1').stop(true).fadeIn('fast');
                            });

                        }
                    }
                })
            }
        );

        // add notes to overviews
        $('.mag-glass').each(
            function() {
                $(this).bind({
                    'mouseenter': function() {
                        $('#overview-note').removeClass('note-alt');
                        if (!thisIsIe) {
                            $('#overview-note').css({'opacity': 0, 'display': 'block'});
                        }
                        thisText = $(this).children().children('img').attr('alt');
                        $('#overview-note .mid').html(thisText);
                        // adjust x position
                        thisPos = $(this).position();
                        if ((thisPos.left) > 199) {
                            // overlay on left (default)
                            // startLeft = 430;
                            newLeft = (thisPos.left) + 235;
                            startLeft = (newLeft - 30);
                        } else {
                            // overlay on right
                            $('#overview-note').addClass('note-alt');
                            // startLeft = 750;
                            newLeft = (thisPos.left) + 547;
                            startLeft = (newLeft + 30);
                        }
                        // adjust y position
                        thisHeight = (parseInt($('#overview-note').height()) - 9);
                        if (thisHeight > 119) {
                            newTop = (thisPos.top) - parseInt((thisHeight - 119) / 2);
                        } else {
                            newTop = ((thisPos.top) + parseInt((119 - thisHeight) / 2) - 6);
                        }
                        // position & animate element
                        if (!thisIsIe) {
                            $('#overview-note').css({'left': startLeft + 'px', 'top': newTop + 'px'});
                            $('#overview-note').stop(true).animate({'opacity': 1, 'left': newLeft + 'px'}, 200);
                        } else {
                            $('#overview-note').css({'left': newLeft + 'px', 'top': newTop + 'px'});
                            $('#overview-note').show();
                        }
                    },
                    'mouseleave': function() {
                        thisPos = $(this).position();
                        if ((thisPos.left) > 199) {
                            // overlay on left (default)
                            // startLeft = 430;
                            startleft = (thisPos.left - 30);
                        } else {
                            // overlay on right
                            // startLeft = 750;
                            startleft = (thisPos.left + 30);
                        }
                        if (!thisIsIe) {
                            $('#overview-note').stop(true).animate({'opacity': 0, 'left': startLeft + 'px'}, 200, function() {
                                $('#overview-note').hide();
                            });
                        } else {
                            $('#overview-note').hide();
                        }
                    }
                })
            }
        );

        $(window).load(function () {
            magText = $('#features-lrg-' + ovShown + ' .mag-glass-1').children().children('img').attr('alt');
            magPos = $('#features-lrg-' + ovShown + ' .mag-glass-1').position();
            $('#overview-note .mid').html(magText);
            // adjust x position
            if ((magPos.left) > 199) {
                // overlay on left (default)
                newLeft = (magPos.left) + 235;
                startLeft = (newLeft - 30);
            } else {
                // overlay on right
                $('#overview-note').addClass('note-alt');
                newLeft = (magPos.left) + 547;
                startLeft = (newLeft + 30);
            }
            // adjust y position
            magHeight = (parseInt($('#overview-note').height()) - 9);
            if (magHeight > 119) {
                newTop = (magPos.top) - parseInt((magHeight - 119) / 2);
            } else {
                newTop = ((magPos.top) + parseInt((119 - magHeight) / 2) - 6);
            }
            // position & animate element
            if (!thisIsIe) {
                $('#overview-note').css({'opacity': 0, 'display': 'block', 'left': startLeft + 'px', 'top': newTop + 'px'});
                $('#overview-note').delay(500).animate(
                    {'opacity': 1, 'left': newLeft + 'px'}, 800, "swing"
                ).delay(2000).animate(
                    {'opacity': 0, 'left': startLeft + 'px'}, 800, "swing"
                );
            } else {
                $('#overview-note').css({'left': newLeft + 'px', 'top': newTop + 'px'});
                $('#overview-note').show();
                $('#overview-note').delay(500).animate(
                    {'left': newLeft + 'px'}, 800, "swing"
                ).delay(2000).animate(
                    {'left': startLeft + 'px'}, 800, "swing", function() {
                        $('#overview-note').hide();
                    }
                );
            }
        });

    }

    // getting started page
    if ($('.gettingstarted-list').length > 0) {
        
        // add tool tips to icons
        $('.gettingstarted-list .icn').each(
            function() {
                $(this).bind({
                    'mouseenter': function() {
                        
                        // add border to icon
                        if ($(this).children('.icn-over').length < 1) {
                            $(this).prepend('<span class="icn-over"></span>');
                        }
                        
                        // prepare note content
                        if (!thisIsIe) {
                            $('#gettingstarted-note').css({'opacity': 0, 'display': 'block'});
                        }
                        thisText = $(this).children('img').attr('title');
                        $('#gettingstarted-note .mid').html(thisText);
                        
                        // calculate position
                        thisOffset = $(this).offset();
                        thisPos = $(this).position(); // problems with offset
                        thisHeight = parseInt($('#gettingstarted-note').height());
                        newLeft = (thisPos.left) - 54;
                        newTop = ((thisOffset.top) - thisHeight) - 127;
                        startTop = (newTop - 30);
                        
                        // position & animate element
                        if (!thisIsIe) {
                            $('#gettingstarted-note').css({'left': newLeft + 'px', 'top': startTop + 'px'});
                            $('#gettingstarted-note').stop(true).animate({'opacity': 1, 'top': newTop + 'px'}, 200);
                        } else {
                            $('#gettingstarted-note').css({'left': newLeft + 'px', 'top': newTop + 'px'});
                            $('#gettingstarted-note').show();
                        }
                        
                    },
                    'mouseleave': function() {
                        
                        // remove icon from border
                        $(this).remove('.icn-over');
                        
                        // calculate position
                        startTop = parseInt($('#gettingstarted-note').css('top')) - 30;
                        
                        // position & animate element
                        if (!thisIsIe) {
                            $('#gettingstarted-note').stop(true).animate({'opacity': 0, 'top': startTop + 'px'}, 200, function() {
                                $('#gettingstarted-note').hide();
                            });
                        } else {
                            $('#gettingstarted-note').hide();
                        }
                        
                    }
                })
            }
        );
        
    }
    
    function createVideo(url) {
        var videoDiv = $("<div></div>").addClass('video-snippet');
        aboutVidType.append(videoDiv);
        var fv = videoDiv.flareVideo({
          'loop': true,
            'autoplay': true,
            'controls': false,
            'flashSrc': '/_swf/flarevideo.swf',
            'srcs':[
            {
              src:  url,
              type: 'video/mp4'
            }
        ]
        });
    }

    function clearAboutVid () {
        $('.about-features li').each(
            function() {
                $(this).removeClass('feat-locked');
            }
        )

        aboutVidType.children().remove();

        if ($.support.opacity) {
            aboutVidType.stop(true).animate({opacity: 0}, 150, function() {
                $(this).css('display','none');
            });
        } else {
            aboutVidType.css('display', 'none');
        }

        aboutVidLocked = false;
        aboutVidType = '';
    };

    // sales list
    $('.sales-list li .list-exp').hide();
    $('.sales-list li a').bind({
        'click': function(e) {
            e.preventDefault();
            thisLink = $(this);
            $(this).parent('li').children('.list-exp').slideToggle('fast', function() {
                thisLink.toggleClass('list-sel');
            });
        }
    });

    // blog/educators press carousel
    if ($('.side-highlights').length) {

        var hlSel = 0;
        var hlTotal = 0;
        var hlHeight = 0;
        var hlTimeout = '';

        // get all link boxes
        hlItems = $('.side-highlights .side-desc').get();
        hlTotal = (hlItems.length) - 1;

        if (!thisIsIe) {
            // get height of link boxes, hide all link boxes
            $('.side-highlights .side-desc').each(
                function() {
                    if (parseInt($(this).outerHeight()) > hlHeight) {
                        hlHeight = parseInt($(this).css('height'));
                    }
                }
            );
            $('.side-highlights .side-desc').css('height',hlHeight + 'px');
        }
        $('.side-highlights .side-desc').css('display','none');

        // show selected link box
        $(hlItems[0]).css('display','block');

        // create links
        for (i = 0; i < hlItems.length; i++) {
            $('.side-highlights .side-bot').append('<a href="#"></a>');
        }

        // add selected state to first link
        hlLink = $('.side-highlights .side-bot a').get(0);
        $(hlLink).addClass('sel');

        // set left pad of link box
        hlPad = (parseInt($('.side-highlights .side-bot').css('width')) / 2) - ((hlItems.length * 20) / 2);
        $('.side-highlights .side-bot').css('paddingLeft',hlPad + 'px');
        $('.side-highlights .side-bot').css('width', (296-hlPad) + 'px');

        // add actions to links
        $('.side-highlights .side-bot a').bind({
            'click': function(e) {
                e.preventDefault();
                hlNew = $('.side-highlights .side-bot a').index(this);
                hlText = $(hlItems[hlNew]);
                if ($(hlText).css('display') == 'none') {
                    hlFade(hlNew,false);
                }
            }
        });
        
        // if more than one link box, start auto fade
        if (hlItems.length > 1) {
            var hlTimeout = window.setInterval(function() {
                if (hlSel < hlTotal) {
                    hlFade(1+hlSel,true);
                } else {
                    hlFade(0,true);
                }
            }, (8 * 1000));
        }
        
        function hlFade(hlNew,hlTimer) {

            if (!hlTimer) {
                hlStop();
            }

            hlText = $(hlItems[hlNew]);
            hlLinkNew = $('.side-highlights .side-bot a').get(hlNew);
            hlLinkOld = $('.side-highlights .side-bot a').get(hlSel);

            $(hlItems[hlSel]).stop(true).fadeOut(200, function() {
                $(hlItems[hlSel]).css('opacity',1); // to fix rapid-clicking
                $(hlLinkOld).removeClass('sel');
                $(hlLinkNew).addClass('sel');
                $(hlText).fadeIn('fast');
                hlSel = hlNew;
            });
        }

        function hlStop() {
            if (hlTimeout != '') {
                window.clearInterval(hlTimeout)
                hlTimeout = '';
            }
        }

    }
    

    // FANCYBOX FORM STUFF

    function initFancybox(ele,fname,ferror) {
        $(ele).fancybox({
            'titleShow'       : false,
            'overlayShow'     : true,
            'overlayOpacity'  : 0.8,
            'overlayColor'    : '#eeeeee',
            'scrolling'       : 'no',
            'autoDimensions'  : true,
            'showCloseButton' : true,
            'padding'         : 0,
            'margin'          : 0,
            'onStart' : function() {
                if (!$('#fancybox-outer').hasClass('whiteoverlay')) {
                    $('#fancybox-outer').addClass('whiteoverlay');
                }
                $(':input',fname).val('');
            },
            'onClosed' : function() {
                resetFancybox(fname,ferror,true);
            }
        });
    }

    function resetFancybox(fname,ferror,vals) {
        if (ferror != 0) {
            $(ferror).hide();
        }
        $(fname + ' div').removeClass('form-error');
        if (vals) {
            $(':input',fname).val('');
            if (fname == '#form-free-title') {
                $(fname).get(0).reset();
                $.uniform.update();
            }
        }
    }

    // refer a friend, sidebar button
    initFancybox('.btn-refer-friend','#form-refer-friend','#f-refer-error');

    // refer a friend, nav button
    initFancybox('.nav-refer a','#form-refer-friend','#f-refer-error');

    // notify me, micro site
    initFancybox('.btn-notifyme','#form-notifyme',0);

    // request title
    initFancybox('.btn-request-title','#form-request-title','#f-request-error');

    // request free title
    initFancybox('.btn-free-title','#form-free-title','#f-free-error');

    // refer a friend ajax
    $("#form-refer-friend").bind("submit", function() {

        resetFancybox('#form-refer-friend','#f-refer-error',false);

        if (($("#f-refer-emails").val().length < 1) || ($("#f-refer-name").val().length < 1) || ($("#f-refer-email").val().length < 1)) {
            $("#f-refer-error").show();
            if ($("#f-refer-emails").val().length < 1) {
                if (!$("#f-refer-emails").parent().parent().hasClass('form-error')) {
                    $("#f-refer-emails").parent().parent().addClass('form-error');
                }
            }
            if ($("#f-refer-name").val().length < 1) {
                if (!$("#f-refer-name").parent().parent().hasClass('form-error')) {
                    $("#f-refer-name").parent().parent().addClass('form-error');
                }
            }
            if ($("#f-refer-email").val().length < 1) {
                if (!$("#f-refer-email").parent().parent().hasClass('form-error')) {
                    $("#f-refer-email").parent().parent().addClass('form-error');
                }
            }
            $.fancybox.resize();
            return false;
        }

        $.fancybox.showActivity();

        $.ajax({
            type        : "POST",
            cache       : false,
            url         : "/refer_friend/",
            data        : $(this).serializeArray(),
            success: function(data) {
                if (data == 'pass') {
                    $.fancybox($('#referfriend-thanks').html(), {'padding': 0, 'margin': 0});
                    $.fancybox.resize();
                    resetFancybox('#form-refer-friend','#f-refer-error',true);
                } else {
                    $.fancybox.hideActivity();
                    resetFancybox('#form-refer-friend','#f-refer-error',false);
                    $("#f-refer-error").show();
                    if (data.indexOf("recipients") > -1) {
                        $("#f-refer-emails").parent().parent().addClass('form-error');
                    }
                    if (data.indexOf("name") > -1) {
                        $("#f-refer-name").parent().parent().addClass('form-error');
                    }
                    if (data.indexOf("email") > -1) {
                        $("#f-refer-email").parent().parent().addClass('form-error');
                    }
                    $.fancybox.resize();

                }
            }
        });

        return false;
    });

    // request a title ajax
    $("#form-request-title").bind("submit", function() {

        resetFancybox('#form-request-title','#f-request-error',false);

        if (($("#f-request-title").val().length < 1) || ($("#f-request-name").val().length < 1) || ($("#f-request-email").val().length < 1) || ($("#f-request-work").val().length < 1)) {
            $("#f-request-error").show();
            if ($("#f-request-title").val().length < 1) {
                if (!$("#f-request-title").parent().parent().hasClass('form-error')) {
                    $("#f-request-title").parent().parent().addClass('form-error');
                }
            }
            if ($("#f-request-name").val().length < 1) {
                if (!$("#f-request-name").parent().parent().hasClass('form-error')) {
                    $("#f-request-name").parent().parent().addClass('form-error');
                }
            }
            if ($("#f-request-email").val().length < 1) {
                if (!$("#f-request-email").parent().parent().hasClass('form-error')) {
                    $("#f-request-email").parent().parent().addClass('form-error');
                }
            }
            if ($("#f-request-work").val().length < 1) {
                if (!$("#f-request-work").parent().parent().hasClass('form-error')) {
                    $("#f-request-work").parent().parent().addClass('form-error');
                }
            }
            $.fancybox.resize();
            return false;
        }

        $.fancybox.showActivity();

        $.ajax({
            type        : "POST",
            cache       : false,
            url         : "/request_title/",
            data        : $(this).serializeArray(),
            success: function(data) {
                if (data == 'pass') {
                    $.fancybox($('#requesttitle-thanks').html(), {'padding': 0, 'margin': 0});
                    $.fancybox.resize();
                    resetFancybox('#form-request-title','#f-request-error',true);
                } else {
                    $.fancybox.hideActivity();
                    resetFancybox('#form-request-title','#f-request-error',false);
                    $("#f-request-error").show();
                    if (data.indexOf("title") > -1) {
                        $("#f-request-title").parent().parent().addClass('form-error');
                    }
                    if (data.indexOf("name") > -1) {
                        $("#f-request-name").parent().parent().addClass('form-error');
                    }
                    if (data.indexOf("email") > -1) {
                        $("#f-refer-email").parent().parent().addClass('form-error');
                    }
                    if (data.indexOf("work") > -1) {
                        $("#f-refer-work").parent().parent().addClass('form-error');
                    }
                    $.fancybox.resize();

                }
            }
        });

        return false;
    });

    // free title request ajax
    $("#form-free-title").bind("submit", function(event) {

        resetFancybox('#form-free-title','#f-free-error',false);

        if (($("#f-free-institution").val().length < 1) || ($("#f-free-first").val().length < 1) || ($("#f-free-last").val().length < 1) || ($("#f-free-prof-email").val().length < 1) || ($("#f-free-courses").val().length < 1) || ($("#f-free-titlename").val().length < 1)) {
            $("#f-free-error").show();
            if ($("#f-free-institution").val().length < 1) {
                if (!$("#f-free-institution").parent().parent().hasClass('form-error')) {
                    $("#f-free-institution").parent().parent().addClass('form-error');
                }
            }
            if ($("#f-free-prof-email").val().length < 1) {
                if (!$("#f-free-prof-email").parent().parent().hasClass('form-error')) {
                    $("#f-free-prof-email").parent().parent().addClass('form-error');
                }
            }
            if ($("#f-free-courses").val().length < 1) {
                if (!$("#f-free-courses").parent().parent().hasClass('form-error')) {
                    $("#f-free-courses").parent().parent().addClass('form-error');
                }
            }
            if ($("#f-free-titlename").val().length < 1) {
                if (!$("#f-free-titlename").parent().parent().parent().hasClass('form-error')) {
                    $("#f-free-titlename").parent().parent().parent().addClass('form-error');
                }
            }
            $.fancybox.resize();
            return false;
        }

        $.fancybox.showActivity();

        function randomString() {
        	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
        	var string_length = 40;
        	var randomstring = '';
        	for (var i=0; i<string_length; i++) {
        		var rnum = Math.floor(Math.random() * chars.length);
        		randomstring += chars.substring(rnum,rnum+1);
        	}
            return randomstring
        }
        //Make a hashed email
        var realEmail = $("#f-free-prof-email").val().split("@");
        var emailHash = realEmail[0]+"+"+randomString()+"@"+realEmail[1];
        $("#f-hash-email").val(emailHash);
    
        
        console.log($("#f-hash-email").val());

        event.preventDefault();
        $.getJSON(
        this.action + "?callback=?",
        $(this).serialize(),
        function (data) {
            if (data.Status === 400) {
                //data.Message
                $("#f-free-error").show();
                $.fancybox.hideActivity();
                console.log(data)
            } else { // 200
                $.fancybox($('#freetitle-thanks').html(), {'padding': 0, 'margin': 0});
                $.fancybox.resize();
                resetFancybox('#form-free-title','#f-free-error',true);
            }
        });
        
        return false;
    });

    // RSVP Ajax
    $("div.webinar a.rsvp-button").bind("click", function() {
        $("div.webinar div.form-group").hide()
        $("div.webinar div.error").hide();
        $("div.webinar img.spinner").show();
        $('#subForm').submit(function (e) {
            e.preventDefault();
            $.getJSON(
            this.action + "?callback=?",
            $(this).serialize(),
            function (data) {
                if (data.Status === 400) {
                    //data.Message
                    $("div.webinar div.error").text(data.Message).show();
                    $("div.webinar div.form-group").show();
                } else { // 200
                    $("div.webinar img.spinner").fadeOut();
                    $("div.webinar div.thank-you").fadeIn();
                }
            });
        });
        $('#subForm').submit();
    });
    
    // submission policy overlay & anchor
    if ($('.btn-sub-policy').length > 0) {
        
        $('.btn-sub-policy').fancybox({
            'titleShow'       : false,
            'overlayShow'     : true,
            'overlayOpacity'  : 0.8,
            'overlayColor'    : '#eeeeee',
            'scrolling'       : 'no',
            'autoDimensions'  : true,
            'showCloseButton' : true,
            'padding'         : 0,
            'margin'          : 0,
            'onStart' : function() {
                if (!$('#fancybox-outer').hasClass('whiteoverlay')) {
                    $('#fancybox-outer').addClass('whiteoverlay');
                }
            }

        });

        // check for page anchor
        var thisPageHash = location.hash;
        if (thisPageHash.length > 0) {
            if (thisPageHash.indexOf("submission-policy") > -1) {
                $(window).load(function() {
                    $('.btn-sub-policy').trigger('click');
                });
            }
        }
    }

    // grey box overlays
    $('.grey-img').each(
        function() {
            $(this).fancybox({
                'titleShow'       : false,
                'overlayShow'     : true,
                'overlayOpacity'  : 0.8,
                'overlayColor'    : '#eeeeee',
                'scrolling'       : 'no',
                'autoDimensions'  : true,
                'showCloseButton' : true,
                'padding'         : 0,
                'margin'          : 0,
                'hideOnContentClick' : false
            })
        }
    );

    // footer newsletter
    $(".newsletter-footer").bind("submit", function(){
        var $this = $(this).addClass("sending").removeClass("sent failed")
        var data = $this.serializeArray() // must come before disabling
        var $inputs = $this.find("input").attr("disabled", "disabled");

        $.ajax({
            type: "POST",
            cache       : false,
            url: $this.attr("action"),
            data: data,
            success: function(data){
                $this.addClass("sent");
                $inputs.attr("disabled", "");
            },
            error: function(){
                $this.addClass("failed");
                $inputs.attr("disabled", "");
            },
            complete: function(){
                $this.removeClass("sending");
                $inputs.attr("disabled", "");
            }
        });

        return false;
    });

    // sidebar newsletter
    $(".newsletter-side").bind("submit", function(){
        var $this = $(this).addClass("sending").removeClass("sent failed")
        var data = $this.serializeArray() // must come before disabling
        var $inputs = $this.find("input").attr("disabled", "disabled");

        $.ajax({
            type: "POST",
            cache       : false,
            url: $this.attr("action"),
            data: data,
            success: function(data){
                $this.addClass("sent");
                $inputs.attr("disabled", "");
            },
            error: function(){
                $this.addClass("failed");
                $inputs.attr("disabled", "");
            },
            complete: function(){
                $this.removeClass("sending");
                $inputs.attr("disabled", "");
            }
        });

        return false;
    });
    
    // request free title automatic modal window spawn
    if ($('#overlay-freetitle').length > 0) {
        
        // check for page anchor
        var thisPageHash = location.hash;
        if (thisPageHash.length > 0) {
            if (thisPageHash.indexOf("free-title-request") > -1) {
                $(window).load(function() {
                    $('.btn-free-title').trigger('click');
                });
            }
        }
    }
    
    // promo hero feature
    if ($('.overview-promos').length > 0) {
        
        $('.btn-watch-video').fancybox({
            'titleShow'       : false,
            'overlayShow'     : true,
            'overlayOpacity'  : 0.8,
            'overlayColor'    : '#eeeeee',
            'scrolling'       : 'no',
            'autoDimensions'  : true,
            'showCloseButton' : true,
            'padding'         : 0,
            'margin'          : 0,
            'onStart' : function() {
                if (!$('#fancybox-outer').hasClass('whiteoverlay')) {
                    $('#fancybox-outer').addClass('whiteoverlay');
                }
            }

        });
        
        var promoImgSel = 0;
        var promoImgAni = false;
        $('#chapters table .part').hide();
        $('.promo-book-img .chapters-buy').hide();
        
        var thisPageHash = location.hash;
        if (thisPageHash.length > 0) {
            
            // the 4 page anchors
            // /chef/
            // /soup/
            // /meat/
            // /desserts/
            // /video/ (spawns video)
                        
            if (thisPageHash.indexOf("chef") > -1) {
                var promoImgSel = '0';
            } else if (thisPageHash.indexOf("soup") > -1) {
                var promoImgSel = '1';
            } else if (thisPageHash.indexOf("meat") > -1) {
                var promoImgSel = '2';
            } else if (thisPageHash.indexOf("desserts") > -1) {
                var promoImgSel = '3';
            } else if (thisPageHash.indexOf("video") > -1) {
                $(window).load(function () {
                    $('.btn-watch-video').trigger('click');
                });
            }
            
        }
        
        promoImg = $('.overview-promos .top img').get(promoImgSel);
        promoLink = $('.overview-promos .bot a').get(promoImgSel);
        $(promoImg).css('z-index','3');
        $(promoLink).addClass('sel');
        $('.overview-promos .top img').css('visibility','visible');
        $('#chapters table .part.chapters-'+promoImgSel).show();
        $('.promo-book-img #chapters-buy-'+promoImgSel).show();
        
        $('.overview-promos .bot a').click(function(e) {
            e.preventDefault();
            if ((!$(this).hasClass('sel')) && (!promoImgAni)) {
                
                promoImgAni = true;
                thisEl = this;
                thisElI = $('.overview-promos .bot a').index(this);
                imgToHide = $('.overview-promos .top img').get(promoImgSel);
                imgToShow = $('.overview-promos .top img').get(thisElI);
                
                $('.overview-promos .bot a').removeClass('sel');
                promoLink = $('.overview-promos .bot a').get(thisElI);
                $(promoLink).addClass('sel');
                
                // change heading
                $('.hd-promo-cook').removeClass('hd-promo-cook-bake');
                if (thisElI == 3) {
                    $('.hd-promo-cook').addClass('hd-promo-cook-bake');
                }
                
                // change chapters
                $('#chapters table .part').hide();
                $('#chapters table .part.chapters-'+thisElI).show();
                
                // change chapter buy links
                $('.promo-book-img .chapters-buy').hide();
                $('.promo-book-img #chapters-buy-'+thisElI).show();
                
                $(imgToHide).css('z-index','2');
                $(imgToShow).hide();
                $(imgToShow).css('z-index','3');
                $(imgToShow).fadeIn(400, function() {
                    promoImgAni = false;
                    promoImgSel = thisElI;
                    $(imgToHide).css('z-index','1');
                });
                
            }
        });
        
    }
    
    
});
