
var mouse_is_inside_panel_notification  = false;
var update_panel_timeout                = false;
var currently_selected_swatch_color     = false;
var currently_selected_icon             = false;

var form_processing                     = false;
var just_clicked_on_edit_button_submenu = false;

formProcessingBtn                       = new Image(); 
formProcessingBtn.src                   = "/images/main/button_disabled2.gif"; // Preload form processing button


function moviePlay() {
    startMoviePlay("embedded");
}

function movieStop() {
    stopMoviePlay("embedded");
}


function myAddListener(obj, evt, handler, captures) {
    if ( document.addEventListener ) {
        obj.addEventListener(evt, handler, captures);
    } else {
        // IE
        obj.attachEvent('on' + evt, handler);
    }
}
       

function RegisterListener(eventName, objID, embedID, listenerFcn) {
    var obj = document.getElementById(objID);
    if ( !obj ) obj = document.getElementById(embedID);
    if ( obj ) myAddListener(obj, eventName, listenerFcn, false);
}


function startMoviePlay(mode) {
    startMovieCounter();
}

var movieTimeout        = false;
var lastCheckpoint      = 0;
var hasStartedPlaying   = false;

function startMovieCounter() {
    var nextCheckpoint = lastCheckpoint + 1;
    if (!hasStartedPlaying) {
        hasStartedPlaying = true;
        updateMovieCounter('0');
    }
    movieTimeout  = setTimeout("updateMovieCounter("+nextCheckpoint+")", checkpoint * 1000);
}



function updateMovieCounter(thisCheckpoint) {
    lastCheckpoint = thisCheckpoint;
    if (thisCheckpoint <= 4) {
        if (thisCheckpoint > 0) startMovieCounter();
        if (video_id) {
            $.ajax({
                url: '/includes/ajax_video_checkpoint.php',
                type: 'POST',
                data: {video_id: video_id, checkpoint: thisCheckpoint, rand_user_id: rand_user_id},
                success: function(data) {
                    //done
                }
            });
        }
    }
}


function stopMoviePlay() {
    if (movieTimeout) clearTimeout(movieTimeout);
}



$(document).ready(function() {

    RegisterListener('qt_play', 'video_object', 'video_embed', moviePlay);
    RegisterListener('qt_stop', 'video_object', 'video_embed', movieStop);
    
    
    $('html').click(function() {
        close_all_open_panels('panel');
    });
    
    $('#toolbar_account_menu').click(function(event) {
        event.stopPropagation();
    });
    $('#toolbar_account').click(function(event) {
        event.stopPropagation();
    });
    $('#toolbar_alerts').click(function(event) {
        event.stopPropagation();
    });
    $('#panel_notification').click(function(event) {
        event.stopPropagation();
    });
    $('#panel').click(function(event) {
        event.stopPropagation();
    });
    $('.cal_event').click(function(event) {
        event.stopPropagation();
    });
    $('.cal_list_event').click(function(event) {
        event.stopPropagation();
    });
    $('#cal_popup').click(function(event) {
        event.stopPropagation();
    });
    
    $('#panel_notification').hover(function() {
        mouse_is_inside_panel_notification = true;
    }, function() {
        mouse_is_inside_panel_notification = false;
    });

    $('body').mouseup(function(){
        if (!mouse_is_inside_panel_notification) $('#panel_notification').fadeOut('fast');
    });
    
    $('.choice').mouseenter(function() {
        $('ul',this).show();
    });
    $('.choice').mouseleave(function() {
        $('ul',this).hide();
    });
    $('.choice ul').click(function(event) {
        $(this).hide();
    });
    
    
    $('.edit_button_more').click(function() {
        just_clicked_on_edit_button_submenu = true;
        var show_this_submenu = false;
        if (!$(this).next().is(':visible')) show_this_submenu = true;
        $('.edit_button_submenu').fadeOut('fast');
        if (show_this_submenu) $(this).next().fadeIn('fast');
    });

    $('.edit_button_submenu').click(function(event) {
        just_clicked_on_edit_button_submenu = true;
    });
    
    
    $('#panel').draggable({cancel: '#panel_inner, #panel_close'});
    
    set_panel_max_height();
    
    if (window.location.hash) {
        detect_hash('onload');
    }
    
    
    // Load previous or next photo in gallery on keydown
    $(document).keydown(function(e) {
        if ($('#gallery').data('prev_photo') && e.keyCode == 37) { // Prev photo on left arrow
            gallery_load_photo($('#gallery').data('prev_photo'));
            gallery_toggle_sharebox('hide');
        } else if ($('#gallery').data('next_photo') && e.keyCode == 39) { // Next photo on right arrow
            gallery_load_photo($('#gallery').data('next_photo'));
            gallery_toggle_sharebox('hide');
        } else if ($('#panel').is(':visible') && e.keyCode == 27) { // Close panel (if open) on ESC
            update_panel('hide');
        } else if ($('#gallery').length > 0 && e.keyCode == 27) { // Close gallery (if exists) on ESC
            gallery_close();
        } else if ($('#showcase_photo_frame').data('prev_photo') && e.keyCode == 37) { // Prev photo on left arrow in Showcase
            gallery_load_photo_showcase($('#showcase_photo_frame').data('prev_photo'));
        } else if ($('#showcase_photo_frame').data('next_photo') && e.keyCode == 39) { // Next photo on right arrow in Showcase
            gallery_load_photo_showcase($('#showcase_photo_frame').data('next_photo'));
        } else if (e.keyCode == 27) {
            close_all_open_panels(); // Close any open panels on ESC
        }
    });
    
});



function close_all_open_panels(panel_id_to_ignore) {
    $.each(['panel', 'panel_notification', 'toolbar_account_menu', 'cal_popup'], function(key, value) {
        if (value != panel_id_to_ignore) {
            $('#'+value).fadeOut('fast');
        }
    });
    
    if (!just_clicked_on_edit_button_submenu) $('.edit_button_submenu').fadeOut('fast');
    just_clicked_on_edit_button_submenu = false;
}


