document.observe( 'dom:loaded', initializePage );

var SC =
{
    $ : function( id )
    {
        o_element = null;
	    css_style = '[id=' + id + ']';
        $$( css_style ).each( function( elem_iterator )
        {
            o_element = elem_iterator;
            throw $break;
        } );
        return o_element;
    },

    Form :
    {
        clearForm : function ( form )
        {
            o_form = Element.extend( form );
            o_form.getElements().each( function( elem_iterator )
            {
                SC.Form.setInputValue( elem_iterator, '' );
            } );
        },

        setInputValue : function( elem, value )
        {
            if ( elem.type == "text" )
            {
                elem.value = value;
            }
            else if ( elem.type == "radio" || elem.type == "checkbox" )
            {
                elem.checked = ( elem.value == value );
            }
            else if ( elem.type == "select-one" )
            {
                elem.selectedIndex = 0;
                for ( var i = 0; i < elem.options.length; i++ )
                {
                    if ( elem.options[i].value == value )
                    {
                        elem.selectedIndex = i;
                        break;
                    }
                }
            }
            else if ( elem.type == "select-multiple" )
            {
                for ( var i = 0; i < elem.options.length; i++ )
                {
                    elem.options[i].selected = ( elem.options[i].value == value );
                }
            }
            else if ( elem.type == "hidden" || elem.type == "button" || elem.type == "submit" ) { }
        },

        registerPhoneFields: function( base_field_name )
        {
            $( base_field_name + '_1' ).observe( 'keyup', SC.Form.fieldJump );
            $( base_field_name + '_2' ).observe( 'keyup', SC.Form.fieldJump );
        },

        fieldJump: function( event )
        {
            var o_initial_elem = event.element(); 

            // Ignore shift & tab key.  User may be trying to shift-tab backwards
            if ( event.keyCode == 9 || event.keyCode == 16 )
            {
                return;
            }

            // Don't move forward until the current field is complete
            if ( o_initial_elem.value.length < o_initial_elem.maxLength )
            {
                return;
            }

            // Get the next field based on the current tag name
            var base_field_name = o_initial_elem.id.substr( 0, o_initial_elem.id.length - 1 );
            var a_field_debris = o_initial_elem.id.split( '_' );
            var target_field_name = base_field_name + '' + ( 1 + parseInt( a_field_debris[ a_field_debris.length - 1 ] ) );

            var o_target_elem = $( target_field_name );
            if ( !o_target_elem || o_target_elem.value != "" )
            {
                return;
            }

            if ( o_target_elem.setAttribute ) { o_target_elem.setAttribute( 'autocomplete','off' ); }
            o_target_elem.focus();
        },

        disableAutoComplete: function ( field_id )
        {
            o_field = $( field_id );
            if ( o_field && o_field.setAttribute )
            {
                o_field.setAttribute( 'autocomplete','off' );
            }
        }
    },

	Text :
	{
		friendlyArrayConcat : function( a_strings, custom_comma_separator, custom_and_separator )
		{
			if( ! a_strings.length ) { return ''; }

			if( 'string' != typeof custom_comma_separator ) { custom_comma_separator = ', '; }
			if( 'string' != typeof custom_and_separator ) { custom_and_separator = ' and '; }

			last_classifier = a_strings.pop();
			if( ! a_strings.length ) { return last_classifier; }

            return a_strings.join( custom_comma_separator ) + custom_and_separator + last_classifier;
		}
	}
};

function initializePage( event )
{
    $$('.photo_thumb_container').each( function( elem_iterator )
    {
        elem_iterator.observe( 'click', swapProfilePhoto );
    } );

    $$('.has_hint').each( function( elem_iterator )
    {
        elem_iterator.observe( 'focus', showHint_event );
        elem_iterator.observe( 'blur', hideHint_event );
    } );

    $$('.has_hint_mouseover').each( function( elem_iterator )
    {
        elem_iterator.observe( 'mouseover', showHint_event );
        elem_iterator.observe( 'mouseout', hideHint_event );
    } );
	
	var o_scanalert_img = document.images[ "scanalert_img" ];
    if( o_scanalert_img )
    {
    	protocol = ( 0 == document.location.href.indexOf( 'https' ) ? 'https://' : 'http://' ); 
        document.images[ "scanalert_img" ].src = protocol + "images.scanalert.com/meter/www.sittercity.com/13.gif";
    }
	
	if( document.images )
	{
		loginBox = new Image( 275, 218 );
		loginBox.src= "/img/masthead/login_box.gif"; 
	}

}

function showHint_event( event )
{
    o_element = event.element();
    showHint( o_element.identify() );
}

function hideHint_event( event )
{
    o_element = event.element();
    hideHint( o_element.identify() );
}

function showHint( field_name )
{
    document.getElementById( 'hint_' + field_name ).className='hintcontainervisible';
}

function hideHint( field_name )
{
    document.getElementById( 'hint_' + field_name ).className='hintcontainerhidden';
}

function effectSlide( object_id )
{
    div_object = document.getElementById( object_id );
    
    if( div_object.style.display == 'none' )
    {
        new Effect.SlideDown( object_id, {queue: {position:'front', scope: object_id, limit:1} });
        if( object_id == 'new_basic_search' )
        {
            document.getElementById( 'basic_search_iframe' ).className = 'visible';
        }
    }
    else
    {
        new Effect.SlideUp( object_id, {queue: {position:'end', scope: object_id, limit:1} });
        if( object_id == 'new_basic_search' )
        {
            document.getElementById( 'basic_search_iframe' ).className = 'hidden';
        }
    }
}

function effectSlideUp( object_id )
{
    new Effect.SlideUp( object_id );
}

function effectSlideDown( object_id, finish_function )
{
	var function_options = { queue: {position:'end', scope: object_id} };

	if( finish_function )
	{
		function_options.afterFinish = finish_function;
	}

    new Effect.SlideDown( object_id, function_options );
}

function effectVisible( object_id )
{
    document.getElementById( object_id ).className = 'visible';
}

function effectHide( object_id )
{
    document.getElementById( object_id ).className = 'hidden';
}

function effectFade( fade_object_id )
{
    new Effect.Fade( fade_object_id, { duration: .5 } );
}

function effectFadeAppear( fade_object_id, appear_object_id )
{
    new Effect.Fade(fade_object_id, {duration: .5, queue: {position:'front', scope: fade_object_id, limit:2} });
    new Effect.Appear(appear_object_id, {duration: .5, queue: {position:'end', scope: fade_object_id, limit:2} });
}

function effectTransition( fade_object_id, appear_object_id )
{
    new Effect.Fade(fade_object_id, {duration: 1, queue: {position:'front', scope: fade_object_id, limit:2} });
    new Effect.Appear(appear_object_id, {duration: 1, queue: {position:'end', scope: appear_object_id, limit:2} });
}

function effectSlideAppear( slide_object_id, appear_object_id )
{
    new Effect.SlideUp( slide_object_id, {queue: {position:'end', scope: slide_object_id, limit:1} });
    new Effect.Appear(appear_object_id, {duration: .5, queue: {position:'end', scope: slide_object_id, limit:2} });
}

function effectSlideUpDown( fade_object_id, appear_object_id, finish_function )
{
	var function_options = { queue: {position:'end', scope: fade_object_id} };

	if( finish_function )
	{
		function_options.afterFinish = finish_function;
	}

	new Effect.SlideUp( fade_object_id, { queue: {position:'end', scope: fade_object_id} } );
    new Effect.SlideDown( appear_object_id, function_options );
}

