<?php $__env->startSection('page_title'); ?>
    OSAA - Manage Web Ads
<?php $__env->stopSection(); ?>

<?php $__env->startSection('page_sub_title'); ?>    
    Manage Website Advertisements
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
    @parent

    <style type="text/css">
    	h2 {
            color: #1C43A6 !important;
        }

        h2.line {
            border-bottom: 1px solid #1C43A6;
            padding-bottom: 0.25em;
            margin-bottom: 0.25em;
        }

        h3 {
            color: #990000 !important;
        }

        .no-close .ui-dialog-titlebar-close {
            display: none;
        }

    	.success_bar {
    		position: fixed;
    		top: 600px;
    		left: 0;
    		width: 100%;
    		padding: 0.25em 0;
    		line-height: 1.5em;
    		background-color: rgba(176, 255, 190, 0.0);
    		border-bottom: 2px solid rgba(13, 88, 27, 0.50);
    		border-top: 2px solid rgba(13, 88, 27, 0.50);
    		z-index: 500;
    	}

    	.success_bar .message {
    		width: 1200px;
    		margin: 0 auto;
    		font-size: 14pt;
    		color: #151515;
    	}    	

    	.page_functions {
    		width: auto !important;
    	}  
      

        label, .label {            
            font-weight: bold;
            font-size: 7pt;
            display: block;
            margin: 3px 0 -3px 0;
        }  


        
        


    </style>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('jquery_init'); ?>	        
    
    if(!window.console)
    {
        window.console = { log: $.noop, group: $.noop, groupEnd: $.noop };            
    }

	// Success bar
	$('.success_bar').animate({ 'top' : 32, 'background-color' : 'rgba(176, 255, 190, 1.0)'}, 1600, 'easeOutQuad', function ()
	{		
		$(this).delay(6000).fadeOut(4000);	

		$(this).hover(function ()
		{
			$(this).stop(true).css('opacity', '1.0');
		},
		function ()
		{
			$(this).fadeOut(4000);
		})
	});  
    


    /* 
     * Custom tooltip items
     */
    $('[data-tooltip]').each(function ()
    {
        var item = $(this);

        var help = item.attr('data-tooltip');
        
        item.tooltip({'content' : help, 'items' : item});
    });
    

    /* Positioned elements
     *
     * Elements that contain the attribute data-position="true" will be positioned
     * using JQuery's UI positioning utility.  Other expected attributes define the
     * element's position:
     *    data-position-my
     *    data-position-at
     *    data-position-of
     */
    $('[data-position="true"]').each(function()
    {
        var element = $(this);
        var my = element.attr('data-position-my');
        var at = element.attr('data-position-at');
        var of = element.attr('data-position-of');

        var options = $.parseJSON('{ "my" : "' + my + '", "at": "' + at + '", "of": "' + of + '"}');

        element.position(options);
    });

   
        
    // Table row highlighter
    function colorRows ()
    {       
        $('table').each(function ()
        {
            var i = 0;

            $('tbody tr:visible', $(this)).each(function ()
            {
                if (i % 2 == 1)
                {
                    $(this).addClass('odd');
                }
                else
                {
                    $(this).removeClass('odd');
                }
                i = i + 1;
            });     
        });
    }   
    colorRows(); 


    /*
     * Auto-complete text fields
     */
    $('input[type="text"][data-autocomplete]')
        .each(function()
        {            
            $(this).autocomplete({'source' : $(this).attr('data-source'),
                                  'minLength' : 3});
        });


    /* alertRequiredField
     *
     * Shows an alert box when attempting to save a blank value to a required field.
     */
    function alertRequiredField()
    {
        $('<div></div>')
            .appendTo('body')
            .dialog(
            {                       
                modal : true,
                draggable : false,
                resizable : false,                    
                height : 275,                    
                width : 415,                    
                title : 'Required Field',                    
                buttons: [
                    {
                        text : "OK",
                        'class' : "float_right",
                        icons : { primary : 'ui-icon-check'},
                        click : function()
                                {                                                       
                                    // Close the dialog box
                                    $(this).dialog("close"); 
                                }
                    }
                ],
                open : function ()
                    {  
                        var dialog_object = $(this);

                        dialog_object.html('<br />You\'ve entered in a blank value for a required field.  Required fields cannot be empty.<div style="font-size: 9pt; margin-top: 1em;" class="small gray note">The original value has been restored.</div>');
                        
                        $('.ui-dialog-buttonpane').css('padding', '0 0.5em').css('font-size', '9pt');
                        $('.ui-dialog-buttonpane .ui-dialog-buttonset').css('width', '100%');
                        $('.ui-dialog-buttonpane .ui-dialog-buttonset').append('<div style="font-size: 8pt; line-height: 1.25em; margin-top: 0.5em;">Still having trouble?<br />(503) 682-6722 x228</div>');
                    },                    
                close : function ()
                    {
                        var dialog_object = $(this);
                        $(dialog_object).remove();
                    }                
            });
    }


    /* saveFormData
     *
     * Given a form field and a value, this function will do a
     * JSON POST request to save the ads's information.  The optional
     * third parameter will determine if the page will be reloaded or not.
     */
    function saveFormData(ad_id, field, value, type, reload)
    {
        // Ensure the field and value parameters are provided
        if (typeof field == 'undefined' || typeof value == 'undefined' || typeof type == 'undefined')
        {
            alert('Scripting error.  Unable to save form data.');
        }

        // Get the optional reload parameter
        reload = typeof reload !== 'undefined' ? reload : false;        

        $('*').css({'cursor':'wait'});

        var jqxhr = $.ajax(
        {
            type : 'POST',                      
            url : '<?php echo url('/admin/ads'); ?>/' + ad_id + '/update',
            data : { 'verify_id' : ad_id,
                     'field' : field,
                     'value' : value,
                     'type'  : type },
            dataType : 'html'
        })
        .done(function(returned_data)
        {                               
            // Success
            //console.log("Successfully saved {'" + ad_id + "|" + field + "' : '" + value + "'}");
            
            var info = $.parseJSON(returned_data);

            $('#updated_at').html(info.updated_at);
            $('#updated_by').html(info.updated_by);

            if (info.force_reload)
            {
                reload = true;
            }

        })
        .fail(function(jqXHR, status, error)
        {                                                   
            // Error
            var response = jqXHR.responseText;
            var errorData = $.parseJSON(response);
            //console.log(errorData);
            alert("There was an error saving this ads's data.\n\n" + errorData.error.message + "\n\nPlease try again.  Please note, that if you try to reload this page, your unsaved data will be lost.");
        })
        .complete(function ()
        {
            // Reload if necessary
            if (reload)
            {
                location.reload();
            }
            else
            {
                $('*').css({'cursor':''});
            }
        });
    }   

    // Autosave text fields
    function autoSaveTextField(input_field)
    {
        clearTimeout(autoSaveTextField.timeout);
        autoSaveTextField.timeout = setTimeout(function (){
            
            var ad_id = input_field.attr('data-ad-id');
            var value = input_field.val();
            var original_value = input_field.attr('data-original');
            var field = input_field.attr('data-field');
            var type = input_field.attr('data-type');                        
            
            var readonly_attr = input_field.attr('readonly');            
            if (typeof readonly_attr !== typeof undefined && readonly_attr !== false)
            {
                return false;
            }

            var reload = false;
            var reload_attr = input_field.attr('data-reload');            
            if (typeof reload_attr !== typeof undefined && reload_attr !== false)
            {
                reload = true;
            }

            var required = false;
            var required_attr = input_field.attr('data-required');            
            if (typeof required_attr !== typeof undefined && required_attr !== false)
            {
                required = true;
            }

            if (required && value == '' && !(original_value == '' || typeof original_value === typeof undefined || original_value === false))
            {
                input_field.val(original_value);

                input_field.focus();

                alertRequiredField();          

                return;
            }

            if (value != original_value && ((required && value != '') || !required))
            {
                saveFormData(ad_id, field, value, type, reload);
                input_field.attr('data-original', value);
            }
        }, 50);
    }

    // Autosave text fields and textareas
    $('input[type="text"][data-autosave]').on('change blur autocompletechange autocompleteselect', function (event)
    {            
        autoSaveTextField ($(this));
    });
    $('textarea[data-autosave]').on('change blur autocompletechange autocompleteselect', function (event)
    {            
        autoSaveTextField ($(this));
    });   

    // Autosave select fields    
    $('select[data-autosave]').on('change', function(event)
    {
        var select_field = $(this);
        var ad_id = select_field.attr('data-ad-id');
        var selected = $(':selected', select_field);
        var value = selected.val();
        var original_value = select_field.attr('data-original'); 
        var field = select_field.attr('data-field');
        var type = select_field.attr('data-type');                        
     
        var readonly_attr = select_field.attr('readonly');            
        if (typeof readonly_attr !== typeof undefined && readonly_attr !== false)
        {
            return false;
        }

        var reload = false;
        var reload_attr = select_field.attr('data-reload');            
        if (typeof reload_attr !== typeof undefined && reload_attr !== false)
        {
            reload = true;
        }

        if (value != original_value)
        {
            saveFormData(ad_id, field, value, type, reload);
            select_field.attr('data-original', value);
        }                
    });

    // Autosave check-box fields    
    $('input[type="checkbox"][data-autosave]').on('change', function(event)
    {
        var checkbox_field = $(this);        
        var ad_id = checkbox_field.attr('data-ad-id');
        var value = checkbox_field.is(':checked');
        var original_value = checkbox_field.attr('data-original'); 
        var field = checkbox_field.attr('data-field');
        var type = checkbox_field.attr('data-type');                        
        
        var readonly_attr = checkbox_field.attr('readonly');            
        if (typeof readonly_attr !== typeof undefined && readonly_attr !== false)
        {
            return false;
        }

        var reload = false;
        var reload_attr = checkbox_field.attr('data-reload');            
        if (typeof reload_attr !== typeof undefined && reload_attr !== false)
        {
            reload = true;
        }

        if (value != original_value)
        {
            saveFormData(ad_id, field, value, type, reload);
            checkbox_field.attr('data-original', value);
        }         
    });

    
	/*
     * Close button
     */
	$('.close_button')
		.button({'icons':{'primary':'ui-icon-circle-close'}})
		.css({'font-size':'9pt', 'margin-left':'10px'});     

   
    /*
     * Form behavior
     */ 
    $('a.test_link').click(function(event)
    {
        event.preventDefault();

        var link = $(this);
        var ad_id = link.attr('data-ad-id');
        var type = link.attr('data-type');

        if (type == 'link')
        {
            var href = $('#link_' + ad_id).val();
        }
        else
        {
            var image = $('#image_' + ad_id).val();
            var href = "<?php echo asset('images/ads/placements/'); ?>/" + image;
        }

        window.open(href);
    });

    
    $('img.preview').each(function(index)
    {
        var item = $(this);
        var ad_id = item.attr('data-ad-id');
        var image = $('#image_' + ad_id).val();
        var src = "<?php echo asset('images/ads/placements/'); ?>/" + image; 
        item.attr('src', src);
    });

    var total = <?php echo $total; ?>;
    $('.weight_total').each(function(index)
    {
        var item = $(this);
        var ad_id = item.attr('data-ad-id');
        var weight = parseInt($('#weight_' + ad_id).val());

        var load = (weight / total) * 100;

        item.html(weight + '/' + total + ' = ' + load.toFixed(2) + '%');

    });

    $('a.create_ad')
        .button({'icons' : {'primary' : 'ui-icon-plusthick'}})
        .css({'font-size' : '9pt'})
        .click(function(event)
        {
            event.preventDefault();

            $('<div><div>')
                .addClass('ui-widget-overlay ui-front')
                .appendTo('body');
              
            $('<div><div>').appendTo('body')
                .css('width', '225px')
                .css('height', '170px')
                .css('text-align', 'center')
                .css('padding', '0.5em')
                .position({my : "center center", at : "center center", of : window})
                .addClass('ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-di    buttons')
                .html('<br />Creating...<br /><br /><img src="http://www.osaa.org/images/icons/ajax_loader3.gif" /><div style="font-size: 8pt; line-height: 105%; margin-top: 2em;">Please wait, this may take a while to process...</div>');

            window.location.href="<?php echo url('/admin/ads/create'); ?>";            
        });
    