$(window).resize(function() {
    set_panel_max_height();
    if ($("#document_dim").length) $("#document_dim").css("height", $(document).height());
    if ($("#gallery").length) {
        gallery_center_photo();
    }
});



// Track swiping on iOS devices

var fingerCount     = 0;
var startX          = 0;
var startY          = 0;
var curX            = 0;
var curY            = 0;

function touchStart(event,passedName) {
    event.preventDefault();
    fingerCount = event.touches.length;
    if (fingerCount == 1) {
        startX = event.touches[0].pageX;
        startY = event.touches[0].pageY;
        curX = startX;
        curY = startY;
        triggerElementID = passedName;
    } else {
        touchCancel(event);
    }
}

function touchMove(event) {
    event.preventDefault();
    if (fingerCount == 1 ) {
        curX = event.touches[0].pageX;
        curY = event.touches[0].pageY;
    } else {
        touchCancel(event);
    }
}

function touchEnd(event) {
    event.preventDefault();
    if (fingerCount == 1) {
        var travel_x = curX - startX;
        var travel_y = curY - startY;
        if (Math.abs(travel_x) > Math.abs(travel_y) && Math.abs(travel_x) > 33) {
            if (travel_x > 0) {
                if ($('#gallery').data('prev_photo')) {
                    gallery_load_photo($('#gallery').data('prev_photo'));
                }
            } else {
                if ($('#gallery').data('next_photo')) {
                    gallery_load_photo($('#gallery').data('next_photo'));
                }
            }
            gallery_toggle_sharebox('hide');
        }
    }
    touchCancel(event);
}

function touchCancel(event) {
    // reset the variables back to default values
    fingerCount     = 0;
    startX          = 0;
    startY          = 0;
    curX            = 0;
    curY            = 0;
}




function set_panel_max_height() {
    $('#panel_inner').css('max-height', ($(window).height() - 220) + 'px');
}



window.onhashchange = function() {
    detect_hash('hashchange');
}



function toggle_spacer_div(spacer_div_id) {
    $('#spacer_div_'+spacer_div_id).slideToggle('fast');
    
    toggle_disclosure_triangle(spacer_div_id);
    
    new_hash_string = '';
    hash_parts = window.location.hash.split('&');
    spacer_ids = hash_parts[0].split('-');
    var arLen = spacer_ids.length;
    current_id_is_already_open = false;
    for ( var i=0, len=arLen; i<len; ++i ){
        var thisId = spacer_ids[i];
        if (thisId == parseInt(thisId)) { // Makes sure is int
            if (spacer_div_id != thisId) {
                new_hash_string = new_hash_string + '-' + thisId;
            } else {
                current_id_is_already_open = true;
            }
        }
    }
    if (!current_id_is_already_open) new_hash_string = new_hash_string + '-' + spacer_div_id;
    window.location.hash = 'spacer'+new_hash_string;
}



function detect_hash(method) {

    this_gallery_id = false;
    this_photo_id   = false;
    
    hash_parts = window.location.hash.split('&');
    
    if (hash_parts[0].substr(0,9) == '#gallery-' && hash_parts[1].substr(0,6) == 'photo-') {
        gallery_parts   = hash_parts[0].split('-');
        photo_parts     = hash_parts[1].split('-');
        this_gallery_id = parseInt(gallery_parts[1]);
        this_photo_id   = parseInt(photo_parts[1]);
        if (this_gallery_id > 0 && this_photo_id > 0) {
            gallery_init(this_gallery_id, this_photo_id);
        }
    } else if (hash_parts[0].substr(0,7) == '#event-') {
        event_parts = hash_parts[0].split('-');
        open_cal_event(event_parts[1]);
    } else if (hash_parts[0].substr(0,8) == '#spacer-' && method == 'onload') {
        spacer_ids = hash_parts[0].split('-');
        var arLen = spacer_ids.length;
        for ( var i=0, len=arLen; i<len; ++i ){
            var thisId = spacer_ids[i];
            if (thisId == parseInt(thisId)) { // Makes sure is int
                // Toggle the disclosure triangle
                toggle_disclosure_triangle(thisId);
                $('#spacer_div_'+thisId).slideToggle('fast');
            }
        }
    }

}



function toggle_disclosure_triangle(div_id) {
    var triangle_div = document.getElementById('triangle_'+div_id);
    if (triangle_div) {
        if (triangle_div.style.backgroundPosition == "0px -14px") {
            triangle_div.style.backgroundPosition = "0px 0px";
        } else {
            triangle_div.style.backgroundPosition = "0px -14px";
        }
    }
}





function show_update_panel(message) {
    if (update_panel_timeout) clearTimeout(update_panel_timeout);
    $('#update_panel').fadeOut('fast', function() {
        $('#update_panel').html(message).fadeIn('fast');
    });
    update_panel_timeout = window.setTimeout("$('#update_panel').fadeOut('slow')", 3000);
}


function update_panel(show_hide, action, parameters) {

    close_all_open_panels('panel');
    
    if (show_hide == 'show') {
        if ($('#panel').is(':hidden')) {
            $('#panel_inner').html('Loading...');
        }
    } else {
        $('#panel').fadeOut('fast', function() {
            $('#panel_title').html('&nbsp;');
        });
    }
    
    if (action) {
        $.ajax({
            url: '/includes/panel.php',
            type: 'POST',
            data: {action: action, params: parameters},
            success: function(data) {
                $('#panel_inner').html(data);
                if (show_hide == 'show') {
                    $('#panel').css({top: 142 + $(window).scrollTop() + "px", left: "50%"});
                    $('#panel').fadeIn('fast');
                }
            }
        });
    }

}

function panel_process(button_name) {
    if (button_name) {
        $('#panel_save_link').html(button_name);
    }
    $('#panelForm').submit();
}

function swap_notification_panels(this_div_num) {
    if (this_div_num) {
        $('#notifications_inner_div_'+this_div_num).hide();
    }
    current_nav_panel = this_div_num + 1;
    $('#notifications_inner_div_'+current_nav_panel).show();
}