function popup( url, width, height ) 
{
    window.open(url,'popup','width='+width+',height='+height+',scrollbars=yes,resizable=yes,toolbar=no,directories=no,menubar=no,status=no,left=100,top=100');
    return false;
}

function pageWidth() {return window.innerWidth != null? window.innerWidth: document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body != null? document.body.clientWidth:null;}
function pageHeight() {return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;}
function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset:document.documentElement && document.documentElement.scrollLeft? document.documentElement.scrollLeft:document.body.scrollLeft? document.body.scrollLeft:0;}
function posTop() {return typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;}
function posRight() {return posLeft()+pageWidth();}
function posBottom() {return posTop()+pageHeight();}

var button_has_been_clicked = false;

function getHasFormBeenSubmitted()
{
    return button_has_been_clicked;
}

function setHasFormBeenSubmitted()
{
    button_has_been_clicked = true;
}

function submitFormOnlyOnce( form_name )
{
    if( getHasFormBeenSubmitted() )
    {
        alert( 'This form is currently being submitted.  Please continue to hold.' );
    }
    else
    {
        if ( form_name && form_name.submit )
        {
            // form_name is actually a form object
            form_name.submit();
        }
        else
        {
            document.forms[ form_name ].submit();
        }
        setHasFormBeenSubmitted();
    }
}

function submitThisFormOnlyOnce( input_elem, action /* = null */ )
{
    o_form = getParentForm( input_elem );

    if ( action && ! getHasFormBeenSubmitted() )
    {
        // If specified, set the action
        o_form[ 'action' ].value = action;
    }

    submitFormOnlyOnce( o_form );
}

function swapUserImage( direction, total_number_of_images )
{
    current_image_number = parseFloat( document.getElementById('current_image').value );
    //total_number_of_images = <?= count( $a_photos ) ?>;

    if( direction == 'next' )
    {
        next_image_number = current_image_number + 1;
    }
    else
    {
        next_image_number = current_image_number - 1;
    }
    //document.getElementById('photo_' + current_image_number).className='hidden';
    //document.getElementById('photo_' + next_image_number).className='visibile';
    effectFadeAppear( 'photo_' + current_image_number, 'photo_' + next_image_number );
    document.getElementById('current_image').value = next_image_number;
    
    if( document.getElementById('current_image').value == 1 )
    {
        document.getElementById('image_previous').className='hidden';
    }
    else
    {
        document.getElementById('image_previous').className='visible';
    }
    
    if( document.getElementById('current_image').value == total_number_of_images )
    {
        document.getElementById('image_next').className='hidden';
    }
    else
    {
        document.getElementById('image_next').className='visible';
    }
}

function createAjaxObject() 
{
    var ajax_object;

    try
    {   // Try the standard way
        ajax_object = new XMLHttpRequest();

    } catch( trymicrosoft )
    {   // Standard way is a no go!
        try
        {   // Try Microsoft variant 1
            ajax_object = new ActiveXObject( "Msxm12.XMLHTTP" );

        } catch( othermicrosoft )
        {   // Still failure!
            try
            {   // Try Microsoft variant 2
                ajax_object = new ActiveXObject( "Microsoft.XMLHTTP" );

            } catch( failed )
            {   // Well we're just incompetent now, aren't we
                ajax_object = null;

            }
        }
    }

    if( ajax_object == null )
    {
        alert( "Error creating request object!" );
    }

    return ajax_object;
}

function sendAjaxRequestSSL( ajax_include, parameters, send_result_to ) 
{
    var ajax = createAjaxObject();
    var resistCache = new Date().getTime();
    
    url = '/ajax_dispatcher_ssl.html?ajax_include=' + ajax_include + '&' + parameters + '&send_result_to=' + send_result_to + '&dummy=' + resistCache;
    ajax.open( 'get', url, true );
    ajax.onreadystatechange = function () { handleAjaxResponse( ajax ); };
    ajax.send( null );
}

function sendAjaxRequest( ajax_include, parameters, send_result_to ) 
{
    var ajax = createAjaxObject();
    var resistCache = new Date().getTime();
    
    url = '/ajax_dispatcher.html?ajax_include=' + ajax_include + '&' + parameters + '&send_result_to=' + send_result_to + '&dummy=' + resistCache;
    ajax.open( 'get', url, true );
    ajax.onreadystatechange = function () { handleAjaxResponse( ajax ); };
    ajax.send( null );
}

function handleAjaxResponse( ajax )
{
    if( ajax.readyState == 4 )
    {
        if( ajax.status == 200 )
        {
            var response = ajax.responseText;
            var update = new Array();
            
            if( response.indexOf( '|' ) != -1 )
            {
                update = response.split( '|' );
                function_return = update[0] + '( "' + escape( update[1] ) +  '" )';
                eval( function_return );
            }
        }
        else
        {
            alert( "Error: Requested URL can not be accessed." );
        }
    }
}

function getAjaxMessageElement( o_container )
{
	// Use PrototypeJS to find a child of the container
	if( ! o_container && ! o_container.select ) { return null; }

	if( o_container.hasClassName( 'ajax_message' ) ) { return o_container; }

    var o_message_button = null;
    o_container.select( '.ajax_message' ).each( function( elem_iterator )
    {
    	o_message_button = elem_iterator;
        throw $break; // Pretend this is a "break"
    } );

    return o_message_button;
}

function focusAjaxMessage( o_container )
{
    o_message = getAjaxMessageElement( o_container );
    if( o_message )
    {
    	o_message.focus();
    }
}

// This controls the checkbox and css class for the CreateCalendar service.
function onOff( cellName, cancelBox, limit )
{
    var currentValue = document.getElementById( 'cal' + cellName ).checked;

    if( limit == 'yes' )
    {
        var oldClickCount = parseInt( document.getElementById( 'clicked_count' ).value );
        var curClickCount = 0;
    
        // Cancel the dual processing done by the onclick and actual checkbox click
        if( cancelBox == 'yes' )
        {
            if( currentValue == true )
            {
                document.getElementById( 'cal' + cellName ).checked = false;
            }
            else
            {
                document.getElementById( 'cal' + cellName ).checked = true;
            }
        }
        else
        {
            if( currentValue == true )
            {
                document.getElementById( 'cal' + cellName ).checked = false;
                document.getElementById( 'cell' + cellName ).className = 'caltd';
                curClickCount = oldClickCount - 1;
                document.getElementById( 'clicked_count' ).value = curClickCount;
                
                if( oldClickCount == 7 && curClickCount == 6 )
                {
                    // Activate all the boxes
                    for( i = 0; i < 7; i++)
                    {
                        for( j = 0; j < 8; j++)
                        {
                            document.getElementById( 'cal' + i + j ).disabled = false;
                        }
                    }
                    
                    document.getElementById( 'cal_limit_explain' ).style.color = 'black';
                    document.getElementById( 'cal_limit_explain' ).style.fontWeight = 'normal';
                }
            }
            else
            {
                if( oldClickCount != 7 )
                {
                    document.getElementById( 'cal' + cellName ).checked = true;
                    document.getElementById( 'cell' + cellName ).className = 'seltd';
                    curClickCount = oldClickCount + 1;
                    document.getElementById( 'clicked_count' ).value = curClickCount;
        
                    if( curClickCount == 7 )
                    {
                        // Deactivate all unchecked boxes
                        for( i = 0; i < 7; i++)
                        {
                            for( j = 0; j < 8; j++)
                            {
                                if( document.getElementById( 'cal' + i + j ).checked == false )
                                {
                                    document.getElementById( 'cal' + i + j ).disabled = true;
                                }
                            }
                        }
                        
                        document.getElementById( 'cal_limit_explain' ).style.color = 'red';
                        document.getElementById( 'cal_limit_explain' ).style.fontWeight = 'bold';
                    }
                }
            }
        }
    }
    else
    {
        if( currentValue == true )
        {
            document.getElementById( 'cal' + cellName ).checked = false;
            document.getElementById( 'cell' + cellName ).className = 'caltd';
        }
        else
        {
            document.getElementById( 'cal' + cellName ).checked = true;
            document.getElementById( 'cell' + cellName ).className = 'seltd';
        }
    }
}

