var need_to_confirm_leaving = false;
var $loadingDialog= false;

$j(document).ready(function(){
     //EDIT BUTTON
     $j(document).on('click','.edit_content',function(){
        //SETUP THE MAIN AREA.
         if (!$j(this).hasClass('is_link')) {
             var $area = $j(this)
                 .siblings(".content_body");

             if (!$area.length) {
                 $area = $j(this).closest('.content_container').find('.content_body');
             }

             var active_editor = false;
             if ($area.data('editor')) {
                 active_editor = $area.data('editor');
                 active_editor.focus();
             }
             else {
                //console.log($area);
                 $area.data('orig_html', $area.html());
                 var clean_data = $j(this).siblings('template').html();
                 $area[0].innerHTML = clean_data;
                 $area.find('div[class^="fck_widget_"]').attr('contenteditable', 'false');
                 $area.find('div.fck_widget_slider').html('Slider Widget Here');
                 $area.find('div.fck_widget_gallery_album').html('Gallery Widget Here');
                 $area.find('div.fck_widget_blog').html('Blog Widget Here');
                 $area.find('div.fck_widget_blog_slider').html('Blog Slider Widget Here');
                 $area.find('.form_replacement')
                     .html('Content Form here')
                     .attr('contenteditable', 'false');

                 //start the editor
                 if ($area.find('.section_subcontent').length) {
                     $area.find('.section_subcontent').each(function () {
                         startCKEditor($j(this), $area);
                     });
                 }
                 else {
                     startCKEditor($area, $area);
                 }
             }
             $j(window).scroll();

             //H2 AREA
             var $h2 = $j(this)
                 .siblings(".content_title").attr('contenteditable', 'true').css('display', '');

             var $table = $j(this)
                 .siblings("table.blog_details");

             $table.css('display', '');

             var $h3_author = $table
                 .find('input[name="author"]');

             var $h3_date = $table
                 .find(".date_editable");

             var $area_short = $table
                 .find('input[name="shortpost"]');

             if ($j('input[name="show_shortpost"]').is(":checked")) {
                 $table.find(".content_shortpost").hide();
             }

             $j(this).siblings(".author").hide();
             $j(this).siblings(".date").hide();
             $j(this).siblings(".blog_date_alt").hide();

             var $h3_old_date = $j(this).siblings(".date");

             if (!$h2.data('orig_html')) {
                 $h2.data('orig_html', $h2.html());
             }

             //switch to the save or abandon buttons
             $j(this).parent().children('.edit_content').hide();
             $j(this).parent().children('.clone_content').hide();
             $j(this).parent().children('.save_content').show();
             $j(this).parent().children('.cancel_content').show();

             need_to_confirm_leaving = true;
         } else {
             window.location.replace($j(this).data('link'));
         }

         //create the editor
         return false;
     });

     //CLONE BUTTON
     $j(document).on('click','.clone_content', function() {
        if (!confirm('Are you sure you want to clone this content?')) return false;
        closeContentEditor(this,false,true);
        return false;
     });

     //CANCEL EDIT BUTTON
     $j(document).on('click','.cancel_content',function(){
        if(!confirm('Are you sure you want to ignore these changes?')) return false;
        closeContentEditor(this,false);
        return false;
     });
     //SAVE EDIT
     $j(document).on('click','.save_content',function(){
        closeContentEditor(this,true);
        return false;
     });
     //DELETE BUTTON
     $j(document).on('click','.remove_content',function(){
        if(!confirm("You are about to delete content from your site.\n Would you like to continue?")) return false;

        //close the editor
        closeContentEditor(this,false);

        var $parent  = false;
        var id = $j(this).parents('.featured_article').attr('content_id');
        if(!id){
            $parent = $j(this).parents('.right_bm');
            id = $parent.attr('content_id');
        }
        else $parent = $j(this).parents('.featured_article');

        showLoadingMessage('Deleting', 'Please wait while we delete the content');

        $j.ajax({
            url: '/ajax/ajax.content.php',
            type :'POST',
            data : {
                'action':'delete',
                id : id
            },
            error : function (){
                hideLoadingMessage();
                alert('There was an error saving');
            },
            success : function(){
                hideLoadingMessage();
                $parent.remove();
            }
        });
        return false;
     });

     $j(document).on('change', 'input[name=show_shortpost]', function() {
         if ($j(this).is(":checked")) {
             $j('.content_shortpost').hide();
         } else {
             $j('.content_shortpost').show();
         }
     });

    (function($) {
        var currentForm = null;
        $(document.body).on('click', '.change_visibility_and_template', function() {
            //close the other forms
            if( currentForm ){
                currentForm.dialog('destroy');
            }

            var $this = $(this);
            var visibility = $this.attr('data-visibility');
            var background_image = $this.attr('data-background-image');
            var template = $this.attr('data-template');
            var id = $this.data('id');

            var cont_id = $(this).parent().parent().attr('content_id');
            var $form = $('<form>').css('textAlign', 'left');
            currentForm = $form;
            $form.append('<var>Visibility:</var></br>');
            $form.append(
                $.map(displayTooltips, function(label, value) {
                    return '<label><input name="display_type" type=radio value="' + value + '"/> ' + label + '</label><br>'
                }).join('')
            ).find('[name=display_type][value=' + visibility + ']').prop('checked', true);
            $backgroundImage = '</br><var>Background Image:</var></br><input  name="background_image"  value="' + background_image + '" type="text" size="60"/>' +
                       '<input type="button" value="Browse Server" onclick="BrowseServer($j(this).prev(),true);" class="action-button" />';
            $form.append($backgroundImage);
            if (contentTemplates) {
                $templatesSelect = '</br><var>Template:</var></br><select name=template><option value="0">Global Template</option>';
                $.each(contentTemplates, function (i, t) {
                    $selected = template == t['id'] ? 'selected' : '';
                    $templatesSelect += '<option data-class="' + t['class'] + '" value ="' + t['id'] + '" ' + $selected + '>'+ t['name']+'</option>';
                });
                $templatesSelect += '</select>';
                $form.append($templatesSelect);
                if (template !=0)
                    var previousTemplate = $form.find('[name=template]').find(':selected').data('class');
            }
            $form.dialog({
                title: "More Options",
                open: function(event,ui){
                    //remove any privacy stuff
                    $form.find('.page_visibility_div').remove();

                    $.ajax({
                        url: '/ajax/ajax.content.php',
                        type: 'POST',
                        data: {
                            action: 'getUserAccess',
                            id: cont_id
                        }

                    }).done(function(res){
                        if(res.success){
                            if(res.hasAccess){
                                if(res.page_visibility_html!='' && res.page_visibility_element != ''){
                                    $form.append(res.page_visibility_html);
                                    $("select#"+res.page_visibility_element+"_id").change(function(){
                                        if($("select#"+res.page_visibility_element+"_id :selected").val()=='members'){
                                            $("#"+res.page_visibility_element+"_tag_selector").show();
                                            $("#"+res.page_visibility_element+"_site_account_type_selector").show();
                                        }
                                        else {
                                            $("#"+res.page_visibility_element+"_tag_selector").hide();
                                            $("#"+res.page_visibility_element+"_site_account_type_selector").hide();
                                        }
                                    }).change();
                                }
                            }
                        }
                    });
                },
                buttons: {
                    "Update": function() {
                        var p = {};
                        if( $form.find('[name^="page_visibility["]').length){
                            $form.find('[name^="page_visibility["]').each(function(i){
                                p[$(this).attr('name').replace(/page_visibility|\[|\]|\d+/gim,'')] = $(this).val();
                            });
                        }
                        $.ajax({
                            url: '/ajax/ajax.content.php',
                            type: 'POST',
                            data: {
                                action: 'update_visibility_and_template',
                                visibility: $form.find('[name=display_type]:checked').val(),
                                background_image : $form.find('[name=background_image]').val(),
                                template_id: $form.find('[name=template]').val(),
                                privacy :p,
                                id: id
                            }

                        }).done(function(res) {
                            var visibility = $form.find('[name=display_type]:checked').val();
                            var background_image = $form.find('[name=background_image]').val();
                            var tip = displayTooltips[visibility] + ' - click to change';
                            var $content = $this.closest('.featured_article').find('.content_body');
                            var featured_article = $this.closest('.featured_article');

                            $this.prop('title', tip);
                            $this.children()[0].className = 'sc-icon sc-icon-display' + visibility;
                            $this.attr('data-visibility', visibility);
                            $this.attr('data-background-image', background_image);
                            if(visibility==='content_mobile_only'||visibility==='content_hidden') $content.addClass('diagonal_lines_pattern');
                            else $content.removeClass('diagonal_lines_pattern');
                            if (contentTemplates) {
                                var templateClass = $form.find('[name=template]').find(':selected').data('class');
                                var template = $form.find('[name=template]').val();
                                $this.attr('data-template', template);
                                $this.attr('data-template-class', templateClass);
                                featured_article.addClass(templateClass);
                            }

                            featured_article.css('background-image', 'url(\'' + background_image + '\')');
                        });
                        if (contentTemplates && previousTemplate)
                            $this.closest('.featured_article').removeClass(previousTemplate);
                        $(this).dialog('destroy');
                        currentForm = null;
                    },
                    Cancel: function() {
                       $(this).dialog('destroy');
                       currentForm = null;
                    }
              }
            });

            //add the stick value if not set
            var checked_ = $this.parent().find('.content_title').attr('data-is-sticky') == 0 ? '':'checked';

            if ($('.content_container.blog').length > 0) {
                $form.append('<div><small><i>Click to make this post a Sticky</i></small></div><label></labe><input type="checkbox" '+checked_+' name="is_sticky" /> Sticky</label>');
            }

            $('input[name="is_sticky"]').click(function(){
                var make_sticky = 0, sticky_id = $this.parent().find('.content_title').attr('data-id-sticky') ? $this.parent().find('.content_title').attr('data-id-sticky') : $this.attr('data-id');
                if($(this).is(':checked')){
                    make_sticky = 1;
                }
                $this.parent().find('.content_title').attr('data-is-sticky',make_sticky);
                $.post('/ajax/ajax.content.php',{'action':'make_post_stick','sticky':make_sticky,'id':sticky_id});
            });
        });

        $(document.body).on('click', '.change_sticky', function() {
            var $this = $(this);
            var id = $this.data('id');

            if ($this.hasClass('is_sticky')) {
                var update = 0;
            } else {
                var update = 1;
            }

            $.ajax({
                url: '/ajax/ajax.content.php',
                type: 'POST',
                data: {
                    action: 'make_post_stick',
                    sticky: update,
                    id: id
                }
            }).done(function(res) {
                if ($this.hasClass('is_sticky')) {
                    $this.removeClass('is_sticky');
                    $this.find('.ui-button-text').text('Mark as Sticky');
                } else {
                    $this.addClass('is_sticky');
                    $this.find('.ui-button-text').text('Unmark as Sticky');
                }
            });
        });
    })($j);

    $j('.add_link').click(function(){
        //get page_id
        var isRightBar = $j(this).attr('is_rightbar')=='true';
        var $clone_item;
        var $block_container;
        var toBottom = $j(this).attr('position')=='bottom';
        if(isRightBar){
            var rightBarId = $j(this).attr('right_bar_id');
            $clone_item = $j(this).parents('.sidebar_container').find('.right_bm:first-child').clone();
            if(!$clone_item.length){
                //second toolbar thats empty
                $clone_item = $j('.right_bm:first-child').clone();
            }
            $block_container =  $j(this).parents('.sidebar_container').find('.content_container');
        }
        else {
            $clone_item = $j('#div_order').find('.featured_article:first-child').clone();
            $block_container =  $j('#div_order');
        }

        var today = new Date();
        var today_timezone = new Date(today.getTime() - today.getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19);

        //empty content id
        $clone_item.removeAttr('content_id');

        //clear block info
        $clone_item.find('.content_body').html('<p>Update this content.</p>');
        $clone_item.find('template').html('<p>Update this content.</p>');
        $clone_item.find('input[name=author]').val('');
        $clone_item.find('input[name=shortpost]').val('');
        $clone_item.find('.date_editable').val(today_timezone);
        $clone_item.find('.orig_date').val(today_timezone);
        $clone_item.find('h2.content_title').text('');
        $clone_item.find('h3.date').text('Now');
        $clone_item.find('h3.author_set').text('');
        //turn off edit mode
        $clone_item.find('.content_body').removeAttr('contenteditable');
        $clone_item.find('h2.content_title').removeAttr('contenteditable');
        $clone_item.parent().children('.save_content').hide();
        $clone_item.parent().children('.cancel_content').hide();
        $clone_item.parent().children('.edit_content').show();
        $clone_item.parent().children('.clone_content').show();

        var page_id = $j(this).attr('page_id');
        if(isRightBar){
            var data = {
                page_id: page_id,
                'to_bottom': toBottom?'Y':'N',
                'right_bar_id':rightBarId,
                'action' : 'add_sidebar_box'
            };
            showLoadingMessage('Adding Rightbar', 'Please wait');

            $j.ajax({
                url: '/ajax/ajax.content.php',
                type :'POST',
                'data' : data,
                dataType: 'json',
                error : function (){
                    alert('There was an error adding new content');
                },
                success : function(data){

                    $clone_item.attr('content_id', data.id);
                    if(toBottom){
                         $block_container.append($clone_item);
                    }
                    else {
                         $block_container.prepend($clone_item);
                    }
                    $j("#div_order" ).sortable("refresh");
                    $j(".sidebar_container").sortable("refresh");
                    hideLoadingMessage();

                }
            });
        }
        else {

            //need to ask questions.
            $j('#add_edit_content_box').clone().dialog({
                //TODO when setting up tabs
                //title: 'Add a New Section',
                title: 'Choose a Layout',
                modal: true,
                width:550,
                open: function(){
                    //TODO turn on when doing tabs
                    //$j(this).find( ".add_content_tabs" ).tabs();
                    //$j(this).parents(".ui-widget-content").find( ".ui-dialog-titlebar.ui-widget-header" ).css('display','none');
                    //$j(this).find(".layout_radio" ).buttonset();
                },
                buttons: {
                    "Add Section": function() {
                        //figure out the sections
                        var section_txt = $j(this).find('input[name="layout"]:checked').val();
                        var template_id = $j(this).find('[name="template"]').val();
                        var background_image = $j(this).find('input[name="background_image"]').val();
                        var section_html = '';
                        if(section_txt){
                            var sections = section_txt.split('|');
                            for(s in sections){
                                if(sections.hasOwnProperty(s)){
                                    section_html += '<div class="section_subcontent '+sections[s]
                                            +'"><p>Update this content.</p></div>';
                                }
                            }
                            //section_html += '<div style="clear:both"></div>';
                        }
                        else {
                            section_html='<p>Update this content.</p>';
                        }

                        $clone_item.find('.content_body').html(section_html);
                        $clone_item.find('template').html(section_html);
                        //make stick default to 0
                        $clone_item.find('.content_title').attr('data-is-sticky',0);
                        $clone_item.css('background-image', ('url(\'' + background_image + '\')'));

                        //get list of all content template classes and remove any existing ones
                        var templateClasses = [];
                        $j(this).find('[name="template"] > option').each(function() {
                            templateClasses.push($j(this).attr('data-class'));
                        });
                        templateClasses.forEach( function(class_name) {
                            if (($clone_item).hasClass(class_name)) {
                                $clone_item.removeClass(class_name);
                            }
                        });
                        //now add the selected template class
                        $clone_item.addClass($j(this).find('[name="template"]').find(':selected').attr('data-class'));

                        //TODO save visibility
                        var data = {
                            page_id: page_id,
                            'to_bottom': toBottom?'Y':'N',
                            'action' : 'insert_content',
                            'section_html':section_html,
                            'page_template_id':template_id,
                            'background_image':background_image
                        };
                        showLoadingMessage('Adding Content', 'Please wait');

                        var that = this;
                        $j.ajax({
                            url: '/ajax/ajax.content.php',
                            type :'POST',
                            'data' : data,
                            dataType: 'json',
                            error : function (){
                                alert('There was an error adding new content');
                            },
                            success : function(data){
                                // reload the page if it has no content blocks or if the first content block on page load was deleted
                                if (!$clone_item.hasClass('featured_article')) {
                                    showLoadingMessage('Reloading', 'Please wait');
                                    location.reload();
                                } else {
                                    hideLoadingMessage();

                                    $clone_item.attr('content_id', data.id);
                                    $clone_item.find('.content_title').attr('data-id-sticky', data.id);
                                    $clone_item.find('.change_sticky').attr('data-id', data.id);
                                    $clone_item.find('.content_button').attr('data-id', data.id);

                                    if($clone_item.find('.edit_content')[0].hasAttribute('data-link') &&
                                        $clone_item.find('.edit_content').attr('data-link').includes('post_id=')){
                                        var old_link = $clone_item.find('.edit_content').attr('data-link').split('post_id=');
                                        $clone_item.find('.edit_content').attr('data-link', old_link[0] + 'post_id=' + data.id + '&edit=true\'');
                                    }

                                    if (toBottom) {
                                        $block_container.append($clone_item);
                                    }
                                    else {
                                        $block_container.prepend($clone_item);
                                    }
                                    $j("#div_order").sortable("refresh");
                                    $j(".sidebar_container").sortable("refresh");

                                }


                                //TODO visibility
                                /*var val = $form.find('[name=display_type]:checked').val();

                                var tip = displayTooltips[val] + ' - click to change';
                                $this.prop('title', tip);
                                $this.children()[0].className = 'sc-icon sc-icon-display' + val;
                                $this.data('value', val);
                                var $content = $this.closest('.featured_article').find('.content_body');
                                if(val==='content_mobile_only'||val==='content_hidden')$content.addClass('diagonal_lines_pattern');
                                else $content.removeClass('diagonal_lines_pattern');*/
                            }
                        });
                        $j(this).dialog('destroy');
                    },
                    Cancel: function() {
                       $j(this).dialog('destroy');
                    }
                }
            });
            return false;

        }


        return false;
    });

    //TOGGLE LINKS
    $j('.remove_links').click(function(){
         var num_editors = 0;
         if(!$j.isEmptyObject(CKEDITOR.instances)){
             for (var i in CKEDITOR.instances) {
                (function(i){
                    $editor =  $j('#'+CKEDITOR.instances[i].name+'');
                    num_editors +=  ($editor.parents('.control-group').length>0?0:1);
                })(i);
            }
         }
         if(!num_editors){
             if( $j('.add_link:first').is(':hidden')){
                 $j('.move_content, .edit_content, .clone_content, .remove_content, .change_visibility_and_template, .change_sticky, .add_link, .only_edit_mode').fadeIn();
                 $j(this).find('.ui-button-text').text('Pause Editing');
                 $j('.edit-buttons-header').text('Editing Page');
                 $j(this).find('.ui-icon').removeClass('ui-icon-play').addClass('ui-icon-pause');
             }
             else{
                 $j('.move_content, .edit_content, .clone_content, .remove_content, .change_visibility_and_template, .change_sticky, .add_link, .only_edit_mode').hide();
                 $j(this).find('.ui-button-text').text('Start Editing');
                 $j('.edit-buttons-header').text('');
                 $j(this).find('.ui-icon').removeClass('ui-icon-pause').addClass('ui-icon-play');
             }
         }
         else{
             alert('To toggle the editor icons, first finish editing all your content');
         }
    });
    //TODO location post id

    if (getParameterByName('edit')) {
        var post_id = getParameterByName('post_id');

        $j('.remove_links').click().click();
        $j('div[content_id=' + post_id + ']').find('.edit_content').click();
    } else {
        $j('.remove_links').click();
    }

    if($j.prototype.sortable){
         //MAKE MAIN AREA SORTABLE
        $j("#div_order").sortable({
            items: '.featured_article',
            placeholder: "featured_article",
            forcePlaceholderSize: true,
            helper: function(event, ui){
                //clone the
                var $c =  $j(ui).clone();
                $c.css('position','absolute');
                return $c.get(0);
            },
            handle: '.move_content',
            update: function(){
                saveContentOrder(false);
            }
        });

         //MAKE THE NAVS SORTABLE
        $j(".sidebar_container").sortable({
            items: '.right_bm',
            placeholder: "right_bm",
            forcePlaceholderSize: true,
            handle: '.move_content',
            helper: function(event, ui){
                var $c =  $j(ui).clone();
                $c.css('position','absolute');
                return $c.get(0);
            },
            connectWith :'.sidebar_container',
            update: function(){
                saveContentOrder(true);
            }
        });
    }

    if($j.prototype.disableSelection){
        $j(".sidebar_container .right_box1" ).disableSelection();
    }

    $j(document).on('click','.cke_button__form', function(e){
        e.preventDefault();
        e.stopPropagation();
        var self = $j(this);
        self.attr('onclick', '');
        $j.getJSON('/admin/ajax.forms.php?action=list', function(forms) {
            var select = $j('<select style="width:150px"></select>');
            for (var index in forms) {
                if(!forms.hasOwnProperty(index))continue;
                select.append($j('<option value="' + forms[index].id + '">' + forms[index].name +
                   (forms[index].title ?' (' + forms[index].title + ')':'')
                    +'</option>'));
            }
            if(select.find('option').length<1){
                select.append($j('<option value="">No Forms on your site</option>'));
            }
            $j('<div></div>').append(
                select
            ).dialog({
                modal: true,
                title: 'Insert A Form',
                buttons: {
                    'Insert': function() {
                        var theId = self.parents('.cke_chrome').attr('id');
                        if($j(this).find('select').val() == '') $j(this).dialog('close');
                        else{
                            var ed = null;
                            if(typeof self.data('editor_el') !== 'undefined'){
                                ed = self.data('editor_el');
                            }
                            else {
                                var num = theId.replace('cke_editor','');
                                ed=CKEDITOR.instances['editor'+num];
                            }
                            var toInsert = '<div class="form_replacement" form_id="'+$j(this).find('select').val()
                             +'" contenteditable="false">Form '+$j(this).find('select :selected').text()+' Inserted Here</div>';
                            ed.insertElement( CKEDITOR.dom.element.createFromHtml( toInsert ));
                            $j(this).dialog('close');
                        }
                    },
                    'Cancel': function() {
                        $j(this).dialog('close');
                    }
                }
            });
        });
        return false;
    });


});