function disbale_save_button(button_id, button_name) {
    if (button_id == 'login' || form_processing != button_id) {
        $('#save_button_'+button_id).css({backgroundImage: 'url(/images/main/button_disabled2.gif)', backgroundPosition: '0px 0px', cursor: 'default'}).html(button_name);
        form_processing = button_id;
        return true;
    }
    return false;
}




function update_toolbar_inbox_count(num) {
    var thisText = 'Inbox';
    if (num > 0) thisText += "<div class='toolbar_badge'>"+num+"</div>";
    $('#toolbar_inbox').html(thisText)
}

function update_toolbar_alert_count(num) {
    var thisText = 'Alerts';
    if (num > 0) thisText += "<div class='toolbar_badge'>"+num+"</div>";
    $('#toolbar_alerts').html(thisText)
}




function toggle_toolbar_account_menu(tmp_show_or_hide) {

    close_all_open_panels();
    
    show_or_hide = 'hide';
    if (tmp_show_or_hide == 'show' || (!tmp_show_or_hide && $('#toolbar_account_menu').is(':hidden'))) {
        show_or_hide = 'show';
    }
    
    if (show_or_hide == 'show') {
        $('#toolbar_account_menu').fadeIn('fast');
    } else {
        $('#toolbar_account_menu').fadeOut('fast');
    }
}


function update_panel_notification(show_hide, action, parameters) {

    close_all_open_panels('panel_notification');
    
    if (show_hide == 'toggle') {
        show_hide = 'hide';
        if ($('#panel_notification').is(':hidden')) {
            show_hide = 'show';
        }
    }
    
    if (show_hide == 'show') {
        if ($('#panel_notification').is(':hidden')) $('#panel_notification').html('<ul><li>Loading...</li></ul>');
        $('#panel_notification').fadeIn('fast');
    } else {
        $('#panel_notification').fadeOut('fast');
    }
    
    if (action) {
        $.ajax({
            url: '/includes/panel_notification.php',
            type: 'POST',
            data: {action: action, params: parameters},
            success: function(data) {
                $('#panel_notification').html(data);
            }
        });
    }

}




function dashboard_update_followed_sites(type, title) {
    $('.edit_button_submenu').fadeOut('fast');
    $('#followed_sites_box .edit_button_more').html(title);
    $.ajax({
        url: '/includes/ajax_dashboard_followed_sites.php',
        type: 'POST',
        data: {type: type},
        success: function(data) {
            $('#followed_sites_list').html(data);
        }
    });
}

function update_feed(unique_id, site_type, content_type, item_count, building_id, site_id, page_id) {
    $('#feed_loading').html("<img src='/images/main/ajax-loader.gif' width='16' height='16'>").fadeIn();
    $.ajax({
        url: '/includes/ajax_feed_update.php',
        type: 'POST',
        data: {unique_id: unique_id, site_type: site_type, content_type: content_type, item_count: item_count, building_id: building_id, site_id: site_id, page_id: page_id},
        success: function(data) {
            $('#feed_loading').hide().html('');
            $('#feed').html(data);
        }
    });
}


function showcase_admin(item_id, yes_or_no) {

    $('#showcase_'+item_id).slideUp('fast', function() {
        $('#showcase_'+item_id).remove();
        if ($('.showcase_box').length < 1) {
            $('#last_line').remove();
            $('#no_items_msg').fadeIn('fast');
        }
    });
    

    $.ajax({
        url: '/includes/ajax_showcase_admin_handler.php',
        type: 'POST',
        data: $('#showcase_item_'+item_id).serialize() + "&item_id="+item_id+"&yes_or_no="+yes_or_no,
        success: function(data) {
            $('#showcase_debug').html(data);
        }
    });

}








var banner_timer = false;

function banner_slide(banner_num, cancel_timer) {

    var slideTimer = 900;

    if (cancel_timer) {
        clearTimeout(banner_timer);
        slideTimer = 250;
    } else {
        if (banner_num == 1) slideTimer = 350;
        x = 1;
        if (banner_num < banner_count)  x = 1 + parseInt(banner_num);
        banner_set_timer(x);
    }

    var this_pos = $('#banner_'+banner_num).position();
    
    $('#showcase_banner_inner').animate({left: '-' + this_pos.left +'px'}, slideTimer);
    
    // UPDATE NAV DOTS
    $('#banner_nav_dots .nav_dot_selected').removeClass('nav_dot_selected').addClass('nav_dot');
    $('#nav_dot_'+banner_num).removeClass('nav_dot').addClass('nav_dot_selected');

}

function banner_set_timer(num) {
    banner_timer = setTimeout("banner_slide('"+num+"')", 4500);
}



function showcase_lift_tags() {
    $('#showcase_banner_outer').hide();
    $('#showcase_link_box').hide();
    $('#tag_box').appendTo('#showcase_top');
    $('#remove_tags').show();
}

function showcase_lower_tags() {
    $('#showcase_banner_outer').show();
    $('#showcase_link_box').show();
    $('#tag_box').appendTo('#showcase_bottom');
    $('#remove_tags').hide();
}