function pleaseWait()
{
    pleaseWait('');
}

// for home page search
function pleaseWait( susan_url )
{
    if (!susan_url) { susan_url = 'img/susansearch.gif'; }
    box_height = 400;
    box_width = 400;
    window_height = ( pageHeight() / 2 ) - ( box_height / 2 ) + posTop();
    window_width = ( pageWidth() / 2 ) - ( box_width ) + posLeft();
    document.getElementById("search_status").innerHTML="<table id='searching_box' style=\"position:absolute; top:" + window_height + "px; left:" + window_width + "px; z-index: 10000; background-color: white; border: 1px solid black; width: " + box_width + "px; height: " + box_height + "px;\"><tr><td align='center' valign='middle'><br /><br /><br /><br /><div style='color: #c90;font-size: 26px;font-weight:normal;'>Please wait as we run your search...</div><img src=\"" + susan_url + "\"></td></tr></table>";
    fixIESelect( 'searching_box', true );   
}

function fixIESelect(id, state)
{
    var DivRef = document.getElementById(id);
    var IfrRef = document.getElementById('ie_div');
    if(state)
    {
        DivRef.style.display = "block";
        IfrRef.style.width = DivRef.offsetWidth;
        IfrRef.style.height = DivRef.offsetHeight;
        IfrRef.style.top = DivRef.style.top;
        IfrRef.style.left = DivRef.style.left;
        IfrRef.style.zIndex = DivRef.style.zIndex - 1;
        IfrRef.style.display = "block";
    }
    else
    {
        DivRef.style.display = "none";
        IfrRef.style.display = "none";
    }
}

// Timer alerting support staff to timing out of checked out tickets
function checkoutTimer( count )
{
    if( count == 60 )
    {
        var stopTime = new Date();
        var reset_timer = confirm( "This ticket will be checked in due to inactivity in approximately one minute.  If you need additional time, click \"OK\" to reset this timer (no unsaved changes will be lost).  If you dismiss this dialog, or don't hit \"OK\" within the next minute, be aware that other members of the support staff will be able to access this ticket and prevent you from saving any changes." );
        var restartTime = new Date();
        count -= Math.ceil( ( restartTime.getTime() - stopTime.getTime() ) / 1000 );

        if( reset_timer && count > 0 )
        {
            document.getElementById("checkout_reload").value = "yes";
            document.form.submit();
        }
    }

    if( count > 0 )
    {
        count--;
        window.setTimeout( "checkoutTimer( " + count + " )", 1000 );
    }
    else
    {
        document.getElementById("checkin_box").style.display = "block";
        return 0;
    }
}

// Jumps from the supplied phone field to the next sequential one
function phoneJump( field_root, field_number )
{
    var target_number = parseInt( field_number ) + 1;
    var target_field = document.getElementById( field_root + "_" + target_number );
    var field_value = document.getElementById( field_root + "_" + field_number ).value;
    var field_length = field_value.length;
    
    if ( field_length == 3 && target_field.value == "" )
    {
        if ( target_field.setAttribute ) { target_field.setAttribute('autocomplete','off'); }
        target_field.select();
    }
}

// Makes sure the supplied phone fields are numeric and of correct lengths
function phoneValidate( field_root )
{
    
    var valid_chars = "0123456789";
    var field_value, str_char, error_flag = "no";
    
    for( i = 1; i <= 3; i++ )
    {
        field_value = document.getElementById( field_root + "_" + i ).value;

        for( j = 0; j < field_value.length; j++ )
        {
            str_char = field_value.charAt( j );
            if( valid_chars.indexOf( str_char ) == -1 && error_flag == "no" )
            {
                error_flag = i;
            }
        }
    
        if( ( i != 3 && field_value.length != 3 && error_flag == "no" ) || ( i == 3 && field_value.length != 4 && error_flag == "no" ) )
        {
            error_flag = "length";
        }
    }
    
    if( error_flag != "no")
    {
        if( error_flag == "length" )
        {
            document.getElementById( field_root + "_length_error" ).style.display = "block";
            document.getElementById( field_root + "_num_error" ).style.display = "none";
        }
        else
        {
            document.getElementById( field_root + "_num_error" ).style.display = "block";
            document.getElementById( field_root + "_length_error" ).style.display = "none";
        }
        
        return 0;
    }
    else
    {
        document.getElementById( field_root + "_length_error" ).style.display = "none";
        document.getElementById( field_root + "_num_error" ).style.display = "none";
        
        return 1;
    }
}

// Jumps from the supplied ssn field to the next sequential one
function ssnJump( field_root, source_field_id, target_field_id )
{
    var target_field = document.getElementById( field_root + "_" + target_field_id );
    var field_value = document.getElementById( field_root + "_" + source_field_id ).value;
    var field_length = field_value.length;

    if ( source_field_id == 'first' )
    {
        if ( field_length == 3 && target_field.value == "" )
        {
            target_field.select();
        }
    }
    
    if ( source_field_id == 'second' )
    {
        if ( field_length == 2 && target_field.value == "" )
        {
            target_field.select();
        }
    }
}

// mypage referral 
function toggleReferral( fromWhom )
{
    
    if ( fromWhom == 'image')
    {
        effectFadeAppear( 'referral_image', 'referral_invite' );
        document.getElementById( 'referral_thanks' ).style.display = 'none';
    }
    
    else if ( fromWhom == 'cancel')
    {
        effectFadeAppear( 'referral_invite', 'referral_image' );
        document.getElementById( 'referral_thanks' ).style.display = 'none';
    }       
    
    else if ( fromWhom == 'sent')
    {
        effectFadeAppear( 'referral_invite', 'referral_image' );
        document.getElementById( 'referral_thanks' ).style.display = 'block';
        document.getElementById( 'invite_response' ).innerHTML = 'Invite sent successfully!';
    }
}

function petExpand( check_id, parent_array_index, form_obj )
{
    pet_check = document.getElementById( "check_group_" + check_id );

    if( pet_check.checked == true )
    {
        document.getElementById( "pet_group_" + check_id ).style.display = "block";
    }
    else
    {
        // Un-check all subcategories
        if (form_obj && window.G_types_of_pets_hierarchy_tree && G_types_of_pets_hierarchy_tree[parent_array_index])
        {
            var success = true;
            
            for (var i = 0; i < G_types_of_pets_hierarchy_tree[parent_array_index].length; i++)
            {
                var elem = form_obj.elements['a_types_of_pets_id[' + G_types_of_pets_hierarchy_tree[parent_array_index][i] + ']'];
                if (elem)
                {
                    elem.checked = false;
                }
                else
                {
                    success = false;
                }
            }

            // Hide all subcategories, if we successfully un-checked them
            if (success)
            {
                document.getElementById( "pet_group_" + check_id ).style.display = "none";
            }
        }
    }
}

