/**
 * JS that applies to all pre-signup pages goes here
 **/

function liveperson_link() {
    pageTracker._trackPageview('signup-chat');
    window.open('https://server.iad.liveperson.net/hc/88547071/?cmd=file&file=visitorWantsToChat&site=88547071&byhref=1','','scrollbars=no,menubar=no,height=400,width=475,resizable=yes,toolbar=no,location=no,status=no');
}

function demo_open() {
    // demo open link
    $('#demo-popup').dialog('open');
}

$(document).ready(function(){
        
    var login_modal;

    // demo popup box
    $("#demo-popup").dialog({
        bgiframe    : false,
        modal       : true,
        resizable   : false,                            
	width       : 700,
	autoOpen: false,
        position: ['top', 50]	    
    });
    
    // demo open link
    $('#temp-demo').click(function(){
	    demo_open();
    });
    
    // this would apply the supersleight function to anything with the div id of 'content' -->
	$('.content-gradient').supersleight({shim: 'images/shim.gif'});
    $('#search-box-bkgd').supersleight({shim: 'images/shim.gif'});
    $('#gsubnav').supersleight({shim: 'images/shim.gif'});
    $('#features-content').supersleight({shim: 'images/shim.gif'});
    $('#side-nav').supersleight({shim: 'images/shim.gif'});
    $('.btn-gradient').supersleight({shim: 'images/shim.gif'});
    $('img#beta-tag').supersleight({shim: 'images/shim.gif'});
    
    $('#search-link').mouseover(function() {
		$('#search-box').css({"display" : "block"});
        $(".search-input input").focus();
	});
		
    $('#search-box').mouseleave(function() {
		$(this).css({"display" : "none"});
	});

    $(".search-input input").focus(function () {
        $(this).parent().css({'background-position' : "0 29px"});
	})
	.blur(function () {
        $(this).parent().css({'background-position' : "0 0"});
        $(this).css({'background-color' : '#fff'});					
	});				
		
    $(".email-input input").focus(function () {
        $(this).parent().css({'background-position' : "0 31px"});
        $(this).css({'background-color' : '#fffaed'});					
	})
	.blur(function () {
        $(this).parent().css({'background-position' : "0 0"});
        $(this).css({'background-color' : '#fff'});					
	});				
		
    $('.nav-link').mouseover(function() {

	    // remove all hover classes for all navs -->
	    // pretty in-elegant here, could be improved -->			
	    $('.nav-link').removeClass('register-hover benefits-hover marketing-network-hover price-hover about-hover');
			
        // turn on hover for this nav button -->
        $(this).addClass( $(this).attr("id") + '-hover');
		
        // hide all subnavs -->
        $('.gsub').css({'display' : 'none'});
		
        // turn on only this subnav -->
        $('#gsub-' + $(this).attr("id") ).css({'display' : 'block'});					
			
	})
    .mouseleave(function(event) {			
		// if you're going to an element that's not within the gsub class you're leaving, so hide the hover and subnav -->
		if ($(event.relatedTarget).parent().hasClass("gsub") === false) {
            $('.nav-link').removeClass('register-hover benefits-hover marketing-network-hover price-hover about-hover');
            $('#gsub-' + $(this).attr("id")).css({'display' : 'none'});
        }						
	});
		
    // mouseleave event for subnavs -->
    $('.gsub').mouseleave(function(event) {
		// if you're going to something that's not in gsub or gnav hide it -->
		// this seems wrong because of the case of going to a different nav tab but we also hide all subnavs when those are moused over, so it works out -->			
	 	if ($(event.relatedTarget).parent().hasClass("gsub") === false && event.relatedTarget.id.indexOf("gnav") == -1) {
            $('.nav-link').removeClass('register-hover benefits-hover marketing-network-hover price-hover about-hover');
            $(this).css({'display' : 'none'});			
        }									
	});

    /**
     * Applies magic labels to the given elements
     **/
    var labeler = function(parent) {
        
        var labels = $(parent).find('.input label').add('.fld-singleton label').addClass('js');
              
        var fields = $(parent).find(".input input[type='text']")
            .add(".input input[type='password']")
            .add("div.fld-singleton input[type='text']")
            .add("div.fld-singleton input[type='password']")
        .each(function() {
            var self = this;
            $(window).load(function() {
                setTimeout(function(){
                    if (self.value != '') {
                        $(self).prev('label').addClass('has-text');
                    }
                }, 200);
            });
        })
        .focus(function(e) {
            $(this).prev('label').addClass('focus');
        })
        .blur(function(e) { // Bind blur listeners - add back label if field is empty
            if ($(this).val() == '') {
                $(this).prev('label').removeClass('has-text').removeClass('focus');
            }
        })
        .keypress(function (e) {
            $(this).prev('label').addClass('has-text').removeClass('focus');
        });
        
    };
    
    // Bind listener to login for modal
    $('#header-btn-login').click(function(e) {

        e.preventDefault();
        if (login_modal) {
            $(login_modal).dialog('open');
            $('#fldEmail').focus();
        }
        else {

            // Add the CSS (so it's already in place when we create the modal
            if (!$("head link[href='/css/presignup/login.css']").length) {
                $('head').append('<link rel="stylesheet" href="/css/presignup/login.css" type="text/css" />');
            }

            // Create a reusable modal
            login_modal = $('<div id="login-modal"></div>').appendTo('body');
            $(login_modal).load(
                '/login?ajax=1',
                null,
                function (responseText) {

                    // If there's nothing returned, redirect to login page
                    if (!responseText) {
                        location.href = '/login';
                    }
                    
                    $(login_modal).dialog({
                        dialogClass : 'login-modal-wrapper',
                        draggable   : false,
//                        height      : $('#login').height() + 80,
                        modal       : true,
                        resizable   : false,
                        width       : $('#login').width(),
                        zIndex      : '9098',

                        beforeclose : function() {
                            $('#frm-forgot_password').hide();
                            $('#frm-login').show();
                            $('#frm-login-msg').hide();
			    $('#frm-forgot_password').find('.error').remove();  
                        }
                    });
                    
                    // Move the close button to inside the form
                    $('.login-modal-wrapper .ui-dialog-titlebar-close')
                        .prependTo('#login')
                        .css('position', 'absolute')
                        .css('top', '20px')
                        .css('right', '50px')
                        .css('z-index', '9999');
                    $('.login-modal-wrapper .ui-widget-header').remove();

                    // Apply the labeler to the form fields
                    labeler(login_modal);
                    $(login_modal).find('.input input').css('z-index', 9998);
                    $(login_modal).find('.input label').css('z-index', 9999);
                    $('#fldEmail').focus();
                        
            }); // End load
        } // End else
        
    });

    // Input label munging
    labeler('body');
    // Bind listener to get in the loop submission
    $('form.frm-newsletter').submit(function(e) {
        e.preventDefault();

        // Make sure the submitter isn't a robot
        // by checking the value of the honeypot field.
        // If it has text, it's a bot.
        if ($(this).find('.fld-honey').val()) {
            return;
        }

        // Validation
        var email = $(this).find("input[name='email']").val();
        if (!email) {
            return;
        }

        var self = this;
        
        var data = {
            ajax  : 1,
            email : email,
            src   : $(this).find("input[name='src']").val()
        };
        $.post($(this).attr('action'), data, function(data) {
            if (data.status) {
                $(self).html('<strong>Thanks for subscribing!<br/>We promise to treat your email<br/>like it was our own</strong>');
		pageTracker._trackPageview('signup-in-the-loop');
            }
            else {
                var msg = 'An unknown error occurred. Please try to subscribe again later';
                if (data.msg.email.emailAddressInvalidFormat) {
                    msg = 'Please enter a valid email address.';
                }
                else if (data.msg.email.recordFound) {
                    msg = 'This email is already in our system.';
                }
		$('.error').remove();
                $(self).prepend('<div class="error">'+msg+'</div>');
            }
        }, 'json');
        
    });
});