function showcase_change_value(key, value) {

    var showcase_prefs = jQuery.parseJSON($('#showcase_prefs').val());
    
    if (key == 'tag_string') {
    
        var tag_value = value;
    
        // Split existing tag list into an array.
        var selected_tags = showcase_prefs['tag_string'].split('-');
        if (selected_tags.length > 0) {
            var new_tag_string = '';
            var add_this_tag = true;
            $(selected_tags).each(function(index, value2) {
                if (value2 > 0) {
                    if (value2 != value) {
                        new_tag_string = new_tag_string + '' + value2 + "-";
                    } else {
                        add_this_tag = false;
                    }
                }
            });
            if (add_this_tag) new_tag_string += value + '-';
            value = new_tag_string;
        } else {
            value += '-';
        }
    }
    
    
    // Change the visual status of items depending on the change, before updating prefs with the new value
    if (key == 'featured_new_popular') {
    
        if ($('#tag_box').parent().attr('id') != 'showcase_bottom') {
            showcase_lower_tags();
        }
        
        $('#showcase_link_'+showcase_prefs['featured_new_popular']).removeClass('box_selected');
        $('#showcase_link_'+value).addClass('box_selected');
        $('#tag_box .box_selected').removeClass('box_selected');
        
    } else if (key == 'tag_string') {
    
        // If we're going to tag mode, unselect the current view mode
        if (showcase_prefs['tag_string'] == '') {
            $('html, body').animate({ scrollTop: 0 }, 'fast');
            showcase_lift_tags();
        }

        if (add_this_tag) {
            $('#tag_'+tag_value).addClass('box_selected');
        } else {
            $('#tag_'+tag_value).removeClass('box_selected');
        }
        
    }
    
    
    showcase_prefs[key] = value;

    
    // Change other prefs based on specific criteria
    if (key == 'tag_string') {
        showcase_prefs['featured_new_popular'] = 'new';
    } else if (key == 'featured_new_popular') {
        showcase_prefs['tag_string'] = '';
    }
    
    showcase_prefs['last_item_id']      = false;
    showcase_prefs['column']            = 1;
    showcase_prefs['col_pause_counter'] = 0;
    showcase_prefs['col_pause_mark']    = false;
    showcase_prefs['qty_visible']       = 0;
    
    var showcase_prefs_string = $.toJSON(showcase_prefs);
    $('#showcase_prefs').val(showcase_prefs_string);


}



var showcase_append_more_link = false;

function showcase_loadNEW() {
    
    var showcase_prefs = jQuery.parseJSON($('#showcase_prefs').val());
    
    $('#ajax_spinner').show();
    $.ajax({
        url: '/includes/ajax_showcase_loadNEW.php',
        type: 'POST',
        data: { prefs: showcase_prefs },
        success: function(data) {
            $('#ajax_spinner').hide();
            
            if (showcase_prefs['last_item_id'] > 0) {
                $('#showcase_items').append(data);
            } else {
                $('#showcase_items').html(data);
            }
            
            if (showcase_append_more_link) {
                $('#showcase_load_more_link_box').html("<a id='showcase_load_more_link' href='javascript:void(0);' onClick=\"showcase_loadNEW();\">Load More</a>");
            } else {
                $('#showcase_load_more_link_box').html('');
            }
            
        }
    });
    

}



function update_blurb_widget(widget_id, blurb_id, color_id, parameters) {
    theseParams = 'widget_id='+widget_id+'&blurb_id='+blurb_id+'&color_id='+color_id;
    if (parameters) theseParams = theseParams + '&'+ parameters;
    $.ajax({
        url: '/includes/blurb_widgets.php',
        type: 'POST',
        data: theseParams,
        success: function(data) {
            $('#blurb_widget_'+blurb_id).html(data);
            if (widget_id == 1) {
                $('#blurb_widget_'+blurb_id).slideDown('fast');
            } else {
                $('#blurb_widget_'+blurb_id).show();
            }
        }
    });
}


function swap_blurb_editing_panels() {
    if ($('#edit_blurb_widget').is(':hidden')) {
        $('#edit_blurb_normal').slideUp('fast', function() {
            $('#panel_title').html('Choose a Blurb Widget');
            $('#edit_blurb_widget').slideDown('fast');
        });
    } else {
        $('#edit_blurb_widget').slideUp('fast', function() {
            $('#panel_title').html('Edit Blurb');
            $('#edit_blurb_normal').slideDown('fast');
        });
    }
}


function close_employee_directory(id) {
    $('#w_user_details_'+id+" .close").hide();
    $('#w_user_details_'+id).slideUp('fast');
    $('#user_suggest_'+id).val('');
}













function gallery_init(id, photo_id) {

    dim_start("gallery_close()");
    $('body').css({'overflow': 'hidden'});

    $('body').prepend("<div id='gallery' ontouchstart=\"touchStart(event,'gallery');\" ontouchmove=\"touchMove(event);\" ontouchend=\"touchEnd(event);\" ontouchcancel=\"touchCancel(event);\"><a id='gallery_close' href='javascript:void(0);' onClick=\"gallery_close();\"></a></div>");

    $('#gallery').data('gallery_id', id);

    gallery_load_photo(photo_id);

    $('body').prepend("<div id='gallery_controls'><div id='photo_caption'></div><div id='gallery_title'></div></div>");
    
    $('#gallery_controls').prepend("<a id='photo_viewall' href='javascript:void(0);' onClick=\"gallery_view_all();\">View All</a><a id='photo_share' href='javascript:void(0);' onClick=\"gallery_toggle_sharebox();\">Share</a><a id='photo_download' href='' target='_new'>Download</a>");
    
    $('#gallery_controls').prepend("<div id='gallery_arrows'><a id='photo_prev' href='javascript:void(0);' onClick=\"gallery_load_photo('prev');\"></a><a id='photo_next' href='javascript:void(0);' onClick=\"gallery_load_photo('next');\"></a><div id='gallery_photo_num'></div></div>");

    $('#gallery').fadeIn(300);
    $('#gallery_controls').delay(300).animate({'margin-bottom': '0px'}, 300);
    
}







var current_photo_load = false;