function patricide( me, target )
{
	if ( me ) {
		var parent = me.parentNode;
	} else {
    	var parent = this.parentNode;
	}
    if ( confirm ('Are you sure you want to permanently remove this information?' )	)
	{
		while( parent.firstChild )
		{
			parent.removeChild( parent.firstChild );
		}
		parent.parentNode.removeChild( parent );
	}
	if (target) { $(target).focus();}
}
function premeditate()
{
    var spans = document.getElementsByTagName( "span" );

    for( var i = 0; i < spans.length; i++ )
    {
        if( spans[ i ].className == "patricide" )
        {
            spans[ i ].onclick = patricide;
        }
    }
}

function checkRange()
{
    var parentDiv   = this.parentNode;
    var a_inputs    = parentDiv.getElementsByTagName( "input" );
    
    for( var i = 0; i < a_inputs.length; i++ )
    {
        if( a_inputs[i].id == "a_rate_amount_min" )
        {
            var rate_min = a_inputs[i];
        }
        
        if( a_inputs[i].id == "a_rate_amount_max" )
        {
            var rate_max = a_inputs[i];
        }
    }
        
    if( parseInt( rate_min.value ) > parseInt( rate_max.value ) && rate_min.value != "" && rate_max.value != "" )
    {
        alert( "Your maximum rate must be greater than or equal to your minimum rate.  Erroneous rate combos will not be saved." );
        return false;
    }
}

function tabSelect( selected_li_id, search_title )
{
    //Get the name of the id prefix for this tabber's LIs and DIVs
    var prefix_key_length = selected_li_id.indexOf('_li');
    var prefix_key = selected_li_id.substr(0 , prefix_key_length);

    //Update the tabs and folders
    for ( var i=0;  li_elem = document.getElementById(prefix_key+"_li"+i);  i++ )
    {
        var li_class = '', folder_class = '';
        if (li_elem.id == selected_li_id) //Select this tab
        {
            li_class = 'selected';
            folder_class = 'tabber_folder';
        }
        else //Deselect this tab
        {
            li_class = '';
            folder_class = 'hidden';
        }
        
        li_elem.className = li_class;
        document.getElementById(prefix_key+"_folder"+i).className = folder_class;
        
    }
    $$('#city_tabber_menu li').each( function (el) {el.title = ''} );
    header_link = $$("#" + selected_li_id + " a").first();
    header_link.title = 'selected';
    link = $(search_title);
    link.focus();


}

// tabGetActiveTabIndex( prefix_key ) - Returns the active tab .... 0, 1, 2, etc
// If it cannot be found, -1 is returned.
function tabGetActiveTabIndex( prefix_key )
{
    for ( var i=0;  li_elem = document.getElementById(prefix_key+"_li"+i);  i++ )
    {
        li_class = li_elem.className;
        if (li_class == 'selected')
        {
            return i;
        }
    }
    
    //It was not found
    return -1;
}

function sidebar_click( o_active_a_tag )
{
    var div_float_clear = null;
    var li_active = o_active_a_tag.ancestors()[0];
    var active_id = o_active_a_tag.readAttribute( 'href' );

    li_active.ancestors().each( function( elem_iterator )
    {
        if ( elem_iterator.hasClassName( 'float_clear') )
        {
            div_float_clear = elem_iterator;
            throw $break; // Pretend this is a "break"
        }
    } );

    if ( !div_float_clear || !active_id )
    {
        // We couldn't find the sidebar container.  Abort!
        return;
    }

    // Drop the preceding # from the href and grab the rest
    active_id = active_id.substr(1);

    // Use Prototype to iterate over the LIs and highlight the active one
    div_float_clear.select( '.auto_sidebar ul li' ).each( function( li_iterator )
    {
        is_active = ( li_iterator == li_active );

        li_iterator.removeClassName( 'current' );
        if ( is_active )
        {
            li_iterator.addClassName( 'current' );
        }
    } );

    // Use Prototype to iterate over the DIVs and reveal the active one
    div_float_clear.select( '.auto_sidebar_page' ).each( function( div_iterator )
    {
        if ( div_iterator.identify() == active_id )
        {
            div_iterator.removeClassName( 'hidden' );
        }
        else if ( !div_iterator.hasClassName( 'hidden' ) )
        {
            div_iterator.addClassName( 'hidden' );
        }
    } );
}

function getContainerNeighbor( o_action_object, container_class, neighbor_style )
{
    return getContainerNeighbors( o_action_object, container_class, neighbor_style, true )
}

function getContainerNeighbors( o_action_object, container_class, neighbor_style, return_first_only )
{
    o_action_object = Element.extend( o_action_object );

    var o_container = null;

    // Use PrototypeJS to find the container
    o_action_object.ancestors().each( function( elem_iterator )
    {
        if ( elem_iterator.hasClassName( container_class ) )
        {
            o_container = elem_iterator;
            throw $break; // Pretend this is a "break"
        }
    } );

    if ( ! o_container )
    {
        return null; // Trouble... Abort
    }

    // Use PrototypeJS to find a child of the container
    o_neighbor_collection = o_container.select( neighbor_style );

    if ( !return_first_only )
    {
        return o_neighbor_collection;
    }

    var o_neighbor = null;
    o_neighbor_collection.each( function( elem_iterator )
    {
        o_neighbor = elem_iterator;
        throw $break; // Pretend this is a "break"
    } );
    
    return o_neighbor;
}

function clearIMGClass( o_img )
{
    if ( o_img.className )
    {
        o_img.className = "";
    }
}

function setErrorImage( o_img, alt_src )
{
    o_img.onerror = null; // Clear the event
    o_img.src = alt_src;
}

function setUserPhotoErrorImage( o_img, is_current_user, use_large_image )
{
    var photo_missing_url = '/img/profile/photo-missing-small.jpg';
    var photo_loading_url = '/img/profile/photo-loading-small.jpg';

    if ( use_large_image )
    {
        photo_missing_url = '/img/profile/photo-missing-large.jpg';
        photo_loading_url = '/img/profile/photo-loading-large.jpg';
    }

    if ( is_current_user )
    {
        setErrorImage( o_img, photo_loading_url );
    }
    else
    {
        setErrorImage( o_img, photo_missing_url );
    }
}

function constrainImage( o_img, max_width, max_height, unhide_image /* = NULL*/ )
{   
    if ( o_img.width && o_img.height)
    {
        var original_width = o_img.width,
            original_height = o_img.height;

        if ( original_width <= max_width && original_height <= max_height )
        {
            return; // The image is small enough... do nothing
        }

        var new_height, new_width;

        if ( original_width > original_height )
        {
            new_width = max_width;
            reduction = max_width / original_width;
            new_height = Math.round ( original_height * reduction );
        }
        else
        {
            new_height = max_height;
            reduction = max_height / original_height;
            new_width = Math.round ( original_width * reduction );
        }
        
        if ( new_height )
        {
            o_img.width = new_width;
            o_img.height = new_height;
        }

        if ( unhide_image )
        {
            o_img_proto = Element.extend( o_img );
            if ( o_img_proto )
            {
                o_img_proto.removeClassName( 'hidden' );
            }
        }
    }
}


function TabBlock ( position, destination_id )
{
    a = 'TabBlock';
    a = document.createElement('a');
	a.id = ('tabBlock_' + destination_id);
    a.href="#";
    a.visibility='hidden';
    Event.observe(a, 'focus', function (ev) { $(destination_id).focus(); });
    $(position).appendChild(a);
}