$j(window).bind('beforeunload', function(event){
    //only check this an edit occured
    if(need_to_confirm_leaving){
        if(!$j.isEmptyObject(CKEDITOR.instances)){
            return "Are you sure you want to exit? you will lose the changes you have made on this page";
        }
        else return;
    }
    return;
});

/*
function editSponsor()
{
	$('sponsorForm').request(
		{
		onSuccess: function(transport){
		    var json = transport.responseText.evalJSON();
			if(json.link){
				$('sponsHeader').innerHTML = '';
				var link =	new Element('a',{href: json.link})
				link.innerHTML = "Sponsored by: " + json.sponsor;
				$('sponsHeader').appendChild(link);
			}else{
				$('sponsHeader').innerHTML = "Sponsored by: " + json.sponsor;
			}
		    Modalbox.hide();

		}
	});

}*/

//Load widget popup
function CKwidgetLoad()
{
    //container in $j("#widgetChooser")
    $j("#widgetChooser").load("/ajax/ajax.content.php?action=get_widgets", '', function(data){

        $j('select,input').css('background','#fff');
        $j('.selector').hide();

        $j("select[name=widget_list]").change(function(){
            var list_type= $j("select[name=widget_list] :selected").val();
            if(list_type=='fck_widget_past_events'){
                list_type='fck_widget_events';
            }
            var prop=$j("select[name=widget_list] :selected").attr('extra');

            $j('.selector').hide();
            $j('#select_chooser select').empty();

            if(prop=='text'){
                $j('#text_chooser').show();
                switch(list_type){
                    case 'fck_widget_youtube':
                        $j('#text_chooser_label').text('Enter video ID');
                        break;
                    case 'fck_widget_yutorah':
                        $j('#text_chooser_label').text('Enter Your Organization ID');
                        break;
                    case 'fck_widget_twitter':
                        $j('#text_chooser_label').text('Enter twitter username');
                        $j('#text_chooser input').val('');
                        break;
                    case 'fck_widget_facebook':
                        $j('#text_chooser_label').text('Enter facebook username');
                        break;
                }
            }
            else if(prop=='member_id'){
                $j('#member_id').show();
            }
            else if(prop=='gallery_id'){
                $j('#gallery_id').show();
            }
            else if(prop=='blog_id'){
                $j('#blog_id').show();
            }
            else if(prop=='blog_slider_id'){
                $j('#blog_slider_id').show();
            }

            else if(prop=='recipe_source'){
                $j('#recipe_source').show();
                $j('#limit_num_recipes').show();
            }
            else if(prop=='right_calendar_options'){
                $j('#rollover_type').show();
            }
            else if(prop=='enrollment_id'){
                $j('#enrollment_id').show();
            }
            else if(prop=='map_location_type_id'){
                $j('#map_location_type_id').show();
            }
            else if(prop=='slider_id'){
                $j('#slider_id').show();
            }
            else if(prop=='calendar_tag_ids'){
                $j('#calendar_tag_ids').show();
            }
            else if(prop=='event_slider_options'){
                $j('#event_slider_options').show();
            }

            else if(prop=='ad_size'){
                $j('#ad_size').show();
            }
            else if(prop=='goal_id'){
                $j('#goal_id').show();
            }
            else if(prop=='gallery_album_id'){
                $j('#gallery_album_id').show();
            }
            else if(prop=='donation_form_id'){
                $j('#donation_form_id').show();
            }
            else {
                arr = prop.split(',');
                if(arr.length>0 && arr[0]!=''){
                    $j('#select_chooser').show();

                    var options = '';
                    for (var i = 0; i < arr.length; i++) {
                        options += '<option value="' + arr[i] + '">' + arr[i]+ '</option>';
                    }
                    $j("#select_chooser select").html(options);


                    switch(list_type){
                        case 'fck_widget_lifecycles':
                            $j('#select_chooser_label').text('Select the lifecycle type');
                            break;
                        case 'fck_widget_gallery_album':
                            $j('#select_chooser_label').text('Select the lifecycle type');
                            break;
                    }
                }
            }

            $j('head').append('<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.5/ace.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.5/ext-static_highlight.js"></script>');

            if ($j('#'+list_type+'_options')) {
                $j('#'+list_type+'_options').show();
            }

        }).change();
        return false;
    });
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

//once the widget was OKed
function CKwidgetOK(editor)
{
    var list_type= $j("select[name=widget_list] :selected").val();
    var list_type_orig=list_type;
    if(list_type=='fck_widget_past_events'){
        list_type='fck_widget_events';
    }
    var widget_name=$j("select[name=widget_list] :selected").text();
    var prop=$j("select[name=widget_list] :selected").attr('extra');
    alt = '';
    alt_text = '';

    switch(prop){
        case 'text':
            alt = $j('#text_chooser input').val();
            alt_text = alt;
            break;
        case 'member_id':
            alt = $j('#member_id option:selected').val();
            alt_text = 'to '+$j('#member_id option:selected').text();
            break;
        case 'gallery_id':
            alt = $j('#'+prop+' option:selected').val();
            alt_text = '; Album '+$j('#'+prop+' option:selected').text();
            break;
        case 'gallery_album_id':
            alt = [];
            if($j('#'+prop).find('option:selected').length){
                //add other options if available.
                $j('#'+prop).find('option:selected').each(function(){
                    alt.push($j(this).val());
                });
            }
            alt = alt.join('|||');
            //alt_text = '; Album '+$j('#'+prop+' option:selected').text();
        case 'gallery_album_id':
            break;
        case 'map_location_type_id':
            alt = $j('#map_location_type_id option:selected').val();
            alt_text = '; For Type '+$j('#map_location_type_id option:selected').text();
            break;
        case 'ad_size':
            alt = $j('#ad_size option:selected').val();
            alt_text = '; Ad Size '+$j('#ad_size option:selected').text();
            break;
        case 'goal_id':
            alt = $j('#goal_id option:selected').val();
            alt_text = '; Goal Widget '+$j('#goal_id option:selected').text();
            break;
        case 'quote_data':
            alt = [];
            alt.push($j('#quote_data textarea').val());
            alt.push($j('#quote_data input').val());
            alt = alt.join('|||'); //3 pipes will split the quote from the author (semicolons aoften appear in quotes, and 2 semicolons sometimes)
                                    //appear when we htmlentity like this - qqq";;"aaa - becomes - qqq&quot;;;$quot;aaa   when we split
            alt_text = alt;
            break;
        case 'enrollment_id':
                alt = $j('#enrollment_id option:selected').val();
                alt_text = '; Enrollment '+$j('#enrollment_id option:selected').text();
                break;
        case 'blog_id':
             alt = $j('#blog_id select :selected').val() + ',' + $j('#blog_id input[name="limit"]').val();
             alt_text = '; Blog '+$j('#blog_id select :selected').text();
            break;
        case 'blog_slider_id':
             alt = $j('#blog_slider_id select :selected').val() + ',' + $j('#blog_slider_id input[name="limit"]').val();
             alt_text = '; Blog Slider'+$j('#blog_slider_id select :selected').text();
            break;
        case 'recipe_source':
                alt = $j('#recipe_source select :selected').val()+','+$j('#limit_num_recipes INPUT[name=limit]').val();
                alt_text = '; '+$j('#limit_num_recipes INPUT[name=limit]').val()+' '+$j('#recipe_source select :selected').text();
                break;
        case 'rollover_type':
                 alt = $j('#rollover_type select :selected').val();
                 alt_text = '; Rollover Type '+$j('#rollover_type select :selected').text();
                break;
        case 'slider_id':
                 alt = $j('#slider_id select :selected').val();
                 alt_text = '; '+$j('#slider_id select :selected').text();
                break;
        case 'donation_form_id':
                alt = $j('#donation_form_id select :selected').val();
                alt_text = $j('#donation_form_id select :selected').text();
                break;
        case 'event_slider_options':

            var limit = $j('#event_slider_options input[name=\'limit\']').val();

            if (limit) {
                alt = limit;
            }
            var max_shown_at_a_time = $j('#event_slider_options input[name=\'max_shown_at_a_time\']').val();

            if (max_shown_at_a_time) {
                alt += ',' + max_shown_at_a_time;
            }
            break;

        default:
            alt = $j('#select_chooser option:selected').val();
            alt_text = alt;
            if(!alt){
                alt_text = alt = '';
            }
            break;
    }

    if ($j('#'+list_type+'_options').length) {
        var values = new Array();
        $j.each($j('#'+list_type+'_options input[type=checkbox]:checked'), function() {
          values.push($j(this).val());
        });
        alt = values.join();
        alt_text = '; '+alt;

        var limit = $j('#'+list_type+'_options input[name=\'limit\']').val();

		if (limit) {
			alt += ',' + limit;
		}
    }


    if(list_type!=''){
        var sInsert='<div class="'+list_type_orig+'" contenteditable="false">(Automatic - '+widget_name+' '+alt_text+')</div>';

        //this is a better way to handle the "alt" attribute... it will automatically address
        //any quotes or other funny data that would break a standard inline alt. -AF

        sInsert = $j(sInsert).attr("alt",alt).prop('outerHTML');

        editor.insertElement( CKEDITOR.dom.element.createFromHtml( sInsert ));
    }
    return false;

}


function CKViewSourceShow(editor,rand){
    //get text value

    $j('#viewsource_text'+rand).width(1000).after("<input type='hidden' name='source_val'></input>");

    require(["ace/ace", "ace/ext/static_highlight"], function(ace) {
       // var highlight = ace.require("ace/ext/static_highlight")
        var ace_editor = ace.edit("viewsource_text"+rand);
        ace_editor.setOptions({
            minLines: 24,
            maxLines: 24
        });
        ace_editor.setTheme('ace/theme/monokai');
        ace_editor.getSession().setMode("ace/mode/html");

        //var $textarea = $(this).prev('textarea');
        ace_editor.getSession().setValue(editor.getData());
        $j('input[name=source_val]').val(editor.getData());
        ace_editor.getSession().on('change', function () {
            //$j("#viewsource_text"+rand).val(ace_editor.getSession().getValue());
            $j('input[name=source_val]').val(ace_editor.getSession().getValue());
        });
    });

    //get text value
    /*editAreaLoader.init({
        id : "viewsource_text"+rand		// textarea id
        ,syntax: "html"			// syntax to be uses for highgliting
        ,start_highlight: true		// to display with highlight mode on start-up
        ,allow_toggle : false
        ,min_height: 400
        ,min_width: 1000
        ,word_wrap: true
    });*/

}

function CKViewSourceOK(editor,rand){
    //console.log($j('input[name=source_val]').val());
    //save
    //editor.setData( $j('#viewsource_text'+rand).val() );
    editor.setData($j('input[name=source_val]').val());
    //editor.setData( editAreaLoader.getValue('viewsource_text'+rand));
}

function CKViewSourceHide(editor,rand){
    //editAreaLoader.delete_instance('viewsource_text'+rand);
    //$j("#viewsource_text"+rand).remove();
}


//handle for opening filebrowser
$field_which_needs_data = '';
$field_which_needs_data_2 = '';
function BrowseServer( $field, images_only, $field2 = '')
{
    $field_which_needs_data = $field;
    if ($field2) {
        $field_which_needs_data_2 = $field2;
    }
    window.open(
        '/admin/S3FileManager.php?callBack=SetUrl' + (images_only ? '&only_images=true' : ''),
        'filebrowser',
        'height=700,width=1000,scrollbars=yes'
    );
}
//this is where the filebrowser sets location
function SetUrl( fileUrl,data )
{
	$field_which_needs_data.val(fileUrl);
	if ($field_which_needs_data_2) {
        $field_which_needs_data_2.attr('src', fileUrl);
    }
    $field_which_needs_data_2 = '';
}

function closeContentEditor(caller, save, clone)
{
    var page_template_id;
    var page_template_class;
    var background_image;
    if (clone) {
        var $clone_item;
        var $block_container;

        $clone_item = $j('#div_order').find('.featured_article:first-child').clone();
        $block_container = $j('#div_order');

        //empty content id
        $clone_item.removeAttr('content_id');

        var orig_title = $j(caller).siblings(".content_title").text();
        page_template_id = $j(caller).siblings(".change_visibility_and_template ").attr('data-template');
        page_template_class = $j(caller).siblings(".change_visibility_and_template ").attr('data-template-class');
        background_image = $j(caller).siblings(".change_visibility_and_template").attr('data-background-image');

        // account for timezone in new date

        var new_date = new Date();

        var new_date_w_timezone = new Date(new_date.getTime() - new_date.getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19);

        //clear block info
        $clone_item.find('.content_body').html($j.trim($j(caller).siblings(".content_body").html()));
        $clone_item.find('template').html($j.trim($j(caller).siblings(".content_body").html()));
        $clone_item.find('h2.content_title').text(orig_title);
        $clone_item.find('h3.date').text('Now');
        $clone_item.find('h3.author').text($j(caller).find('input[name="author"]').html());
        $clone_item.find('.date_editable').val(new_date_w_timezone);
        $clone_item.find('.orig_date').val(new_date_w_timezone);
        $clone_item.find('.content_shortpost').html($j.trim($j(caller).find('input[name="shortpost"]').html()));
        $clone_item.addClass(page_template_class);
        $clone_item.css('background-image', 'url(\'' + background_image + '\')');

        //turn off edit mode
        $clone_item.find('.content_body').removeAttr('contenteditable');
        $clone_item.find('h2.content_title').removeAttr('contenteditable');
        $clone_item.parent().children('.save_content').hide();
        $clone_item.parent().children('.cancel_content').hide();
        $clone_item.parent().children('.edit_content').show();
        $clone_item.parent().children('.clone_content').show();
    }

    //main content
    var $area = $j(caller).siblings(".content_body");
    if (!$area.length) {
        $area = $j(caller).closest('.content_container').find('.content_body');
    }

    if (!clone) {
        $area.removeClass("inline_offset");
        $area.find('div[class^="fck_widget_"]').removeAttr('contenteditable').text('Refresh Page to see this widget');
        $area.find('.form_replacement').removeAttr('contenteditable').text('Refresh Page to see this form');
        $area.removeAttr('contenteditable');
        $area.find('.section_subcontent').removeAttr('contenteditable');
    }
    //var new_raw_data = editor? editor.getData():'';
    if($area.find('.section_subcontent').length){
        $area.find('.section_subcontent').each(function(){
            stopCKEditor($j(this));
        });
    }
    else {
        stopCKEditor($area);
    }

    var new_raw_data = $area.html();

    //title
    var $h2 = $j(caller).siblings(".content_title");
    if($h2) {
        $h2.removeAttr('contenteditable');
    }

    if ($j(caller).siblings('.table-responsive').length > 0) {
        var $table = $j(caller)
            .siblings(".table-responsive").find('table.blog_details');
    } else {
        var $table = $j(caller)
            .siblings("table.blog_details");
    }

    var $h3_author = $table.find('input[name="author"]');
    var $h3_date_editable = $table.find(".date_editable");
    var $area_short = $table.find('input[name="shortpost"]');

    var h3_author = ($h3_author.length == 1 ? $h3_author.val() : '');
    var h3_date = ($h3_date_editable.length == 1 ? $h3_date_editable.val() : '');
    var new_summary = '';

    if (!($table.find('input[name="show_shortpost"]').is(":checked"))) {
        new_summary = ($area_short ? $area_short.val() : '');
    }

    if(save!==true && !clone){
        $area.html($area.data('orig_html'));
        if($h2)
            $h2.html($h2.data('orig_html'));
        if($h3_author)
            $h3_author.val($j(caller).siblings('.author').find('.author_set').html());
        if($h3_date_editable)
            $h3_date_editable.val($j(caller).siblings('.orig_date').val());
        if($area_short)
            $area_short.val($j(caller).siblings('.orig_short').val());

        $table.hide();

        $j(caller).siblings('.date').show();
        $j(caller).siblings('.author').show();
    } else if (save) {
        //save the changes, destroy the editor.
        var on_sidebar = false;
        var id = $area.parents('.featured_article').attr('content_id');
        if($area.parents('#footer').length===1){
            id = 'footer';
        }
        if(!id){
            id = $area.parents('.right_bm').attr('content_id');
            on_sidebar = true;
        }
        if(!id) {
            id = $area.parents('.featured_article').attr('event_id');
            if (id) id = 'event_' + id;
            is_event = true;
        }

        showLoadingMessage('Saving', 'Please wait while we save');
        var h2_save = ($h2.length==1?$h2.html():'');

        if(h2_save==='&nbsp;') h2_save = '';

        if ($area_short){
            if (new_summary == '') {
                $area_short.html('');
            }
        }

        $table.hide();

        if( $j(caller).siblings('.date').length && $h3_date_editable){
            $j(caller).siblings('.date').html(h3_date.replace("T", " ")).show();
        }
        $j(caller).siblings('.orig_date').val(h3_date);
        $j(caller).siblings('.orig_short').val(new_summary);
        $j(caller).siblings('.author').find('.author_set').html(h3_author);
        if (h3_author.length > 0) {
            $j(caller).siblings('.author').show();
        }

        showLoadingMessage('Saving', 'Please wait');


        $j.ajax({
            url: '/ajax/ajax.content.php',
            type :'POST',
            data : {
                'action':'update',
                id : id,
                'info[name]': h2_save,
                'info[body]' : new_raw_data,
                'info[date_added]' : h3_date,
                'info[author]' : h3_author,
                'info[summary]' : new_summary,
                'info[page_template_id]' : page_template_id,
                'info[page_template_class]' : page_template_class,
                'info[background_image]' : background_image
            },
            dataType : 'script',
            error : function (e){
                const getMessage = new Promise(function(resolve, reject) {
                    if (e.responseText) {
                        message = JSON.parse(e.responseText).message;
                    }
                    resolve(message);
                });
                
                getMessage
                    .then ( (message) => {
                        alert(message);
                    })
                    .catch( () => {
                        alert('There was an error saving your content');
                    });
                hideLoadingMessage();
            },
            success: function(){
                hideLoadingMessage();
            },
            complete:function(){
                if($h2.length===1){
                    var h2_str = $h2.html();//.replace('&nbsp;',' ');
                    if(!h2_str || /^\s*$/.test(h2_str)) $h2.css('display','none');
                }
                $area.siblings('template')[0].innerHTML = new_raw_data;
                $area.removeAttr('style');
            }
        });
    }

    if (clone) {
        showLoadingMessage('Cloning', 'Please wait while we clone');
        var h2_clone = ($h2.length==1?$h2.html():'');
        if(h2_clone==='&nbsp;') h2_clone = '';
        showLoadingMessage('Cloning', 'Please wait');

        var page_id = $j('.add_link').attr('page_id');

        $j.ajax({
            url: '/ajax/ajax.content.php',
            type :'POST',
            data : {
                'page_id': page_id,
                'action':'clone_content',
                'section_html':new_raw_data,
                'section_title':orig_title,
                'section_date':h3_date,
                'section_added':h3_author,
                'section_summary':new_summary,
                'page_template_id' : page_template_id,
                'page_template_class' : page_template_class,
                'background_image' : background_image
            },
            dataType : 'json',
            error : function (){
                hideLoadingMessage();
                alert('There was an error cloning');
            },
            success: function(){
                hideLoadingMessage();
            },
            complete:function(data){
                // reload the page if it has no content blocks or if the first content block on page load was deleted
                if (!$clone_item.hasClass('featured_article')) {
                    location.reload();
                    showLoadingMessage('Reloading', 'Please wait');
                } else {

                    var new_id = JSON.parse(data.responseText);

                    if ($h2.length === 1) {
                        var h2_str = $h2.html();//.replace('&nbsp;',' ');
                        if (!h2_str || /^\s*$/.test(h2_str)) $h2.css('display', 'none');
                    }

                    $area.siblings('template')[0].innerHTML = new_raw_data;
                    $area.removeAttr('style');

                    $clone_item.attr('content_id', new_id.id);
                    $clone_item.find('.content_title').attr('data-id-sticky', new_id.id);
                    $clone_item.find('.content_button').attr('data-id', new_id.id);

                    $j('#div_order').prepend($clone_item);

                    $j("#div_order").sortable("refresh");
                    $j(".sidebar_container").sortable("refresh");
                }
            }
        });
    }

    $j(caller).parent().children('.save_content').hide();
    $j(caller).parent().children('.cancel_content').hide();
    $j(caller).parent().children('.edit_content').show();
    $j(caller).parent().children('.clone_content').show();

    return false;

}

function saveContentOrder(rightBar){
    div_order =[];
    //get save the new order.
    if(rightBar){
        $j(".sidebar_container").each(function(){
            div_order[$j(this).attr('right_bar_id')] = $j.map($j(this).find('.right_bm'), function(elem){
                return $j(elem).attr('content_id');
            });
        });
    }
    else {
         div_order[0] = $j.map($j('#div_order .featured_article'), function(elem){
            return $j(elem).attr('content_id');
        });
    }
    //save the order
    showLoadingMessage('Saving Order', 'Please wait while we save the order');

    $j.ajax({
        url: '/ajax/ajax.content.php',
        type :'POST',
        'data' : {
            action: 'div_order'+(rightBar?'_right':''),
            order: div_order //TODO is this right?
        },
        dataType: 'json',
        error : function (){
            hideLoadingMessage();
            alert('There was an error reordering your page');
        },
        success : function(data){
            hideLoadingMessage();
        }
    });
}

function showLoadingMessage(title, message)
{
    if($j.fn.buttonUI) return;
    if($loadingDialog){
        hideLoadingMessage();
    }

    if(!title) title ='Loading';
    if(!message) message ='Please wait...';

    $loadingDialog = $j('<div>'+message+'</div>');
    $loadingDialog.dialog({
        width:250,
        closeOnEscape: false,
        height:140,
        modal: true,
        open: function(event, ui) {$loadingDialog.closest('.ui-dialog').find(".ui-dialog-titlebar-close").hide();},
        title:title
    }).text(message);
}

function hideLoadingMessage()
{
    if($loadingDialog){
        $loadingDialog.dialog('close');
        $loadingDialog.remove();
    }
    $loadingDialog = false;
}

function startCKEditor($editor, $area){
    $editor.attr('contenteditable','true');
    $area.addClass("inline_offset");
    active_editor = CKEDITOR.inline( $editor.get(0) );
    active_editor.on('instanceReady', function(ev) {
         ev.editor.focus();
         $j('.cke_button__form').attr('onclick', '');

         var cke = $j("div#cke_"+this.name);
         cke.find("div.cke_custom_toolbar").remove();
         var toolbar = $j($area.siblings("div.cke_custom_toolbar")).clone().prependTo(cke);
         toolbar.show();
         toolbar.find(".save_button").click(function(){
            $j($area).siblings("div.save_content").click();
         });
         toolbar.find(".discard_button").click(function(){
            $j($area).siblings("div.cancel_content").click();
         });
         toolbar.find(".close_button").click(function(){
            CKEDITOR.instances[cke.attr("id").replace("cke_","")].fire("blur");
            return false;
         });
         //fix the position on first load.
         CKEDITOR.instances[cke.attr("id").replace("cke_","")].fire("focus");
    });
    active_editor.on('focus',function(){
       $area.addClass("inline_offset");
    });

    active_editor.on('blur',function(){
       $area.removeClass("inline_offset");
    });

    $editor.data('editor', active_editor);

}

function stopCKEditor($area){
    var editor  = $area.data('editor');
    //var new_raw_data = editor? editor.getData():'';
    if(editor)  {

        editor.destroy();
        $area.removeClass(function (index, css) {
            return (css.match (/(^|\s)cke_\S+/g) || []).join(' ');
        });
        $area.removeAttr('tabindex');
        $area.removeAttr('spellcheck');
        $area.removeAttr('role');
        $area.removeAttr('aria-label');
        $area.removeAttr('title');
        $area.removeAttr('aria-describedby');

        $area.removeData('editor');
    }
}