function gallery_load_photo(photo_id) {

    if (photo_id == 'prev' && $('#gallery').data('prev_photo')) {
        photo_id = $('#gallery').data('prev_photo');
    } else if (photo_id == 'next' && $('#gallery').data('next_photo')) {
        photo_id = $('#gallery').data('next_photo');
    } else if (photo_id == 'prev' || photo_id == 'next') {
        return false;
    }

    if ($('#gallery_photo').length) $('#gallery_photo').remove();
    $('#photo_caption').hide();
    
    if (current_photo_load) {
        // If an ajax request is pending for a previous photo load, abort it before issuing a new one.
        current_photo_load.abort();
    }
    
    var load_gallery_info = false;
    if ($('#gallery_title').length < 1) load_gallery_info = 'yes';

    current_photo_load = $.ajax({
        url: '/includes/gallery_photo2.php',
        type: 'POST',
        dataType: 'json',
        data: {gallery_id: $('#gallery').data('gallery_id'), photo_id: photo_id, load_gallery_info: load_gallery_info},
        success: function(data) {
            
            $('#gallery').append("<img id='gallery_photo' src='" + data.filename + "' onLoad=\"gallery_center_photo();\">");
            
            gallery_center_photo();
            
            $('#gallery_photo').fadeIn(400);
            
            $('#gallery_photo_num').html(data.num + ' of ' + data.total_photos);
            
            if (data.prev_photo) {
                $('#gallery').data('prev_photo', data.prev_photo);
                $('#photo_prev').fadeIn('fast');
            } else {
                $('#gallery').data('prev_photo', false);
                $('#photo_prev').fadeOut('fast');
            }
            
            if (data.next_photo) {
                $('#gallery').data('next_photo', data.next_photo);
                $('#photo_next').fadeIn('fast');
            } else {
                $('#gallery').data('next_photo', false);
                $('#photo_next').fadeOut('fast');
            }
            
            if ($('#gallery_audio_note').length > 0) {
                $('#gallery_audio_note').fadeOut('fast');
            }
            
            
            if (load_gallery_info) {
                $('#gallery_title').html(data.title);
                if (Modernizr.audio) {
                    if (data.audio_mp3 || data.audio_ogg) {
                    
                        $('#gallery_controls').prepend("<div id='gallery_audio_note'><a href='javascript:void(0);' id='gallery_audio_close' onClick=\"$('#gallery_audio_note').fadeOut('fast');\"></a><img src='/images/main/audio.png' id='audio_img'><div id='sound_note_head'>Enhanced With Audio</div>This gallery has an audio file attached below. Listen along while browsing photos.</div>");
                        $('#gallery_audio_note').delay('1000').fadeIn('slow');

                        var audio_tag = "<div id='gallery_audio'><audio id='gallery_audio_file' controls='controls'>";
                        if (data.audio_mp3) audio_tag += "<source src='" + data.audio_mp3 + "' type='audio/mp3' />";
                        if (data.audio_ogg) audio_tag += "<source src='" + data.audio_ogg + "' type='audio/ogg' />";
                        audio_tag += "Your browser does not support the audio tag.</audio></div>";
                        
                        $('#gallery_title').append(audio_tag);
                    }
                }
            }
            
            
            $('#gallery_controls').fadeIn('fast');

            $('#gallery').data('link', false);
            if (data.link) $('#gallery').data('link', data.link);
            
            $('#photo_download').attr('href', data.filename);
            
            if (data.caption) { $('#photo_caption').html(data.caption).fadeIn(); }
            
            current_photo_load = false;
            
            preload(data.preload);
            
        },
        error:function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    });
}



function gallery_center_photo() {
    var photo_top_offset = Math.round(($('#gallery').height() - $('#gallery_photo').height()) / 2);
    $('#gallery_photo').css("margin-top", photo_top_offset + "px");
}



function gallery_toggle_sharebox(manual_show_or_hide) {
    var show_or_hide = 'show';
    if (manual_show_or_hide == 'hide' || (!manual_show_or_hide && $("#gallery_sharebox").length)) {
        show_or_hide = 'hide';
    }
    if (show_or_hide == 'hide') {
        $('#gallery_sharebox').fadeOut(200, function() {
            $("#gallery_sharebox").remove();
        });
    } else {
        $('body').prepend("<div id='gallery_sharebox'><img src='/images/main/share_icon_large.png' width='45' height='38' style='margin: 0px 12px -6px 0px;'><span style='font-size: 24px;'>Share this Photo</span><div id='gallery_sharebox_desc'>Copy the full address below to link directly to this photo.</div><input type='text' id='gallery_sharebox_input' value='" + $('#gallery').data('link') + "'><div id='gallery_sharebox_button_wrapper'><button type='button' class='button_right button_gray' onClick=\"gallery_toggle_sharebox();\">Close</button></div></div>");
        $('#gallery_sharebox').css({'margin-left': Math.round(($(window).width() - $('#gallery_sharebox').width()) / 2) + 'px', 'margin-top': Math.round(($(window).height() - $('#gallery_sharebox').height()) / 2.5) + 'px'}).fadeIn(300);
    }
}



function gallery_view_all() {

    $('#gallery_photo').fadeOut('fast');
    gallery_toggle_sharebox('hide');
    
    $('#gallery_controls').fadeOut('fast');
    
    $.ajax({
        url: '/includes/gallery_photo2.php',
        type: 'POST',
        dataType: 'json',
        data: {gallery_id: $('#gallery').data('gallery_id'), thumbs: 'true'},
        success: function(data) {
            
            $('#gallery').prepend("<div id='gallery_thumbs'></div>");
            
            $(data.photos).each(function() {
                $('#gallery_thumbs').append("<div class='thumb'><a href='javascript:void(0);' onClick=\"gallery_view_all_close(); gallery_load_photo('" + this.id + "');\"><img src='/images/photos_thumb/" + this.filename + "' width='" + this.width + "' height='" + this.height + "'></a></div>");
            });
            
        },
        error:function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    });

}

function gallery_view_all_close() {
    $('#gallery_thumbs').fadeOut('fast', function() { $(this).remove() });
}





function gallery_close() {
    $('body').css({'overflow': 'auto'});
    gallery_toggle_sharebox('hide');
    $('#gallery').fadeOut('fast', function() { $('#gallery').remove()});
    $('#gallery_controls').animate({'margin-bottom': '-120px'}, 200, function() {$('#gallery_controls').remove()});
    dim_end();
    window.location.hash = ''; // Remove hash so when page is reloaded, gallery doesn't open back up.
}

function gallery_toggle_thumbs() {
    $('#gallery_lower').hide();
    $('#gallery_thumbs').html('<br>Loading...').show();
    $.ajax({
        url: '/includes/gallery_thumbs.php',
        type: 'POST',
        data: {gallery_id: $('#gallery').data('gallery_id')},
        success: function(data) {
            $('#gallery_thumbs').html(data);
        }
    });
}