function Lightbox (boxID, width) 
{

	this.boxID = boxID;
	this.header; 
    this.lightbox_id= "lightbox_" + this.boxID;  
	this.width = width;
	this.origin = '';
	this.displayCallback = function () {};
	this.clearCallback = function () {};

    this.esc = function (ev) 
	{
        if (27 == ev.keyCode)
        {
            Event.stop(ev);
            this.clear();
        }
    }.bindAsEventListener(this);

    this.getHeader = function () 
		{ 
				if (! this.header )
				{
					header = $$( "#" + this.lightbox_id  + " h2" )
						.first(); 
					header.replace('<h2><a href="#" id="header_' + this.lightbox_id + '" onclick="javascript:return false;">' + header.innerHTML + '</a></h2>');
					this.header = $$( "#" + this.lightbox_id  + " h2" )
						.first(); 
					return this.header.firstDescendant();
				} else return this.header.firstDescendant();
		};
	this.display = function( origin )
	{
	    this.origin     =  origin ;
    	var lightBox    = $( this.lightbox_id );
	    var boxBg       = $( "lightbox_bg" );
    	var docDivs     = document.getElementsByTagName( "div" );
	    var ytContainer = $( "youtube_container" );
    	var ytHTML      = $( "youtube_html" );
	    var body        = document.getElementsByTagName('body');
    	
		// block tabbibf away from lightbox
        TabBlock(lightBox, this.getHeader().id);


    	// Register event handler for esc key (to disable lightbox)
    	Event.observe ( window, 'keydown', this.esc);
	    for( var i = 0; i < docDivs.length; i++ )
    	{
        	if( docDivs[ i ].id.indexOf( "lightbox_" ) === 0 )
	        {
    	        if( docDivs[ i ] != lightBox )
        	    {
            	    docDivs[ i ].className = "lightbox_off";
	            }
    	    }
	    }
    	var newMargin               = ( 830 - this.width ) / 2;
	    lightBox.className          = "lightbox_on lightbox_select";
    	lightBox.style.width        = this.width + "px";
	    lightBox.style.marginLeft   = newMargin.toFixed( 0 ) + "px";
    	boxBg.className             = "lightbox_bg_on";
    
	    body[0].className = body[0].className + " lightbox_no_select";
    
    	if( this.boxID == "video" && ytContainer )
	    {
    	    ytContainer.innerHTML = ytHTML.innerHTML;
        	setTimeout( 
				function () 
				{
					$( 'lightbox_bg' ).style.zIndex = 999; 
				}, 
			500 ); // Fix insane youtube/firefox bug
	    }
    	// Scroll to the box in pre-IE-7
	    if( !window.XMLHttpRequest && ! $('lightbox_abandon') )
    	{
        	scroll( 0, 200 );
	    }
   		if (this.displayCallback) 
		{
		    this.displayCallback();
		}
 
	    //
    	//Jump to Lightbox Header
        this.getHeader().focus();
	};

	this.clear = function()
	{
	    var boxBg       = $( "lightbox_bg" );
    	var ytContainer = $( "youtube_container" );
    	var docDivs     = document.getElementsByTagName( "div" );
	    var body        = document.getElementsByTagName('body');

    	for( var i = 0; i < docDivs.length; i++ )
	    {
    	    if( docDivs[ i ].id.indexOf( "lightbox_" ) >= 0 )
        	{
            	docDivs[ i ].className = "lightbox_off lightbox_no_select";
	        }
    	}
    
	    boxBg.className = "lightbox_bg_off";

    	if( ytContainer )
    	{
        	ytContainer.innerHTML = "";
	    }
    
    	body[0].className = "";
    	checkClient();

        if (this.origin) {
            $(this.origin).focus();
        }    

    	Event.stopObserving( window, 'keydown', this.esc);
		if (this.clearCallback) 
		{
			this.clearCallback();
		}
	};
	this.registerDisplayCallback = function ( callback ) 
	{
		this.displayCallback = callback.bind(this);
	};
	
	this.registerClearCallback = function ( callback ) 
	{
		this.clearCallback = callback.bind(this);
	};
}

function displayLightbox( boxID, width )
{
    var lightBox    = document.getElementById( "lightbox_" + boxID );
    var boxBg       = document.getElementById( "lightbox_bg" );
    var docDivs     = document.getElementsByTagName( "div" );
    var ytContainer = document.getElementById( "youtube_container" );
    var ytHTML      = document.getElementById( "youtube_html" );
    var body        = document.getElementsByTagName('body');

    for( var i = 0; i < docDivs.length; i++ )
    {
        if( docDivs[ i ].id.indexOf( "lightbox_" ) === 0 )
        {
            if( docDivs[ i ] != lightBox )
            {
                docDivs[ i ].className = "lightbox_off";
            }
        }
    }

    var newMargin               = ( 830 - width ) / 2;
    lightBox.className          = "lightbox_on lightbox_select";
    lightBox.style.width        = width + "px";
    lightBox.style.marginLeft   = newMargin.toFixed( 0 ) + "px";
    boxBg.className             = "lightbox_bg_on";
    
    body[0].className = body[0].className + " lightbox_no_select";
    
    if( boxID == "video" && ytContainer )
    {
        ytContainer.innerHTML = ytHTML.innerHTML;
        setTimeout( "document.getElementById( 'lightbox_bg' ).style.zIndex = 999", 500 ); // Fix insane youtube/firefox bug
    }

    // Scroll to the box in pre-IE-7
    if( !window.XMLHttpRequest && ! document.getElementById('lightbox_abandon') )
    {
        scroll( 0, 200 );
    }

    
    //
    //Jump to Lightbox Header

}

function clearLightbox()
{
    var docDivs     = document.getElementsByTagName( "div" );
    var boxBg       = document.getElementById( "lightbox_bg" );
    var ytContainer = document.getElementById( "youtube_container" );
    var body        = document.getElementsByTagName('body');

    for( var i = 0; i < docDivs.length; i++ )
    {
        if( docDivs[ i ].id.indexOf( "lightbox_" ) >= 0 )
        {
            docDivs[ i ].className = "lightbox_off lightbox_no_select";
        }
    }
    
    boxBg.className = "lightbox_bg_off";

    if( ytContainer )
    {
        ytContainer.innerHTML = "";
    }
    
    body[0].className = "";
    checkClient();

}

function navExpand( expand_name, headerObj )
{
    if( expand_name )
    {
        var listItems = document.getElementsByTagName( "li" );
    
        for( var i = 0; i < listItems.length; i++ )
        {
            if( listItems[ i ].id.indexOf( expand_name ) >= 0 )
            {
                if( listItems[ i ].style.display == "none" )
                {
                    listItems[ i ].style.display = "block";
                    headerObj.style.color = "#333333";
                }
                else
                {
                    listItems[ i ].style.display = "none";
                    headerObj.style.color = "#37639E";
                }
            }
        }
    }
}

function hoverOpaque( element )
{
    element = Element.extend( element );

    if ( element.hasClassName( "translucent" ) )
    {
        element.removeClassName( "translucent" );
        element.addClassName( "opaque" );
    }
    else
    {
        element.removeClassName( "opaque" );
        element.addClassName( "translucent" );
    }
}

function getParentForm( input_elem )
{
    //Bubble up until we find the form that contains the input that raised the event
    o_input_elem = Element.extend( input_elem );

    if ( o_input_elem.tagName == 'FORM' )
    {
        return o_input_elem;
    }

    o_form_elem = null;
    o_input_elem.ancestors().each( function( elem_iterator )
    {
        if ( elem_iterator.tagName == 'FORM' )
        {
            //we found the form!
            o_form_elem = elem_iterator;
            throw $break; // Pretend this is a "break"
        }
    } );

    return o_form_elem;
}

