// TODO - BS - Add generic error checking on page load.
// Look for error object written by server side into javascript
// If a custom error handling function is defined for this page, use that, otherwise osme standard notification

function addslashes(str) {
    str=str.replace(/\'/g,'\\\'');
    str=str.replace(/\"/g,'\\"');
    str=str.replace(/\\/g,'\\\\');
    str=str.replace(/\\0/g,'\\0');
    return str;
}

function stripslashes(str) {
    str=str.replace(/\\'/g,'\'');
    str=str.replace(/\\"/g,'"');
    str=str.replace(/\\\\/g,'\\');
    str=str.replace(/\\0/g,'\0');
    return str;
}

function htmlentities(s) {
    var str = new String(s);
    str = str.replace(/&/g, "&amp;");
    str = str.replace(/</g, "&lt;");
    str = str.replace(/>/g, "&gt;");
    return str;
}


/**
 * for panel +/- (vaL 050809)
 */
function panel_toggle(obj){
	var parent = $(obj).parents('.panel');
	var div;
	if(parent.length){
		div = $(parent[0]).children('.panel_body');
		if(div.length){
			$(div[0]).toggleClass('panel_body_hide');	
		}
	}
	
	$(obj).children('.panel_toggle').toggleClass('panel_toggle_plus');
}


$(function (){
	// convenient javascript function for testing "empty"
	$.empty = function( mixed_var ) {

	    var key;

	    if (mixed_var === "" ||
	        mixed_var === 0 ||
	        mixed_var === "0" ||
	        mixed_var === null ||
	        mixed_var === false ||
	        mixed_var === undefined )
		{
	        return true;
	    }

	    if (typeof mixed_var == 'object') {
	        for (key in mixed_var) {
	            return false;
	        }
	        return true;
	    }

	    return false;
	};

	// ajax default error handling

	$.ajaxSetup({
        dataType: "json"
	});

	$.FLAjaxConnectionError = function() {
		$("<p>There was a network or server error. Please try again later.</p>").dialog({title: "Error", modal: true, resizable: false, buttons: { 'Ok': function() { $(this).dialog("close"); } }});
	};

    $(document).ajaxError(function() {
        setTimeout($.FLAjaxConnectionError, 3000);
    });

	// this can be used inside the 
	$.FLCheckAjaxError = function(data) {
		if (!$.empty(data.error_code)) {
			$("<p>" + data.error_message + "</p>").dialog({title: "Error", modal: true, resizable: false, buttons: { 'Ok': function() { $(this).dialog("close"); } }});
			return true;
		} else {
			return false;
		}
	};

	if (jQuery.validator){
		jQuery.validator.addMethod("thisManyNumbers", function(value, element, param) { 
			var pattern = new RegExp('[0-9]{' + param + '}');
		 return this.optional(element) || pattern.test(value);
		}, jQuery.format("Please enter at least  {0} number(s) in your password."));
		jQuery.validator.addMethod("thisManyLetters", function(value, element, param) { 
			var pattern = new RegExp('[a-zA-Z]{' + param + '}');
		 return this.optional(element) || pattern.test(value);
		}, jQuery.format("Please enter at least  {0} letters(s) in your password."));
	}
	
	if(Server.error_code) {
		$("<p>" + Server.error_message + "</p>").dialog({
			title: "Error", modal: true, resizable: false, 
			buttons: { 'Ok': function() { $(this).dialog("close"); } }
		});
	}

	if(Server.info_code) {
		$("<p>" + Server.info_message + "</p>").dialog({
			title: "Information", modal: true, resizable: false, 
			buttons: { 'Ok': function() { $(this).dialog("close"); } }
		});
	}
	
	$("#header_logout").click(function() {
        if (typeof(FB) == 'object') {
            FB.ensureInit(function() {
                FB.Connect.logout(function(response) {
                    window.location.href = Server.site_url + '/logout';
                });
            });
        }
        else {
            window.location.href = Server.site_url + '/logout';
        }
        return false;
	});
	
	$("#verify_email_sent").dialog({
	        title: "Confirmation Email Sent", 
	        dialogClass: "signup", 
	        modal: true, autoOpen: false, width: 500, resizable: false, 
	        buttons: { 
                'Close': function() {
                    $(this).dialog("close");
		        }
	        }
	});

    $('#resend_email_link').click(function(){
        $("#resend_email").ajaxSubmit({
            success : function(data){
                if (data.error_code > 0) {
                    $.FLCheckAjaxError(data);
                }
                else {
                    $("#verify_email_sent").dialog('open');
                }
            },
            error : function () {
                $.FLAjaxConnectionError();
            }
        });
    });

});


Common = {};

Common.init = function(context) {

    /*
     * for tooltips, all elements with a class '.with_tooltip' will get a tooltip
     * the tooltip's text/innerHTML can be the element's "alt" value or its <em> child
     *
     * alt for 'text only' tooltips
     * <em> child is available because sometimes, the 'alt' contains an fb:name (&the like)
     */

    $(".with_tooltip", context).each(function(i) {
        var tooltip_text = $(this).attr('alt');
        if (tooltip_text) {
            $(this).append('<em><span>'+tooltip_text+'</span></em>');
        }
        $(this).css({'position':'relative'});
    });

    $(".with_tooltip", context).hover(function() {
        if($(this).children("em").text()) {
            $(this).children("em").show();
        }
    }, function() {
        $(this).children("em").hide();
    });

    $(".watermark", context).each(function() {
        // For all input text items, remove the grey class and clear the box on focus.
        $(this).focus(function() {
            $(this).filter(function() {
                // We only want this to apply if there's not something actually entered
                return $(this).val() === "" || $(this).val() == $(this).attr('watermark');
            }).removeClass("watermark").val("");
        });

        // When the input item loses focus, add the grey class back and the default text if they haven't entered anything.
        $(this).blur(function() {
            $(this).filter(function() {
                // We only want this to apply if there's not something actually entered
                return $(this).val() === "";
            }).addClass("watermark").val($(this).attr('watermark'));
        });

        var that = this;
        $(this).parents('form').submit(function() {
            // Clear out any fields that still have the watermark
            if ($(that).val() == $(that).attr('watermark')) {
                $(that).val('');
            }
        });

        // Cause watermarks to appear on every field
        $(this).blur();
    });

    $('.tips_close_button').hover(
        function() {
            $(this).children('img').attr('src', Server.static_url+'/images/tips_button_close_hover.png');
        },
        function() {
            $(this).children('img').attr('src', Server.static_url+'/images/tips_button_close.png');
        }
    );

    $('.tips_close_button').click(function() {
        var that = this;
        $.post(Server.site_url + '/relatives/ajax/toggle_tips_panel', {state : 'close'}, function(data) {
            if (data.success === true) {
                $('.tips_open_state').slideUp();
                $('.tips_closed_state').slideDown();
            }
        });
    });

    $('.tips_open_button').click(function() {
        $.post(Server.site_url + '/relatives/ajax/toggle_tips_panel', {state : 'open'}, function(data) {
            if (data.success === true) {
                $('.tips_open_state').slideDown();
                $('.tips_closed_state').slideUp();
            }
        });
    });

    // Do we need to ask for any extended permissions?
    if (Server.ask_for_facebook_permission) {
		Server.ask_for_facebook_permission = false; //  It sometimes calls this Common.init() twice... Prevent the dialog from poping up again
		typeof(FB) == "object" && FB.ensureInit(function() {
		 FB.Connect.showPermissionDialog('email,publish_stream,read_stream, xmpp_login,read_friendlists,user_relationships,user_birthday,user_status,user_photo_video_tags,user_photos,friends_birthday,friends_relationships,friends_photos,friends_photo_video_tags,friends_status,user_interests,user_activities,user_likes,user_education_history,user_religion_politics,user_work_history', function(perms) {
                var session;
                if (perms.xmpp_login) {
                    session = Facebook.apiClient.get_session();
                    Meebo('partnerConnect', 'facebook', session.uid, session.session_key);
                }

                // TODO: Move this out of here. It's not really related to Facebook permission dialogs.
			   	$.ajax({
                  type: 'POST',
			   	  url: Server.server_url+'/profile/ajax/update_missing_info',
			   	  data: {netdat:1, perms:perms},
			   	  dataType: "json",
			   	  success: function(data){
			   	  		if (data == 'owned') {
			   	  			$('#missing_info_body').hide();
			   	  			$('#new_password_body').removeClass('hide');
			   	  		}
			   	  		
			   	  		if (data != 'duplicate') {
			   	  			MissingInfoPopup.show(true);
			   	  		}
			   	     },
			   	     error: function(data) {
			   	         $.FLAjaxConnectionError();
			   	     }
			   	 });
                if (perms.xmpp_login) {
                    session = Facebook.apiClient.get_session();
                    Meebo('partnerConnect', 'facebook', session.uid, session.session_key);
                }
			});
		});       	
   	}
   	

    // If logged in, try to connect with Meebo
    typeof(FB) == 'object' && FB.ensureInit(function() {
        var session = FB.Facebook.apiClient.get_session();
        typeof(Meebo) == 'object' && function() {
            Meebo('partnerConnect', 'facebook', session.uid, session.session_key);
        }();
    });

   	if (Server.show_missing_info_popup) {
   		MissingInfoPopup.show(false);
   	}

    if (Server.peel_ad) {
        $('.header_small_links').css('margin-right', '105px');
        $('#header_search_widget').css('margin-right', '105px');
    }
};

Common.report_problem = function(context) {
	var popup = $('#report_problem_box');
	
	$(popup).dialog({
		title: 'Report a Problem', 
	    modal: true,
	    width: 460,
	    resizable: false, 
	    dialogClass: 'ui-dialog-secure', // Add padlock of security to bottom left of dialog
	    buttons: { 
	    	'Cancel': function() {
	    		$(this).find('#report_problem_box_text').val('');
	        	$(popup).dialog('destroy');
	    	},
	        'Report' : function() {
	            var text = $(this).find('#report_problem_box_text').val();
	            $.ajax({
	              type: "GET",
	              url: Server.server_url+'/contactus/ajax/report_a_problem',
	              data: {text:text},
	              dataType: "json",
	              success: function(data){
	              	$('#report_problem_box_text').val('');
	                $(popup).dialog('destroy');
	              },
	              error: function(data) {
	              	$.FLAjaxConnectionError();
	              }
	             });
	         }
	    }
	});
};

$(document).ready(function(){

    Common.init();
    
    $('.form_submit').hover(
        function() {
            $(this).attr('src', Server.static_url+'/images/button_green_submit_hover.png');
        },
        function() {
            $(this).attr('src', Server.static_url+'/images/button_green_submit.png');
        });
	
	//check if the header is `tall_header`
	var isTall = $('.tall_header').length;
	if (isTall) {
		//when it's not the tall header, the page_content_container is padding:75px 0 0
		//because the header is position:absolute
		//but since the tall header is not position:absolute, we don't need that padding
		
		if ($('#page_content_container').hasClass('homepage')) {
			$('#page_content_container').css({'background-position':'100% 0','padding-top':'0'});
		}
		else {
			$('#page_content_container').css({'background-position':'100% 0','padding-top':'50px'});
		}
	}
	
    // TODO: Do we really need this? document.all?
    if (document.all) {
        $('ul.ul_links li').each(function() {
            $(this).bind('mouseover', function() { $(this).addClass('header_nav_rollover_bg');});
            $(this).bind('mouseout', function() { $(this).removeClass('header_nav_rollover_bg'); });
        });
    }
	
	//this are for form buttons that use the embossed buttons to submit its parent's form
	//the embossed buttons are <a> buttons with <span>s in it..
	//it is easier to style them than using <input> or <button>
	$('.form_submit_button').each(function(){
		$(this).click(function(){
			$(this).parents('form').submit();									   
		});
	});

    $('.ul_links a').click(function() {
        typeof(pageTracker) == 'object' && pageTracker._trackEvent('header', $(this).html());
    });

    $('#ghetto_submit_button').click(
        function() {
            // check the client side fields
            var fname = $('#first_name').val();
            var lname = $('#last_name').val();
            var email = $('#email').val();
            var offer = $("input[name='offer']:checked").val();

            var data = {};
            data.error_code = 1;
            if (fname === '' || lname === '' || email === '') {
                data.error_message = 'Please fill out all fields.';
                $.FLCheckAjaxError(data);
                return false;
            }
            else if (!EmailValidation.isValid(email)) {
                data.error_message = 'Please enter a valid email address.';
                $.FLCheckAjaxError(data);
                return false;
            }
            else if (!offer) {
                data.error_message = 'You  must select an offer';
                $.FLCheckAjaxError(data);
                return false;
            }

            // everything is ok so submit
            $('#ghetto_submit_button').addClass('_loading');
            $('#form1').ajaxSubmit({
                success : function(data){
                    if (!$.FLCheckAjaxError(data)) {
                        $("#ghetto_test").dialog("close");
                        $("#ghetto_test_result").dialog({
                            title: "Thanks",
                            modal: true,
                            autoOpen: true,
                            buttons: { "Close": function() { 
                                $(this).dialog("close"); 
                                showing_popup = false; 
                                if (typeof(Tree) != "undefined") {
                                    getBrowserSize(false);
                                }
                            }},
                            height   : 450,
                            width    : 815
                        });
                    }
                    else {
                        $('#ghetto_submit_button').removeClass('_loading');
                    }
                }
            });
        return true;
    });

    $('#popup_submit_button').click(
        function() {
            // check the client side fields
            var fname = 'unused';
            if ($('#first_name').length !== 0)
                fname=$('#first_name').val();
            var lname = 'unused';
            if ($('#last_name').length !== 0)
                lname=$('#last_name').val();
            var email = 'unused';
            if ($('#email').length !== 0)
                email=$('#email').val();
            var phone='unused';
            if ($('#phone').length !== 0)
                phone=$('#phone').val();
            var pagename = $('#pagename').val();
            var offer = $("input[name='offer']:checked").val();

            var data = {};
            data.error_code = 1;
            if (fname === '' || lname === '' || email === '') {
                data.error_message = 'Please fill out all fields.';
                $.FLCheckAjaxError(data);
                return false;
            }
            if (email!='unused' && !EmailValidation.isValid(email)) {
                data.error_message = 'Please enter a valid email address';
                $.FLCheckAjaxError(data);
                return false;
            }
            if (phone != 'unused' && phone !== '' && phone.length < 10)
                {
                    data.error_message = 'Please enter a valid phone number';
                    $.FLCheckAjaxError(data);
                    return false;

                }
            if (!offer) {
                data.error_message = 'You  must select an offer';
                $.FLCheckAjaxError(data);
                return false;
            }
            if (fname=='unused')
                fname='';
            if (lname=='unused')
                lname='';
            if (email=='unused')
                email='';
            if (phone=='unused')
                phone='';

            // everything is ok so submit
            $('#popup_submit_button').addClass('_loading');
            $("#ghetto_test").dialog("close");
            window.location="https://" + window.location.hostname + (window.location.port ? ":" + window.location.port : "") +"/subscription?offer="+offer+"&fname="+fname+"&lname="+lname+"&email="+email+"&pagename="+pagename+"&phone="+phone;
            return true;
    });

    if (($('#popup_tree').html() == 'Yes') && ($('#popup_tree_url').length)) {
        showing_popup = true;
        var popup = $("#ghetto_test");
        popup.dialog({
            title: "Special Offer",
            modal: true,
            autoOpen: false,
            buttons: { "No Thanks": function() { 
                $(this).dialog("close");
                showing_popup = false; 
                if (typeof(Tree) != "undefined") {
                    getBrowserSize(false);
                }
            }},
            minHeight: 710,
            height   : 710,
            width: 815,
            minWidth: 815,
            zIndex: 999999999
        }); 
        popup.dialog('open');
    }
    else {
        if (typeof(Tree) != "undefined") {
            getBrowserSize(false);
        }
    }

    if (typeof(Server.page) != 'undefined') {
        $('#nav_link_'+Server.page).addClass('selected');
    }

});

var Notify = {};
Notify.stream_post = function(type,passvar,url){
		$.ajax({
          type: "GET",
          url: Server.server_url+"/post_stream/ajax/postit",
          data: {type:type,passvar:passvar,url:url},
          dataType: "json",
          success: function(data){
             if (data.publish === 1) {
			   var attachment = {'name':data.name,
			                     'href':data.href,
								 'description':data.description,
								 'media':[{'type':'image','src':data.img,'href':data.href}]};
               FB.Connect.streamPublish('', attachment, null, null, null, function(response) {
                   FB.Connect.showPermissionDialog('publish_stream', function(perms) {
                       $.ajax({
                           type: 'POST',
                           url: Server.server_url+'/profile/ajax/update_missing_info',
                           data: {netdat:1, perms:perms},
                           dataType: "json",
                           success: function(data){
                               if (data == 'owned') {
                                   $('#missing_info_body').hide();
                                   $('#new_password_body').removeClass('hide');
                               }

                               if (data != 'duplicate') {
                                   MissingInfoPopup.show(true);
                               }
                           },
                           error: function(data) {
                               $.FLAjaxConnectionError();
                           }
                       });
                   });
                   if (typeof(callback) == 'function') {
                       callback(response);
                   }
               }, Server.can_auto_publish);
			 }
            }
         });
};

Notify.wall_to_wall = function(type,profile_id,url,callback){
    if (typeof(callback) == 'undefined') {
        callback = null;
    }
	$.ajax({
      type: "GET",
      url: Server.server_url+"/post_stream/ajax/postit",
      data: {type:type,profile_id:profile_id,url:url},
      dataType: "json",
      success: function(data){
         if (data.publish === 1) {
		   var attachment = {'name':data.name,
		                     'href':data.href,
							 'description':data.description,
							 'media':[{'type':'image','src':data.img,'href':data.href}]};
            FB.Connect.streamPublish('',attachment,null,data.fbid,null, function(response) {
                FB.Connect.showPermissionDialog('publish_stream', function(perms) {
                    $.ajax({
                        type: 'POST',
                        url: Server.server_url+'/profile/ajax/update_missing_info',
                        data: {netdat:1, perms:perms},
                        dataType: "json",
                        success: function(data){
                            if (data == 'owned') {
                                $('#missing_info_body').hide();
                                $('#new_password_body').removeClass('hide');
                            }

                            if (data != 'duplicate') {
                                MissingInfoPopup.show(true);
                            }
                        },
                        error: function(data) {
                            $.FLAjaxConnectionError();
                        }
                    });
                });
                if (typeof(callback) == 'function') {
                    callback(response);
                }
            }, Server.can_auto_publish);
		 }
        }
     });
};

var EmailValidation = {};
EmailValidation.isValid = function(email) {
    regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
    return regex.test(email);
};

var Log = {};
Log.event = function(event) {
	$.ajax({
	  type: "GET",
	  url: Server.server_url+"/log/ajax/"+event,
	  data: {},
	  dataType: "json",
	  success: function(data){
          //
	    }
	 });
};

// If the user is already connected with Facebook, try to log them in directly.
function fb_auto_login() {
	typeof(FB) == "object" && FB.ensureInit(function() {
		FB.cancel_auto_login = false;
		FB.Connect.get_status().waitUntilReady( function( status ) {
	    	switch ( status ) {
	        case FB.ConnectState.connected:
	        case FB.ConnectState.userNotLoggedIn:
	        		FB.Facebook.get_sessionWaitable().waitUntilReady( function (session ) {
	        			// Make sure the auto login hasn't been cancelled before redirecting.
                        if (!FB.cancel_auto_login && Server.site_url) {
                            var new_url = Server.site_url+'/login/2002.2/'+Server.next_page;
                            if (window.location.href != new_url) {
                                window.location.href = new_url;
                            }
                            else {
                                window.location.href = Server.site_url;
                            }
	        			}
	        		});
	            break;
	        case FB.ConnectState.appNotAuthorized:
	        	// Prevent infinite redirect
                if (!Server.prevent_redirect_to_allow_page) {
	        		window.location = Server.site_url+'/allow/'+Server.next_page;
	        	}
	        	break;
            default: break;
	        }
	    });
	});
}

// Allow a script to cancel the auto login if it needs to be able to handle the FB session itself.
function fb_auto_login_cancel() {
	typeof(FB) == "object" && FB.ensureInit(function() {
		FB.cancel_auto_login = true;
	});
}

function fb_auto_logout() {
    typeof(FB) == "object" && FB.ensureInit(function () {
        FB.Connect.ifUserConnected(function() {}, '___SITE_URL___/logout');
    });
}

var MissingInfoPopup = {};
MissingInfoPopup.show = function(askForPassword) {

	var popup = $('#missing_account_info_popup');

    $(popup).dialog({
    	title: 'Your Missing Details', 
        modal: true,
        width: 440,
        resizable: false, 
        dialogClass: 'ui-dialog-secure', // Add padlock of security to bottom left of dialog
        buttons: { 
       		'Cancel': function() {
           		$(popup).dialog('destroy');
           	},
            'Update Account' : function() {
            	if (askForPassword) {
            		if ($('#missing_info_body').is(":visible")) {
            			$('#missing_info_form').ajaxSubmit({
            				success: function(data){
            					if (data == 'duplicate' || data == 'noEmail') {
            						window.location.reload(true);
            					}
            					else if (!$.FLCheckAjaxError(data)) {
            						$('#missing_info_body').hide();
            						$('#new_password_body').removeClass('hide');
            					}
            				}
            			});
            		}
            		else if ($('#new_password_body').is(":visible")) {
            			$('#new_password_form').ajaxSubmit({
            				success: function(data){
            					if (!$.FLCheckAjaxError(data)) {
            						window.location.reload(true);
            					}
            				}
            			});
            		}
            	}
            	else {
            		if ($('#missing_info_body').is(":visible")) {
            			$('#missing_info_form').ajaxSubmit({
            				success: function(data){
            					if (!$.FLCheckAjaxError(data)) {
            						window.location.reload(true);
            					}
            				}
            			});
            		}
            	}
         	}
    	}
    });
    	    
   	new AjaxUpload('#upload_new_profile_pic', {
   		action: Server.server_url+'/getting_started/ajax/upload_photo',
   		name: 'profile_picture',
   		autoSubmit: true,
   		responseType: false,
   		onChange: function(file, extension){},
   		onSubmit: function(file, extension) {
   			$('#loading_text').html('Uploading...');
   			$('#upload_new_profile_pic').hide();
   		},
   		onComplete: function(file, response) {
   			$('#loading_text').html('');
   			$('#upload_new_profile_pic').show();
   			if (response) {
   		    	var r = response.split(',');
   		            
   		        if (r[1]) {
   		        	$('#profile_pic_holder').show();
   		        	$('#profile_pic_holder').attr('src',r[1]);
   		        }
   			}
   		}
   	});
   				   	     
 		// Override the default submit function	
   	$('#missing_info_form').submit(function(){
   		return false;
   	});
   	
   	$('#new_password_form').submit(function(){
   		return false;
   	});
};

/*
 * header dropdowns
 */
var HeaderDropdown = {};
HeaderDropdown.init = function(){
	var timeoutInt;
	$('.header_menu_dropdown').each(function(){
		var dropdown = $(this);
		dropdown.mouseover(function(){
			/*
			 * hide others
			 */
			$('.header_menu_dropdown').each(function(){
				if ($(this) != dropdown) {
					$(this).parent().removeClass('header_menu_dropdown_active');
				}
			});
			
			if (timeoutInt) {
				clearTimeout(timeoutInt);
			}
			dropdown.parent().addClass('header_menu_dropdown_active');
		});
		
		dropdown.mouseout(function(){
			timeoutInt = setTimeout(function(){  
				dropdown.parent().removeClass('header_menu_dropdown_active');
			}, 500);
		});
	});
	
	$('.header_menu_dropdown_links').each(function(){
		var dropdown_links = $(this);
		dropdown_links.mouseover(function(){
			if (timeoutInt) {
				clearTimeout(timeoutInt);											   
			}
			dropdown_links.parent().addClass('header_menu_dropdown_active');
		});
		
		dropdown_links.mouseout(function(){
			timeoutInt = setTimeout(function(){
				dropdown_links.parent().removeClass('header_menu_dropdown_active'); 					  
			}, 500);
		});
	});

    $('.header_menu_dropdown2_links').each(function() {
        var that = this;
        $(this).prev().mouseover(function(){
            $('.header_menu_dropdown2_links').each(function() {
                if (this != that) {
                    $(this).removeClass('header_menu_dropdown2_active');
                }
            });
            if (timeoutInt) {
                clearTimeout(timeoutInt);
            }
            $(that).addClass('header_menu_dropdown2_active');
        });

        $(this).prev().andSelf().mouseout(function() {
            timeoutInt = setTimeout(function(){
                $(this).removeClass('header_menu_dropdown2_active');
            }, 500);
        });
    });


};


$(document).ready(function() {
    HeaderDropdown.init();
});


if (signup1 == undefined) {
    var signup1 = {};
}
signup1.showLearnMore = function() {
    var text  = 'We will not store your password after we import your friends & families\' information. ';
        text += 'We may use the email addresses you upload through this importer to help you connect with';
        text += ' relatives, including using this information to generate suggestions for you and your contacts on FamilyLink.';
    $('<p class="learnMoreNote">'+text+'</p>').dialog({
        title: "Note",
        modal: true,
        resizable: false,
        width: 500,
        buttons: {
            'Ok': function() {
                $(this).dialog("close");
            }
        }
    });
};

$(document).ready(function() {
    // Replace any ajax_includes with the actual content
    $('.ajax_include').each(function() {
        var that = this;
        $.get(Server.site_url + '/common/ajax/ajax_include', { include_file : $(that).attr('include_file') }, function(result) {
            if (result.success) {
                $(that).replaceWith(result.rendered_html);
            }
        });
    });

    $('#learn_more_link').click(function(){
        signup1.showLearnMore();
        return false;
    });
});

$(function() {
    $('#popup_3day_trial').dialog({
        title: "3-Day Free Trial for Our Members",
        modal: true,
        resizable: false,
        width: 535, // 535
        height: 500, // 520
        buttons: {
            'Close': function() {
                $(this).dialog('destroy');
            }
        }
    });
});