function gallery_load_photo_showcase(photo_id) {
    $.ajax({
        url: '/includes/gallery_photo_showcase.php',
        type: 'POST',
        data: {gallery_id: $('#showcase_photo_frame').data('gallery_id'), photo_id: photo_id},
        dataType: 'json',
        success: function(data) {
            
            // Redraw the contents of the prev / next links div
            
            if (data.filename) $('#showcase_photo_frame').html("<a href='/images/photos/" + data.filename + "' target='_new'><img src='/images/photos_small/" + data.filename + "' width='" + data.width + "' height='" + data.height + "'></a>");
            
            if (data.caption) {
                $('#showcase_photo_frame').append("<div id='caption'>" + data.caption + "</div>");
                $('#caption').css({'margin-top' : '-' + ($('#caption').height() + 20) + 'px'});
                $('#caption').fadeIn();
                
            }

            if (data.prev_photo_id) {
                $('#showcase_photo_frame').data('prev_photo', data.prev_photo_id);
            } else {
                $('#showcase_photo_frame').data('prev_photo', false);
            }
            
            if (data.next_photo_id) {
                $('#showcase_photo_frame').data('next_photo', data.next_photo_id);
            } else {
                $('#showcase_photo_frame').data('next_photo', false);
            }
            
            
            $('#showcase_photo_prev_next_links').html('');
            if (data.prev_photo_id) {
                $('#showcase_photo_prev_next_links').append("<a class='arrow_white_prev' href='javascript:void(0);' onClick=\"gallery_load_photo_showcase('" + data.prev_photo_id + "');\"></a>");
            } else {
                $('#showcase_photo_prev_next_links').append("<div class='arrow_white_hidden'></div>");
            }
            if (data.next_photo_id) {
                $('#showcase_photo_prev_next_links').append("<a class='arrow_white_next' href='javascript:void(0);' onClick=\"gallery_load_photo_showcase('" + data.next_photo_id + "');\"></a>");
            } else {
                $('#showcase_photo_prev_next_links').append("<div class='arrow_white_hidden'></div>");
            }
            $('#showcase_photo_prev_next_links').append("<div id='photo_num_count'>" + data.num + " of " + data.total_photos + "</div>");
            
            preload(data.preload);
        }
    });
}

function preload(arrayOfImages) {
    $(arrayOfImages).each(function() {
        $('<img/>')[0].src = this;
    });
}






function dim_start(div_clicked_function) {
    $('#document_dim').remove(); // In case any old DIVs are hanging around
    
    var div_clicked_function_js = "";
    if (div_clicked_function) div_clicked_function_js = " onClick=\"" + div_clicked_function + ";\"";
    
    $('body').append("<div id='document_dim'"+div_clicked_function_js+"></div>");
    $("#document_dim").css("height", $(document).height());
    $("#document_dim").fadeTo(300, 1.0);
}

function dim_end() {
    $('#document_dim').fadeOut(function() {
        $("#document_dim").remove();
    });
}





function open_cal_event(event_id, day_of_week, bgcolor) {
    close_all_open_panels('cal_popup');
    
    $('#cal_popup').draggable({cancel: '#cal_popup_inner, #cal_event_close'});
    
    $('#cal_popup_inner').html('Loading...');
    
    var position = $('#cal_event_'+event_id).position();
    var thisMarginLeft = 0;
    if (day_of_week) {
        thisMarginLeft = Math.ceil((day_of_week - 1) * 49.7) - 10;
    }
    
    $('#cal_popup').css({top: (position.top - 50) + "px", marginLeft: thisMarginLeft + "px"});
    $('#cal_popup').fadeIn('fast');
    
    if (bgcolor) {
        var thisbgcolor = bgcolor;
    } else {
        var thisbgcolor = '333333';
    }
    
    $.ajax({
        url: '/includes/ajax_cal_event_popup.php',
        type: 'POST',
        dataType: 'json',
        data: {event_id: event_id},
        success: function(data) {
            if (data.error) {
                $('#cal_popup_title').css('backgroundColor', 'black').html('Error: '+data.error);
                $('#cal_popup_inner').html('');
            } else {
            
                if (!bgcolor && data.color) thisbgcolor = data.color;
                
                if (data.title == '') data.title = '&nbsp;';
                
                $('#cal_popup_title').css('backgroundColor', '#'+thisbgcolor).html(data.title);
                
                var cal_details = "<div class='cal_event_label'>Date</div><div class='cal_event_details'>" + data.date_timestring + "</div>";
                if (data.event_timestring) cal_details += "<div class='cal_event_label'>Time</div><div class='cal_event_details'>" + data.event_timestring + "</div>";
                if (data.location) cal_details += "<div class='cal_event_label'>Location</div><div class='cal_event_details'>" + data.location + "</div>";
                if (data.contact) cal_details += "<div class='cal_event_label'>Contact</div><div class='cal_event_details'>" + data.contact + "</div>";
                if (data.note) cal_details += "<div class='cal_event_label'>Note</div><div class='cal_event_details'>" + data.note + "</div>";
                if (data.link) cal_details += "<div class='cal_event_label'>Link</div><div class='cal_event_details nowrap'><a href='" + data.link_full + "' target='_new'>" + data.link + "</a></div>";
                if (data.filepath) cal_details += "<div class='cal_event_label' style='padding-top: 5px;'>Attachment</div><div class='cal_event_details nowrap'><a href='" + data.filepath + "' target='_new'><img src='" + data.file_thumb + "' " + data.thumb_size + ">" + data.file_name + "</a></div>";
                if (data.cal_title) cal_details += "<div class='cal_event_label'>Calendar</div><div class='cal_event_details'><div style='float: left; width: 14px; height: 14px; margin-right: 3px; background: #" + data.color + ";'></div>" + data.cal_title + "</div>";
                
                if (data.page_access == 3) {
                    cal_details += "<div class='cal_event_label'>&nbsp;</div><div style='margin-top: 15px;' class='cal_event_details tiny'><a class='el' href='javascript:void(0);' onClick=\"update_panel('show', 'edit_event', 's=" + data.site_id + "&p=" + data.page_id + "&event_id=" + data.event_id + "');\">Edit</a> | <a class='el' href='javascript:void(0);' onClick=\"update_panel('show', 'edit_event', 's=" + data.site_id + "&p=" + data.page_id + "&duplicate_id=" + data.event_id + "');\">Duplicate</a></div>";
                }
                
                cal_details += "<br style='clear: both;'>";
                
                $('#cal_popup_inner').html(cal_details);

            }
        }
    });
    
}