function submitPagination( input_elem )
{
    if ( getHasFormBeenSubmitted() ) { return; }

    o_form_elem = getParentForm( input_elem );
    if ( ! o_form_elem ) { return; }

    var last_page = 1;
    o_form_elem.select('.lastpagenum').each( function( elem_iterator )
    {
        last_page = parseInt( elem_iterator.innerHTML );
        throw $break; // Pretend this is a "break"
    } );

    o_page_elem = Element.extend( o_form_elem.elements['page'] );
    var go_page = parseInt( o_page_elem.value );
    if ( isNaN( go_page ) )
    {
        o_page_elem.addClassName( 'bad_field' );
        o_page_elem.focus();
        alert( "Please enter a valid page number." );
        o_page_elem.removeClassName( 'bad_field' );
        return;
    }
    else if ( go_page > last_page )
    {
        o_page_elem.value = last_page;
    }

    o_form_elem.submit();
    setHasFormBeenSubmitted();
}

function submitSort( input_elem )
{
    if ( getHasFormBeenSubmitted() ) { return; }

    o_input_elem = Element.extend( input_elem );

    if ( $F( o_input_elem.identify() ) > 0 )
    {
        o_form_elem = getParentForm( o_input_elem );
        if ( o_form_elem )
        {
            o_form_elem.action += '&' + o_form_elem.serialize();
            o_form_elem.submit();
            setHasFormBeenSubmitted();
        }
    }
}

function scrollProfileThumbs( direction )
{
    var thumbContainer  = document.getElementById( 'photo_thumbs_row' );
    var maxScroll       = parseInt( document.getElementById( 'thumb_scroll_max' ).value );
    var curPosition     = parseInt( document.getElementById( 'thumb_scroll_cur' ).value );
    var leftArrow       = document.getElementById( 'photo_scroll_left' );
    var rightArrow      = document.getElementById( 'photo_scroll_right' );
    
    if( direction == "right" )
    {
        thumbContainer.style.top = ( curPosition - 64 ) + "px";
        document.getElementById( 'thumb_scroll_cur' ).value = curPosition - 64;
    }
    else if( direction == "left" )
    {
        thumbContainer.style.top = ( curPosition + 64 ) + "px";
        document.getElementById( 'thumb_scroll_cur' ).value = curPosition + 64;
    }

    curPosition = parseInt( document.getElementById( 'thumb_scroll_cur' ).value );

    if( curPosition + maxScroll == 0 )
    {
        rightArrow.className = "photo_scroll_right_dim";
        rightArrow.onclick = "";
    }
    else
    {
        rightArrow.className = "photo_scroll_right";
        rightArrow.onclick = function() { scrollProfileThumbs( 'right' ); };
    }

    if( curPosition == 0 )
    {
        leftArrow.className = "photo_scroll_left_dim";
        leftArrow.onclick = "";
    }
    else
    {
        leftArrow.className = "photo_scroll_left";
        leftArrow.onclick = function() { scrollProfileThumbs( 'left' ); };
    }

}

function swapProfilePhoto()
{
    var photoID         = this.id.substring( 6 );
    var photoContainer  = document.getElementById( 'photo_container' );
    var thumbContainer  = document.getElementById( 'photo_thumbs_row' );
    var aPhotos         = photoContainer.getElementsByTagName( 'img' );
    var aThumbs         = thumbContainer.getElementsByTagName( 'div' );
    
    for( var i = 0; i < aPhotos.length; i++ )
    {
        if( aPhotos[ i ].id == "photo_" + photoID )
        {
            aPhotos[ i ].className = "visible_inline";
        }
        else
        {
            aPhotos[ i ].className = "hidden";
        }
    }
    
    for( var i = 0; i < aThumbs.length; i++ )
    {
        if( aThumbs[ i ].id == "thumb_" + photoID )
        {
            aThumbs[ i ].className = "photo_thumb_container_current";
            aThumbs[ i ].onclick = "";
        }
        else
        {
            aThumbs[ i ].className = "photo_thumb_container";
            aThumbs[ i ].onclick = swapProfilePhoto;
        }
    }

}

function toggleVisibility( o_element, visible )
{
    if ( visible )
    {
        o_element.removeClassName( "hidden" );
    }
    else
    {
        o_element.addClassName( "hidden" );
    }
}

function cloneSelect( input_elem )
{
    o_cloneable_select_row = getContainerNeighbor( input_elem, 'cloneable_select_container', '.cloneable_select_row' );

    if ( ! o_cloneable_select_row ) { return; } //Couldn't find the cloneable prototype

    // Cycle through all visible cloned select rows, and add this one after the last one
    o_last_cloned_select_row = null;
    new_id = 1;
    o_cloned_select_row_collection = getContainerNeighbors( input_elem, 'cloneable_select_container', '.cloned_select_row' );
    o_cloned_select_row_collection.each( function( elem_iterator )
    {
    	new_id++;
        o_last_cloned_select_row = elem_iterator;
    } );
    if ( ! o_last_cloned_select_row ) { return; } //Couldn't find the last cloned select row

    old_id = o_cloneable_select_row.select( 'select' ).first().identify();
    new_id = old_id + '_' + new_id;
    new_content = o_cloneable_select_row.innerHTML.replace( new RegExp( old_id, 'g' ), new_id );

    new_cloned_select_row = new Element( 'div', { 'class': 'cloned_select_row' } );
    new_cloned_select_row.update( new_content );

    o_last_cloned_select_row.insert( { after: new_cloned_select_row } );
    setTimeout( '$( new_id ).focus();', 200 );
}

//Clears the content of a textarea/input on first focus.
function clearInput (e) {
    if (e.tagName == 'TEXTAREA' ||
        e.tagName == 'INPUT' ) {
        e.value = '';
        e.onfocus = '';
    }
}

// Submit the a quick poll and get the poll results
function submitQuickPoll( action )
{
    if( action == 'submit' )
    {
        var quickPollID     = document.getElementById( 'quick_poll_id' ).value;
        var quickPollType   = document.getElementById( 'quick_poll_type' ).value;
        var quickPollRoleID = document.getElementById( 'quick_poll_role_id' ).value;
        var quickPollUserID = document.getElementById( 'quick_poll_user_id' ).value;
        var pollContainer   = document.getElementById( 'quick_poll' );
        var queryString     = 'poll_id=' + quickPollID + '&poll_type=' + quickPollType + '&role_id=' + quickPollRoleID + '&user_id=' + quickPollUserID;
        var baseQueryString = queryString;
        
        switch( quickPollType )
        {
            case 'RADIO':
            case 'CHECKBOX':

                var pollChoices     = pollContainer.getElementsByTagName( 'input' );
                
                for( var i = 0; i < pollChoices.length; i++ )
                {
                    if( pollChoices[ i ].checked )
                    {
                        queryString += '&answer[]=' + pollChoices[ i ].value;
                    }
                }

            break;
            
            case 'TEXT':

                var pollText        = pollContainer.getElementsByTagName( 'textarea' );

                if( pollText[ 0 ].value )
                {
                    queryString += '&answer=' + escape( pollText[ 0 ].value );
                }

            break;

        }
        
        if( queryString == baseQueryString )
        {
            alert( 'Please provide a response before submitting.' );
        }
        else
        {
            sendAjaxRequest( 'quick_poll_results', queryString, 'handleQuickPollResults' );
        }

    }
    else
    {
        var quickPollRoleID = document.getElementById( 'quick_poll_role_id' ).value;
        var queryString     = 'role_id=' + quickPollRoleID;

        sendAjaxRequest( 'quick_poll_results', queryString, 'handleQuickPollResults' );
    }
    
}