<?php $__env->stopSection(); ?>

<?php $__env->startSection('page_functions'); ?>          

    <a href="<?php echo url('/account'); ?>" class="close_button">Close</a>    
    
<?php $__env->stopSection(); ?>


<?php $__env->startSection('main_content'); ?>    		

 	<?php /*  Success Bar  */ ?>
 	<?php if (Session::has('success')): ?>
		<div class="success_bar">
			<div class="message">				
				<?php echo Session::get('success'); ?>
			</div>			
		</div>
	<?php endif; ?>


    <?php /*  Errors  */ ?>
    <?php if (Session::has('errors')): ?>        
        <div class="error ui-state-error" style="padding: 0.5em; font-size: 12pt;">
            <span class="ui-icon ui-icon-alert box_icon"></span>
            <?php foreach ($errors->all() as $error): ?>
                <?php echo $error; ?>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>   

        
    <h1>Ads in the Database Table `ads`</h2>

    <?php foreach ($ads as $ad): ?>

        <div style="border: 1px solid #999999; margin-bottom: 0.75em; padding: 0.25em; font-size: 9pt; position: relative; height: 130px;">

            <?php
                $bar_color = ($ad->is_retired) ? '#ffb0b0' : '#b0ffbe';
            ?>

            <div style="font-size: 8pt; background-color: <?php echo $bar_color; ?>; margin-bottom: 1em;">
                <span style="display: inline-block; width: 33%;">ID #: <?php echo $ad->id; ?></span>
                <span style="display: inline-block; width: 33%;">Created: <?php echo (!is_null($ad->created_at)) ? date('n/j/Y g:ia', strtotime($ad->created_at)) : 'N/A'; ?></span>
                <span style="display: inline-block; width: 33%;">Updated: <?php echo (!is_null($ad->updated_at)) ? date('n/j/Y g:ia', strtotime($ad->updated_at)) : 'N/A'; ?></span>
            </div>

            <a href="#" class="test_link" data-ad-id="<?php echo $ad->id; ?>" data-type="image" data-tooltip="Preview image">
                <img src="" alt="Image not Found" title="" class="preview" data-ad-id="<?php echo $ad->id; ?>" style="max-width: 250px; max-height: 100px; position: absolute; right: 3px; outline: 1px solid #000000;" />
            </a>

            <div style="float: left; width: 275px;">
                <?php echo Form::label('name_' . $ad->id, 'Ad Name'); ?>
                <?php echo Form::text(
                       'name_' . $ad->id,
                       $ad->name,
                       array('data-ad-id'    => $ad->id,
                             'data-autosave' => true,
                             'data-field'    => 'name',
                             'data-type'     => 'STRING',
                             'data-original' => $ad->name,
                             'data-required' => true,                           
                             'style'         => 'width: 225px;'
                        )
                    ); ?>
            </div>

            <div style="float: left; width: 275px;">
                <?php echo Form::label('image_' . $ad->id, 'Image File Name'); ?>
                <?php echo Form::text(
                       'image_' . $ad->id,
                       $ad->image,
                       array('data-ad-id'    => $ad->id,
                             'data-autosave' => true,
                             'data-field'    => 'image',
                             'data-type'     => 'STRING',
                             'data-original' => $ad->image,
                             'data-required' => true,
                             'data-reload'   => true,
                             'style'         => 'width: 225px;')); ?>                 
                
                <div class="small gray" style="position: absolute;">
                    ../public/images/ads/placements/
                </div>
            </div>

            <div style="float: left; width: 130px;">
                <?php echo Form::label('size_' . $ad->id, 'Size'); ?>
                <?php echo Form::select(
                       'size_' . $ad->id,
                       $sizes,
                       $ad->size,
                       array('data-ad-id'    => $ad->id,
                             'data-autosave' => true,
                             'data-field'    => 'size',
                             'data-type'     => 'STRING',
                             'data-original' => $ad->size,
                             'data-required' => true,
                             'style'         => 'width: 80px;')); ?>
            </div>           

            <div style="float: left; width: 90px;">
                <?php echo Form::label('weight_' . $ad->id, 'Weight'); ?>
                <?php echo Form::text(
                       'weight_' . $ad->id,
                       $ad->weight,
                       array('data-ad-id'    => $ad->id,
                             'data-autosave' => true,
                             'data-field'    => 'weight',
                             'data-type'     => 'INT',
                             'data-original' => $ad->weight,
                             'data-required' => true,
                             'data-reload'   => true,
                             'style'         => 'width: 40px;'
                        )
                    ); ?>
                <div class="small gray weight_total" data-ad-id="<?php echo $ad->id; ?>"></div>
            </div>

            <br class="clear" style="line-height: 3.5em;" />            

            <div style="float: left; width: 565px;">
                <?php echo Form::label('link_' . $ad->id, 'URL Link'); ?>
                <?php echo Form::text(
                       'link_' . $ad->id,
                       $ad->link,
                       array('data-ad-id'    => $ad->id,
                             'data-autosave' => true,
                             'data-field'    => 'link',
                             'data-type'     => 'STRING',
                             'data-original' => $ad->link,
                             'data-required' => true,                                 
                             'style'         => 'width: 515px;')); ?>

                <a href="#" class="test_link" data-ad-id="<?php echo $ad->id; ?>" data-type="link" data-tooltip="Open linked page in a new tab">
                    <img src="<?php echo asset('/images/icons/link_go_16px.png'); ?>" alt="" title="" style="vertical-align: middle;" />
                </a>
            </div>

            <div style="float: left; width: 200px;">

                <?php echo Form::label('retired_' . $ad->id, 'Retired'); ?>
                <?php echo Form::checkbox(
                       'retired_' . $ad->id,                       
                       true,
                       $ad->is_retired,
                        array('data-ad-id'    => $ad->id,
                              'data-autosave' => true,
                              'data-field'    => 'is_retired',
                              'data-type'     => 'BOOL',
                              'data-reload'   => true,
                              'style'         => 'vertical-align: middle; margin-right: 10px;')); ?>
                <span class="small gray">Check to disable this ad</span>
            </div>            
           
            <br class="clear" /><br />

        </div>




    <?php endforeach; ?>

    <br />

    <a href="#" class="create_ad">Create New Ad</a>




    <br /><br />    
    
    <img src="http://www.osaa.org/images/icons/ajax_loader3.gif" style="display: none;" />	
<?php $__env->stopSection(); ?>