function close_cal_event() {
    $('#cal_popup').fadeOut('fast');
}

function process_login_3(domain) {

    disbale_save_button('login', 'Login...');
    
    $.ajax({
        url: '/includes/login.php',
        type: 'POST',
        data: { login_user: $('#login_user').val(), login_pass: $('#login_pass').val(), submit_login: 'true', domain: domain },
        success: function(data) {
            if (data == 'n') {
                $('#login_error').slideUp('fast').slideDown('fast');
                this_button = document.getElementById('save_button_login');
                this_button.style.backgroundImage       = "url(/images/main/buttons3.png)";
                this_button.style.backgroundPosition    = "-1px -91px";
                this_button.style.cursor                = "pointer";
                this_button.childNodes[0].nodeValue     = 'Login';
            } else {
                window.opener.location.href = data;
                window.close();
            }
        }
    });
    
    return false;

}


function openLoginWindow() {
    w = 500;
    h = 350;
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    window.open('https://'+document.domain+'/login2/?domain='+document.domain, '186_login_window', 'height='+h+',width='+w+',top='+wint+',left='+winl+',toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no');
    return false;
}


function photoUploadAllComplete() {
    $('#button_cancel').hide();
    $('#button_done').show();
}


function update_user_suggest_bin(id) {
    $.ajax({
        url: '/includes/ajax_user_suggest_bin.php',
        type: 'GET',
        dataType: "json",
        data: {user_string: $('#user_suggest_values_'+id).val()},
        success: function(data) {
            $('#user_suggest_bin_'+id).html('');
            var new_html = '';
            if (data.results > 0) {
                $.each(data.matches, function(index, value) {
                    new_html += "<div class='user_suggest_bin_box'><a class='user_bin_box_del' href='javascript:void(0);' onClick=\"user_suggest_remove('" + id + "', '" + index + "');\"></a>" + value + "</div>";
                });
                new_html += "<br style='clear: both;'>";
                $('#user_suggest_bin_'+id).html(new_html).slideDown('fast');
            } else {
                $('#user_suggest_bin_'+id).html('').slideUp('fast');
            }
        }
    });
}


function user_suggest_remove(id, user_id) {
    var new_user_string = '';
    var user_parts = $('#user_suggest_values_'+id).val().split('-');
    
    $.each(user_parts, function(index, value) {
        if (value > 0 && value != user_id) {
            new_user_string += '-' + value;
        }
    });
    
    $('#user_suggest_values_'+id).val(new_user_string);
    update_user_suggest_bin(id);
}

function user_suggest_add(id, user_id_string) {
    $('#user_suggest_values_'+id).val( $('#user_suggest_values_'+id).val() + user_id_string);
    update_user_suggest_bin(id);
}




function update_form_date(id) {
    this_year   = document.getElementById('date_year_'+id).value;
    this_month  = document.getElementById('date_month_'+id).value;
    if (this_month < 10) this_month = '0'+this_month;
    this_day    = document.getElementById('date_day_'+id).value;
    if (this_day < 10) this_day = '0'+this_day;
    document.getElementById(id).value = this_year + '-' + this_month + '-' + this_day;
}

function toggle_form_date_ignore(id) {
    set_disabled_to = false;
    if (document.getElementById('date_ignore_'+id).checked) {
        set_disabled_to = true;
        document.getElementById(id).value = '9999-12-31';
    } else {
        update_form_date(id);
    }
    document.getElementById('date_year_'+id).disabled = set_disabled_to;
    document.getElementById('date_month_'+id).disabled = set_disabled_to;
    document.getElementById('date_day_'+id).disabled = set_disabled_to;

}

function update_form_time(id) {
    this_hour   = document.getElementById('time_hour_'+id).value;
    this_minute = document.getElementById('time_minute_'+id).value;
    this_ampm   = document.getElementById('time_ampm_'+id).value;
    if (this_ampm == 'pm' && this_hour != 12) {
        this_hour = (this_hour - 0) + 12;
    } else if (this_ampm == 'am' && this_hour == 12) {
        this_hour = '00';
    }
    document.getElementById(id).value = this_hour + ':' + this_minute + ':00';

}

function toggle_form_time_ignore(id, alt_id) {
    set_disabled_to = false;
    if (document.getElementById('time_ignore_'+id).checked) {
        set_disabled_to = true;
        document.getElementById(id).value = '00:00:01';
        if (alt_id) document.getElementById(alt_id).value = '00:00:01';
    } else {
        update_form_time(id);
        if (alt_id) update_form_time(alt_id);
    }
    document.getElementById('time_hour_'+id).disabled   = set_disabled_to;
    document.getElementById('time_minute_'+id).disabled = set_disabled_to;
    document.getElementById('time_ampm_'+id).disabled   = set_disabled_to;
    if (alt_id) {
        document.getElementById('time_hour_'+alt_id).disabled   = set_disabled_to;
        document.getElementById('time_minute_'+alt_id).disabled = set_disabled_to;
        document.getElementById('time_ampm_'+alt_id).disabled   = set_disabled_to;
    }
}


function update_swatch_selection(id, color) {
    if (currently_selected_swatch_color) {
        document.getElementById('swatch_'+currently_selected_swatch_color).style.border = "3px solid #FFFFFF";
    }
    currently_selected_swatch_color = color;
    document.getElementById('swatch_'+color).style.border = "3px solid #F4D600";
    document.getElementById(id).value = color;
}

function update_icon_selection(id, icon) {
    if (currently_selected_icon) {
        document.getElementById('icon_'+currently_selected_icon).style.border = "3px solid #FFFFFF";
    }
    currently_selected_icon = icon;
    document.getElementById('icon_'+icon).style.border = "3px solid #F4D600";
    document.getElementById(id).value = icon;
}