// Insert the results of a quick poll back into the site
function handleQuickPollResults( resultText )
{
    if( resultText )
    {
        document.getElementById( 'quick_poll' ).innerHTML = unescape( resultText );
        setTimeout( "focusAjaxMessage( $( 'quick_poll_heading' ) );", 200 );
    }
}

// Handles focus on hover of promotions
function promotionHover( promotionModule, promotionID )
{
	// Don't do in IE6, causes horrible flicker
	
	if( window.XMLHttpRequest )
	{
		var promo = $( promotionID );

		if( promo.checked != true )
		{
			if( promotionModule.className == 'module parent_mod' )
			{
				promotionModule.className = 'module parent_focus_mod';
			}
			else if( promotionModule.className == 'module parent_focus_mod' )
			{
				promotionModule.className = 'module parent_mod';
			}
		}
	}
}

// Selects a promotion
function promotionSelect( promotionModule, promotionID )
{
	var promotionFieldset = $( 'promotions' );
	var inputs	= promotionFieldset.getElementsByTagName( 'input' );
	var divs	= promotionFieldset.getElementsByTagName( 'div' );
	var module;
	
	for( var i = 0; i < inputs.length; i++ )
	{
		if( inputs[ i ].id.substr( 0, 6 ) == 'merch_' )
		{
			module = $( inputs[ i ].id );
			
			if( module.id == promotionID )
			{
				module.checked = true;
			}
			else
			{
				module.checked = false;
			}
		}
	}
	
	for( var i = 0; i < divs.length; i++ )
	{
		if( divs[ i ].className == 'module parent_focus_mod' )
		{
			divs[ i ].className = 'module parent_mod'
		}
		
		if( divs[ i ].id.substr( 0, 11 ) == 'learn_more_' )
		{
			if( divs[ i ].id.substr( 11 ) != promotionID.substr( 6 ) )
			{
				divs[ i ].style.display = 'none';
			}
		}
	}

	promotionModule.className = 'module parent_focus_mod'

}

// Displays or hides "learn more" boxes for promotions
function learnMore( learnMoreID )
{
	var promotionFieldset = $( 'promotions' );
	var divs	= promotionFieldset.getElementsByTagName( 'div' );

	for( var i = 0; i < divs.length; i++ )
	{
		if( divs[ i ].id.substr( 0, 11 ) == 'learn_more_' )
		{
			if( divs[ i ].id == learnMoreID && divs[ i ].style.display != 'block' )
			{
				divs[ i ].style.display = 'block';
				var learnMoreHeader = divs[ i ].getElementsByTagName( 'h3' );
				var learnMoreHeaderLink = learnMoreHeader[0].getElementsByTagName( 'a' );
				learnMoreHeaderLink[0].focus();
			}
			else
			{
				divs[ i ].style.display = 'none';
			}
		}
	}
}

function selectCreditCard( card )
{
	var card_graphic_1 = $( 'cc_security_img_1' );
	var card_graphic_2 = $( 'cc_security_img_2' );
	
	if( card.value == 'amex' )
	{
		card_graphic_1.className = 'hidden';
		card_graphic_2.className = 'visible';
	}
	else
	{
		card_graphic_1.className = 'visible';
		card_graphic_2.className = 'hidden';
	}
}

function displayLoginBox()
{
	var loginBox = $( 'login' );
	
	if( loginBox.className != 'visible' )
	{
		loginBox.className = 'visible';
		setTimeout( "$( 'sign_in_username' ).focus();", 200 );
	}
	else
	{
		loginBox.className = 'hidden';
		$( 'login_button' ).focus();
	}
}

function prepResultPhotos( photoID )
{
	prepSizedResultPhotos( photoID, 150, 170 )	
}

function prepSmallResultPhotos( photoID )
{
	prepSizedResultPhotos( photoID, 53, 61 )	
}

function prepSizedResultPhotos( photoID, maxWidth, maxHeight )
{
	var photo		= document.images[ photoID ];
	var photoWidth	= parseInt( photo.width );
	var photoHeight	= parseInt( photo.height );
	var newWidth, newHeight;
	
	if( photoWidth <= maxWidth && photoHeight <= maxHeight )
	{
		newWidth	= photoWidth;
		newHeight	= photoHeight;
	}
	else if( photoWidth / maxWidth > photoHeight / maxHeight )
	{
		newWidth	= maxWidth;
		newHeight	= Math.floor( ( maxWidth / photoWidth ) * photoHeight ) ;
	}
	else if( photoWidth / maxWidth < photoHeight / maxHeight )
	{
		newWidth	= Math.floor( ( maxHeight / photoHeight ) * photoWidth ) ;
		newHeight	= maxHeight;
	}
	else
	{
		newWidth	= maxWidth;
		newHeight	= maxHeight;
	}

	if( maxWidth % 2 != newWidth % 2 )
	{
		newWidth--;
	}

	if( maxHeight % 2 != newHeight % 2 )
	{
		newHeight--;
	}

	photo.width		= newWidth;
	photo.height	= newHeight;
	
	photo.style.marginTop = Math.floor( ( maxHeight - newHeight ) / 2 ) + "px";
	
	if( photo.className == "photo_loading" )
	{
		photo.className = '';	
	}

}

var globalFieldName;

function displayFieldsetExample( fieldName )
{
	var exampleBox = $( 'ex_' + fieldName );
	
	if( exampleBox.style.display != 'block' )
	{
		globalFieldName = fieldName;
		exampleBox.style.display = 'block';
		setTimeout( "$( 'ex_' + globalFieldName + '_focus' ).focus();", 200 );
	}
	else
	{
		exampleBox.style.display = 'none';
		$( 'ex_' + fieldName + '_link' ).focus();
	}
}

function checkClient()
{
	var bodyTag = document.getElementsByTagName( 'body' );

	if( navigator.appVersion.indexOf( 'Win' )!= -1 )
	{
		bodyTag[0].className = 'os_win';
	}
	else if( navigator.appVersion.indexOf( 'Mac' )!= -1 )
	{
		bodyTag[0].className = 'os_mac';
	}
	else if( navigator.appVersion.indexOf( 'X11' )!= -1 )
	{
		bodyTag[0].className = 'os_unix';
	}
	else if( navigator.appVersion.indexOf( 'Linux' )!= -1 )
	{
		bodyTag[0].className = 'os_linux';
	}

}

//////////////////////////////////////
// Begin Shared Functions           //
// These functions are available in //
// the site, blog and CMS           //
//////////////////////////////////////

if( ! document.SCCommon )
{
	SCCommon =
	{
		isLive : function()
		{
			return document.location.hostname.indexOf( "local" ) == -1
				&& document.location.hostname.indexOf( "cms" ) == -1
				&& document.location.hostname.indexOf( "qa" ) == -1;
		},

		// Return all values in the document cookie
		// Be fore-warned that associative arrays do not report the array.length property correctly!
		getAssociativeCookieArray : function()
		{
			if( document.G_a_cookies ) { return document.G_a_cookies; }

			var rawCookieVars = document.cookie.split( ';' );
			var cookieVars = new Array();

			for( var i = 0; i < rawCookieVars.length; i++ )
			{
				var rawCookieVar = rawCookieVars[ i ];

				while( rawCookieVar.charAt( 0 ) == ' ' )
				{
					rawCookieVar = rawCookieVar.substring( 1, rawCookieVar.length );
				}

				var cookieBits = rawCookieVar.split( '=' );
				cookieVars[ cookieBits[ 0 ] ] = unescape( cookieBits[ 1 ] );
			}

			return document.G_a_cookies = cookieVars;
		},

		setCookieValue : function( name, value, number_of_days )
		{
			assignment_property = name + '=' + escape( value );

			expires_property = '';
			if( number_of_days )
			{
				// If number_of_days is non-empty, this is longer than a session-only cookie
				var expDate = new Date();
				expDate.setTime( expDate.getTime() + ( number_of_days * 24 * 60 * 60 * 1000 ) );
				expires_property = '; expires=' + expDate.toGMTString();
			}

			cookie_payload = assignment_property + expires_property + '; path=/; domain=.sittercity.com';
			document.cookie = cookie_payload;
		},

		//Return all values in the URL querystring
		//Be fore-warned that associative arrays do not report the array.length property correctly!
		getAssociativeQueryStringArray : function( qs )
		{
			if ( !qs ) 
			{
				qs = '&' + document.location.search.replace( /\?/g, '&' ) + '&';
			}
			a_get = new Array();
			a_get_pairs = qs.split( '&' );
			for( i = 0; i < a_get_pairs.length; i++ )
			{
				a_pair = a_get_pairs[ i ].split( '=' );
				if( a_pair.length == 2 )
				{
					a_get[ a_pair[ 0 ] ] = unescape( a_pair[ 1 ].replace( /\+/g,' ' ) );
				}
			}
			return a_get;
		}
	};
}


var UserExperienceCookieModel =
{
	COOKIE_NAME:			'ruexp',

	KEY_STATUS:				0,
	KEY_LAST_VISIT:			1,
	KEY_EXPIRE:				2,
	KEY_SEARCH_CARETYPE:	3,
	KEY_SEARCH_ZIP:			4,

	a_cookie_value:			[ 0, 0, 0, 0, 0 ],

	execute: function()
	{
		this.setValuesFromCookie();
	},

	setValuesFromCookie: function()
	{
		a_cookies = SCCommon.getAssociativeCookieArray();
		cookie_data = a_cookies[ this.COOKIE_NAME ] + '';
		this.a_cookie_values = cookie_data.split( '|' );
	}
};


var SurveyPopupCriteriaModel =
{
	GROUP_CONTROL:			1,
	GROUP_EXPERIMENT:		2,
	GROUP_EXPERIMENT_DONE:	3,
	COOKIE_NAME:			'SurveyPopupGroup',
	COOKIE_LIFE_DAYS:		30,

	percentage: null,

	execute: function( percentage, membership_type_id )
	{
		this.percentage = percentage;

		if( membership_type_id )
		{
			// Existing users do not get the survey
			return;
		}

		var group = this.loadGroup();
		if( ! group )
		{
			group = this.flipCoin() ? this.GROUP_EXPERIMENT : this.GROUP_CONTROL;
		}
		SurveyPopupCriteriaModel.persistGroup( group );

		if( group == this.GROUP_EXPERIMENT && this.isPathEligible( document.location.pathname ) )
		{
			// The pop-up trap gets set now
			this.register_trap();
		}
	},

	loadGroup: function()
	{
		a_cookies = SCCommon.getAssociativeCookieArray();
		return a_cookies[ this.COOKIE_NAME ] * 1;
	},

	persistGroup: function( group )
	{
		// Store the group in a cookie for 30 days
		SCCommon.setCookieValue( SurveyPopupCriteriaModel.COOKIE_NAME, group, SurveyPopupCriteriaModel.COOKIE_LIFE_DAYS );
	},

	flipCoin: function()
	{
		return Math.random() * 100 < this.percentage;
	},

	isPathEligible: function( path )
	{
		patterns = this.getEligiblePaths();
		paths_pattern = patterns.join( '|' );
		o_paths_regex = new RegExp( paths_pattern );
		return o_paths_regex.test( path );
	},

	getEligiblePaths: function()
	{
		var paths = [];

		/*
		paths.push( '^\\/$' );
		paths.push( '^\\/child-care-babysitters\\.html$' );
		paths.push( '^\\/nanny\\.html$' );
		paths.push( '^\\/pet-sitters\\.html$' );
		paths.push( '^\\/senior-care\\.html$' );
		paths.push( '^\\/housekeepers\\.html$' );
		paths.push( '^\\/tutoring\\.html$' );
		*/

		paths.push( '^\\/register_parent_1\\.html$' );
		/*
		paths.push( '^\\/register_parent_2\\.html$' );
		paths.push( '^\\/reg_sitter_1\\.html$' );
		paths.push( '^\\/reg_sitter_2\\.html$' );
		paths.push( '^\\/reg_sitter_3\\.html$' );

		paths.push( '^\\/search_sitters\\.html$' );
		paths.push( '^\\/us\\/[a-z\\-]+-[0-9]{5}\\/[a-z]{2}\\/[a-z\\-]+$' );

		paths.push( '^\\/profile\\/[0-9]+\\.html$' );
		*/

		return paths;
	},

	register_trap: function()
	{
		SurveyPopupCriteriaModel.load_prototype();

		document.staying_in_site = true;

		SurveyPopupCriteriaModel.add_event(
			window, 'load', SurveyPopupCriteriaModel.observe_clicks
		);
		SurveyPopupCriteriaModel.add_event(
			window, 'beforeunload', SurveyPopupCriteriaModel.popup_survey
		);
		SurveyPopupCriteriaModel.add_event(
			window, 'submit', SurveyPopupCriteriaModel.nopop_onsubmit
		);
	},

  add_event: function(obj, evType, fn)
	{ 
    if (obj.addEventListener){ 
      obj.addEventListener(evType, fn, false); 
      return true; 
    } else if (obj.attachEvent){ 
      var r = obj.attachEvent("on"+evType, fn); 
      return r; 
    } else { 
      return false; 
    } 
  },

  load_prototype: function() 
	{
    if ( ! window.Prototype)
    {
      head = document.getElementsByTagName('head')[0];
      var pt = document.createElement('script'); 
      pt.type = 'text/javascript';
      pt.src  = 'http://sittercity.cachefly.net/javascript/effects/prototype.js?v=1F';
      head.appendChild(pt);
    }
  },

	observe_clicks: function() {
		document.staying_in_site = false;
		Event.observe(
		document.body, 'click', function(event) {
			if (Event.element(event).tagName == 'A' || 
				Event.element(event).tagName == 'IMG' ||
				Event.element(event).tagName == 'SPAN' ||
				Event.element(event).tagName == 'INPUT')
			{
				document.staying_in_site = true;
			}
		});
	},

	nopop_onsubmit: function() {
		document.staying_in_site = true;
	},

	popup_survey: function () {
		if(document.staying_in_site) {
			return;
		}
		url = '/surveya.html';
		var width = 800;
		var height = 600;
		var left = parseInt((screen.availWidth/2) - (width/2));
		var top = parseInt((screen.availHeight/2) - (height/2));
		var windowFeatures = "width=" + width + ",height=" + height + 
			",left=" + left + ",top=" + top + ",scrollbars=1";
		window.open(url, 'Survey', windowFeatures);
		SurveyPopupCriteriaModel.persistGroup
		(
			SurveyPopupCriteriaModel.GROUP_EXPERIMENT_DONE
		);
	}
};


(
	function()
	{
		var survey_popup_percentage = 100;
		UserExperienceCookieModel.execute();
		var experience_membership_type_id
			= UserExperienceCookieModel.a_cookie_values
			[
				UserExperienceCookieModel.KEY_STATUS
			] * 1;

		SurveyPopupCriteriaModel.execute
		(
			survey_popup_percentage,
			experience_membership_type_id
		);
	}
)();

//////////////////////////////////////
// End Shared Functions             //
// These functions are available in //
// the site, blog and CMS           //
//////////////////////////////////////