function update_page_type(id, page_type_id) {
    if (document.getElementById(id).value > 0) {
        $('#div_'+id+'_'+$('#'+id).val()).removeClass('choice_box_selected');
    }
    $('#'+id).val(page_type_id);
    $('#div_'+id+'_'+page_type_id).removeClass('choice_box_hover').addClass('choice_box_selected');
}

function toggle_reply_comment(mode, item_id, reply_comment_id) {
    if (mode == 'show') {
        $('#comment_reply_'+item_id).slideDown('fast');
        $('#comment_reply_id_'+item_id).val(reply_comment_id);
        $('#comment_text_'+item_id).focus();
        scroll_to_id('comment_reply_'+item_id);
    } else {
        $('#comment_reply_'+item_id).slideUp('fast');
        $('#comment_reply_id_'+item_id).val('');
    }
}

function checkCommentForm(item_id) {
    this_error = false;
    if ($('#comment_text_'+item_id).val() == '') {
        this_error = "Please enter a comment.";
        if ($('#comment_name_'+item_id).val() == '') this_error = "Please enter a comment and a name.";
    } else if ($('#comment_name_'+item_id).val() == '') {
        this_error = 'Please enter a name.';
    }
    return this_error;
}

function scroll_to_id(id){
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}

function update_hidden_fields() {
    max_columns = 8;
    active_columns = $('#active_columns').val();
    active_columns++;
    if (active_columns <= max_columns) {
        $('#active_columns').val(active_columns);
        $('#item_'+active_columns).slideDown('fast');
    }
    if (active_columns == max_columns) {
        $('#col_add_link').slideUp('fast');
    }
}

function remove_table_column(column_id) {
    window.document.getElementById('delete_columns').value = window.document.getElementById('delete_columns').value + '-' + column_id;
    $('#delete_columns').val($('#delete_columns').val() + '-' + column_id);
    $('#item_col_'+column_id).slideUp('fast');
    $('#item_del_'+column_id).slideDown('fast');
}

function undo_remove_table_column(column_id) {
    var del_col_val = $('#delete_columns').val();
    str_pieces2 = del_col_val.split('-');
    new_del_string = '';
    for (var i=0;i<str_pieces2.length;i++) {
        if (str_pieces2[i] != '' && str_pieces2[i] != column_id) {
            new_del_string = new_del_string + '-' + str_pieces2[i];
        }
    }
    $('#delete_columns').val(new_del_string)
    $('#item_del_'+column_id).slideUp('fast');
    $('#item_col_'+column_id).slideDown('fast');
}

function remove_gallery_photo(photo_id) {
    $('#delete_photos').val( $('#delete_photos').val() + '-' + photo_id);
    $('#gallery_photo_edit_'+photo_id).fadeOut('fast');
    $('#gallery_photo_delete_'+photo_id).fadeIn('fast');
}

function undo_remove_gallery_photo(photo_id) {
    str_pieces2 = window.document.getElementById('delete_photos').value.split('-');
    new_del_string = '';
    for (var i=0;i<str_pieces2.length;i++) {
        if (str_pieces2[i] != '' && str_pieces2[i] != photo_id) {
            new_del_string = new_del_string + '-' + str_pieces2[i];
        }
    }
    $('#delete_photos').val(new_del_string);
    $('#gallery_photo_delete_'+photo_id).fadeOut('fast');
    $('#gallery_photo_edit_'+photo_id).fadeIn('fast');
}



function remove_gallery_photo2(photo_id) {
    $('#delete_photos').val($('#delete_photos').val() + '-' + photo_id);
    $('#gallery_photo_delete_'+photo_id).fadeIn('fast');
    $('#thumb_del_icon_'+photo_id).fadeOut('fast');
}

function undo_remove_gallery_photo2(photo_id) {
    str_pieces2 = window.document.getElementById('delete_photos').value.split('-');
    new_del_string = '';
    for (var i=0;i<str_pieces2.length;i++) {
        if (str_pieces2[i] != '' && str_pieces2[i] != photo_id) {
            new_del_string = new_del_string + '-' + str_pieces2[i];
        }
    }
    $('#delete_photos').val(new_del_string);
    $('#gallery_photo_delete_'+photo_id).fadeOut('fast');
    $('#thumb_del_icon_'+photo_id).fadeIn('fast');
}






function update_scale(sliderValue) {
    
    this_img = document.getElementById('crop_img');
    
    cur_width   = Math.round(sliderValue * min_width);
    cur_height  = Math.round(sliderValue * min_height);
    
    cur_left    = -Math.round((cur_width  * cur_vc_x) - (canvas_w / 2));
    cur_top     = -Math.round((cur_height * cur_vc_y) - (canvas_h / 2));
    
    // Make sure that new X and Y will not be too high or too low (exposing background of editing canvas)
    if (cur_left > 0) cur_left = 0;
    if (cur_top > 0) cur_top = 0;
    
    if (cur_width + cur_left < canvas_w) {
        cur_left = -(cur_width - canvas_w);
    }
    
    if (cur_height + cur_top < canvas_h) {
        cur_top = -(cur_height - canvas_h);
    }

    cur_scale = sliderValue / max_scale;
    
    this_img.style.width    = cur_width + "px";
    this_img.style.height   = cur_height + "px";
    
    this_img.style.left     = cur_left + "px";
    this_img.style.top      = cur_top + "px";
    
}
function getVisualCenterX() {
    cur_vc_x = (Math.abs(cur_left) + (canvas_w / 2)) / cur_width;
}
function getVisualCenterY() {
    cur_vc_y = (Math.abs(cur_top) + (canvas_h / 2)) / cur_height;
}
function calc_overhang(x, y) {
    oh_x = (cur_width + x) - canvas_w;
    oh_y = (cur_height + y) - canvas_h;
    return [oh_x, oh_y];
}
function save_crop(tmp_image_name) {
    params = "crop=true&x1="+Math.abs(cur_left)+"&y1="+Math.abs(cur_top)+"&stage_w="+canvas_w+"&stage_h="+canvas_h+"&scale="+(cur_scale*100)+"&tmpimg="+tmp_image_name;
    update_panel('show', 'avatar_edit', params);
}

