var software_$ = jQuery.noConflict(true);

software_$(document).ready(function() {
    // prepare the toolbar button, if it exists
    var toolbar_button = document.getElementById('software_fullscreen_toggle');
    
    // if the toolbar button exists, then initialize toolbar features
    if (toolbar_button) {
        // if the toolbar's display is set to none, then set that the toolbar is disabled
        if (document.getElementById('software_toolbar').style.display == 'none') {
            var toolbar_enabled = false;
            
        // else the toolbar's display is not set to none, so set that the toolbar is enabled
        } else {
            var toolbar_enabled = true;
        }
        
        // initialize variable for storing if the toolbar was originally enabled or disabled so that we can determine if the value has changed later
        var original_toolbar_enabled = toolbar_enabled;
        
        // add onclick event to toolbar button
        software_$(toolbar_button).click(function() {
            // if the toolbar is enabled, disable the toolbar
            if (toolbar_button.className == "up_button") {
                software_$("#software_toolbar").slideUp("fast");
                toolbar_button.className = "down_button";
                toolbar_button.title = 'Deactivate Fullscreen Mode';
                toolbar_enabled = false;
                
            // else the toolbar is disabled, so enable the toolbar
            } else if (toolbar_button.className == "down_button") {
                software_$("#software_toolbar").slideDown("fast");
                toolbar_button.className = "up_button";
                toolbar_button.title = 'Activate Fullscreen Mode';
                toolbar_enabled = true;
            }
        });
        
        // set toolbar height to the current height of the toolbar's iframe
        var toolbar_height = document.getElementById('software_toolbar').style.height.substring(0, document.getElementById('software_toolbar').style.height.lastIndexOf('p'));
        
        // set the original toolbar height to the starting height
        var original_toolbar_height = toolbar_height;
        
        // if the toolbar is expanded, then add onload event that will update the size of the toolbar
        if (toolbar_enabled == true) {
            document.getElementById('software_toolbar').onload = function() {
                // initialize variable for storing the height of the content in the toolbar
                var toolbar_content_height = '';
                
                // if the browser is webkit (e.g. Safari, Chrome), then use offsetHeight
                if (software_$.browser.safari) {
                    toolbar_content_height = document.getElementById('software_toolbar').contentWindow.document.body.offsetHeight;
                    
                // else the browser is another browser, so use scrollHeight
                } else {
                    toolbar_content_height = document.getElementById('software_toolbar').contentWindow.document.body.scrollHeight;
                }
                
                // update the height of the toolbar iframe so that it fits all of its content
                document.getElementById('software_toolbar').style.height = toolbar_content_height + 'px';
                
                // remember the new height
                toolbar_height = toolbar_content_height;
            };
        }
        
        // when the user browses away from this page, check to see if various properties need to be saved
        window.onbeforeunload = function() {
            // if the toolbar button exists and if any of the toolbar properties have changed, then save changes
            if ((original_toolbar_enabled != toolbar_enabled) || (original_toolbar_height != toolbar_height)) {
                // send an AJAX POST in order to save the toolbar properties in the session
                // async is set to false so that the request is sent before the browser window goes to the next page
                software_$.ajax({
                    type: 'POST',
                    url: '/' + software_directory + '/save_toolbar_properties.php',
                    data: 'enabled=' + toolbar_enabled + '&height=' + toolbar_height,
                    async: false
                });
            }
        }
    }
    
    // if the preview theme css toolbar is on the page, then update it's height
    if (document.getElementById("software_preview_design_code_toolbar")) {
        document.getElementById('software_preview_design_code_toolbar').onload = function() {
            // initialize variable for storing the height of the content in the toolbar
            var toolbar_content_height = '';
            
            // if the browser is webkit (e.g. Safari, Chrome), then use offsetHeight
            if (software_$.browser.safari) {
                toolbar_content_height = document.getElementById('software_preview_design_code_toolbar').contentWindow.document.body.offsetHeight;
                
            // else the browser is another browser, so use scrollHeight
            } else {
                toolbar_content_height = document.getElementById('software_preview_design_code_toolbar').contentWindow.document.body.scrollHeight;
            }
            
            // update the height of the toolbar iframe so that it fits all of its content
            document.getElementById('software_preview_design_code_toolbar').style.height = toolbar_content_height + 'px';
        };
    }
});

function change_states(country_element_id, state_element_id, preserve_state_value) {
    var country_element = document.getElementById(country_element_id);
    var state_element = document.getElementById(state_element_id);
    var new_states = new Array();
    var state_container_id = state_element_id + "_container";
    var state_element_value = state_element.value;

    var y = 0;
    // for all states in states array
    for (x = 0; x < states.length; x++) {
        // if this state is in the country that was selected, store this state
        if (states[x][2] == country_element.value) {
            new_states[y] = x;
            y++;
        }
    }

    // if there is at least one state for selected country, prepare selection drop-down field for state
    if (new_states.length > 0) {
        document.getElementById(state_container_id).innerHTML = '<select name="' + state_element_id + '" id="' + state_element_id + '" class="software_select"></select>';

        var new_state_element = document.getElementById(state_element_id);

        // set "-Select-" to be the first option of state selection drop-down field
        new_state_element.options[new_state_element.length] = new Option('-Select-', '');

        // loop through all states
        for (x = 0; x < new_states.length; x++) {
            new_state_element.options[new_state_element.length] = new Option(states[new_states[x]][0], states[new_states[x]][1]);
        }

    // else there is not a state for selected country, so prepare text field for state
    } else {
        document.getElementById(state_container_id).innerHTML = '<input type="text" name="' + state_element_id + '" id="' + state_element_id + '" class="software_input_text" />';
    }
    
    if ((preserve_state_value == true) && (state_element_value != '')) {
        document.getElementById(state_element_id).value = state_element_value;
    }
}

function change_quick_add_product_id(product_id)
{
    var selection_type;
    var default_quantity;
    var recipient_required;
    
    if (product_id) {
        selection_type = quick_add_products[product_id][0];
        default_quantity = quick_add_products[product_id][1];
        recipient_required = quick_add_products[product_id][2];        
    }
    
    // hide all quick add rows until we figure out which rows to show
    
    if (document.getElementById('quick_add_quantity_row')) {
        document.getElementById('quick_add_quantity_row').style.display = 'none';        
    }
    
    if (document.getElementById('quick_add_amount_row')) {
        document.getElementById('quick_add_amount_row').style.display = 'none';        
    }
    
    if (document.getElementById('quick_add_ship_to_row')) {
        document.getElementById('quick_add_ship_to_row').style.display = 'none';        
    }
    
    if (document.getElementById('quick_add_add_name_row')) {
        document.getElementById('quick_add_add_name_row').style.display = 'none';        
    }
    
    // if product has a quantity selection type, then prefill default quantity and show quantity row
    if (selection_type == 'quantity') {
        document.getElementById('quick_add_quantity').value = default_quantity;
        document.getElementById('quick_add_quantity_row').style.display = '';
    }
    
    // if product has a donation selection type, then show amount row
    if (selection_type == 'donation') {
        document.getElementById('quick_add_amount_row').style.display = '';
    }
    
    // if a recipient is required to be selected, then show ship to and add name rows
    if (recipient_required == true) {
        document.getElementById('quick_add_ship_to_row').style.display = '';
        document.getElementById('quick_add_add_name_row').style.display = '';
    }
}

function software_show_popup_menu(parent_element, position)
{
    parent_element.className = 'on';

    // loop through all nodes under li, in order to find a menu
    for (var i = 0; i < parent_element.childNodes.length; i++) {
        var node = parent_element.childNodes[i];
        
        // if node is a ul, then position menu and show menu
        if (node.nodeName == 'UL') {
            switch (position) {
                case 'Top':
                    node.style.left = '0';
                    node.style.top = '-' + node.offsetHeight + 'px';
                    break
                        
                case 'Bottom':
                    node.style.left = '0';
                    node.style.top = node.parentNode.offsetHeight + 'px';
                    break
                        
                case 'Left':
                    node.style.left = '-' + node.offsetWidth + 'px';
                    node.style.top = '0';
                    break;
                    
                case 'Right':
                    node.style.left = node.parentNode.offsetWidth + 'px';
                    node.style.top = '0';
                    break;
            }
            
            node.style.visibility = 'visible';
        }
    }
}

function software_hide_popup_menu(parent_element)
{
    parent_element.className = '';
    
    // loop through all nodes under li, in order to find a menu
    for (var i = 0; i < parent_element.childNodes.length; i++) {
        var node = parent_element.childNodes[i];
        
        // if node is a ul, then hide menu
        if (node.nodeName == 'UL') {
            node.style.visibility = 'hidden';
        }
    }
}

function software_update_accordion_menu(menu_item_id, parent_menu_item_id, menu_id) {
    
    // set open menu item id to the global open menu item id
    open_menu_item_id = eval("software_menu_"+menu_id+"_open_menu_item_id");
    
    // get display status of menu item
    var menu_item_display_status = document.getElementById("software_menu_item_" + menu_item_id).getElementsByTagName("ul")[0].style.display;
    
    // If the open menu item is not zero and it is not the parent menu item
    if ((open_menu_item_id != 0) && (open_menu_item_id != parent_menu_item_id)) {
        
        // Close the open menu item
        software_hide_accordion_menu(open_menu_item_id, parent_menu_item_id, menu_id);
    }
    
    // If the current menu item was not open
    if (menu_item_display_status != "block") {
        
        // then slide down the current menu item
        software_$(document.getElementById("software_menu_item_" + menu_item_id).getElementsByTagName("ul")[0]).slideDown("fast");
        
        // update open menu item id
        eval("software_menu_"+menu_id+"_open_menu_item_id = " + menu_item_id);
    }
}

function software_hide_accordion_menu(menu_item_id, stop_before_menu_item_id, menu_id) {
    
    // If this menu item id is equal to the stop before menu item id
    if (menu_item_id == stop_before_menu_item_id) {
        
        // set open menu item id to menu item id
        eval("software_menu_"+menu_id+"_open_menu_item_id = " + menu_item_id);
        
        // then return out of function
        return;
        
    // else if we have not reached the stop before menu item id
    } else {
        
        // slide up menu item
        software_$(document.getElementById("software_menu_item_" + menu_item_id).getElementsByTagName("ul")[0]).slideUp("fast");

        // if the direct parent to the li is the software menu ul
        if ((document.getElementById("software_menu_item_" + menu_item_id).parentNode.className) && 
            (document.getElementById("software_menu_item_" + menu_item_id).parentNode.className == "software_menu")) {
            
            // set open menu item id to 0
            eval("software_menu_"+menu_id+"_open_menu_item_id = 0");
            
            // return
            return;
            
        // else continue
        } else {
            
            // get menu item's parent menu item id
            parent_menu_item_id = document.getElementById("software_menu_item_" + menu_item_id).parentNode.parentNode.id;
            
            // remove software_menu_item from the id
            parent_menu_item_id = parent_menu_item_id.replace(/software_menu_item_/, "");
            
            // call this function again to close the parent menu item
            software_hide_accordion_menu(parent_menu_item_id, stop_before_menu_item_id, menu_id);
        }
    }
}

// this function initializes a dynamic ad region and starts the animation
function software_initialize_dynamic_ad_region(ad_region_name, transition_type, transition_duration, slideshow, slideshow_interval)
{
    // when the document is ready, then continue
    software_$(document).ready(function () {
        var ad_elements = software_$('#software_ad_region_' + ad_region_name + ' .items > div');
        var ads_element = software_$('#software_ad_region_' + ad_region_name + ' .items');
        
        // get the items container element and apply the hidden overflow in order to remove scrollbars
        var items_container_element = software_$('#software_ad_region_' + ad_region_name + ' .items_container').css('overflow', 'hidden');
        
        // get the menu item link element that has this target, select the menu item and it's corresponding ad
        function trigger(data) {
            var menu_item_link_element = software_$('#software_ad_region_' + ad_region_name + ' .menu').find('a[href$="' + data.id + '"]').get(0);
            
            // if this is a slide transition then call the function that updates it's menu items
            if (transition_type == 'slide') {
                software_update_current_ad_menu_item(menu_item_link_element);
                
            // else this is a fade transition type, so fade the content
            } else {
                software_fade_ads(menu_item_link_element, ad_region_name, transition_duration);
            }
        }
        
        // if the transition type is set to slide, prepare and initialize the slide effect
        if (transition_type == 'slide') {
            // float the ads so they are in a horizontal line
            ad_elements.css({
                'float' : 'left',
                'position' : 'relative' // IE fix to ensure overflow is hidden
            });
            
            // calculate a new width for the container (so it holds all ads)
            ads_element.css('width', ad_elements[0].offsetWidth * ad_elements.length);
            
            // add click event handler to menu items
            software_$('#software_ad_region_' + ad_region_name + ' .menu').find('a').click(function(){software_update_current_ad_menu_item(this)});
            
            // if there is a bookmark in the location, then select the corresponding menu item
            if (window.location.hash) {
                trigger({ id : window.location.hash.substr(1) });
                
            // else there is not a bookmark in the location, so select the first menu item
            } else {
                software_$('#software_ad_region_' + ad_region_name + ' ul.menu a:first').click();
            }
            
            // prepare the offset which is based on the padding of an element
            var offset = parseInt(ads_element.css('paddingTop') || 0) * -1;
            
            // prepare the scroll options for the scroll plugin
            var scrollOptions = {
                // set the element that has the overflow
                target: items_container_element,
                
                // set the container for the ads
                items: ad_elements,
                
                // set where the menu is located
                navigation: '.menu a',
                
                // set that the scrolling should only work horizontally
                axis: 'x',
                
                // set callback
                onAfter: trigger,
                
                // set offset based on padding
                offset: offset,

                // set the speed of the scroll effect
                duration: transition_duration,
                
                // easing - can be used with the easing plugin: 
                // http://gsgd.co.uk/sandbox/jquery/easing/
                easing: 'swing'
            };
            
            // initialize the serialScroll plugin that handles the scrolling effect and allows the slideshow effect to work
            software_$('#software_ad_region_' + ad_region_name).serialScroll(scrollOptions);
        
        // else prepare and initialize the the fade effect
        } else {
            // place the ads menu above the ads in the stack
            software_$('#software_ad_region_' + ad_region_name + ' .menu').css({'z-index' : '2'});
            
            // update the ads CSS to stack them on top of each other, put them at the bottom of the stack, and hide them all
            software_$('#software_ad_region_' + ad_region_name + ' .items_container .item').css({
                'position' : 'absolute',
                'top' : '0px',
                'left' : '0px',
                'z-index' : '0',
                'float' : 'none',
                'filter:alpha' : '(opacity=0)',
                '-moz-opacity' : '0',
                '-khtml-opacity' : '0',
                'opacity' : '0'
            });
            
            // add click event handler to menu items, then onclick prepare the menu items and call the fade ads function
            software_$('#software_ad_region_' + ad_region_name + ' .menu').find('a').click(function(mouse_event){
                // prevent the link from reloading the page
                mouse_event.preventDefault();
                
                // call the fade function
                software_fade_ads(this, ad_region_name, transition_duration);
            });
            
            // if there is a bookmark in the location, then unhide it's ad and select the corresponding menu item
            if (window.location.hash) {
                // set the corresponding ad to be visable
                software_$('#software_ad_region_' + ad_region_name + ' .items_container #' + window.location.hash.substr(1)).css({
                    'filter:alpha' : '(opacity=1)',
                    '-moz-opacity' : '1',
                    '-khtml-opacity' : '1',
                    'opacity' : '1'
                });
                
                // trigger the change to update the menu
                trigger({ id : window.location.hash.substr(1) });
                
            // else there is not a bookmark in the location, so unhide the first ad and select the first menu item
            } else {
                // set the first ad to be visable
                software_$(software_$('#software_ad_region_' + ad_region_name + ' .items_container .item')[0]).css({
                    'filter:alpha' : '(opacity=1)',
                    '-moz-opacity' : '1',
                    '-khtml-opacity' : '1',
                    'opacity' : '1'
                });
                
                // trigger the change to update the menu
                trigger({ id : software_$('#software_ad_region_' + ad_region_name + ' ul.menu a:first')[0].href.substr(software_$('#software_ad_region_' + ad_region_name + ' ul.menu a:first')[0].href.lastIndexOf('#') + 1) });
            }
        }
        
        // if slideshow is enabled for this ad region, then initialize slideshow
        if (slideshow == true) {
            // start the slideshow with the correct interval
            var cycle_timer = setInterval(function () {
                
                // if this transition type is a slide, then trigger the slide
                if (transition_type == 'slide') {
                    items_container_element.trigger('next');
                
                // else this is a fade so trigger the next fade
                } else {
                    // pass the next ad into the trigger function
                    trigger({ id : software_$(software_$('#software_ad_region_' + ad_region_name + ' ul.menu a.current')[0].parentNode).next('li')[0].firstChild.href.substr(software_$(software_$('#software_ad_region_' + ad_region_name + ' ul.menu a.current')[0].parentNode).next('li')[0].firstChild.href.lastIndexOf('#') + 1) });
                }
               
                // if we have reached the end of the slideshow, then stop slideshow
                if (software_$('#software_ad_region_' + ad_region_name + ' ul.menu li:last-child a').attr('class') == 'current') {
                    clearInterval(cycle_timer);
                   
                    // if this is the fade transition type, then send the slideshow back to the first ad after the set amount of time has passed
                    if (transition_type == 'fade') {
                        setTimeout("software_fade_ads('', '" + ad_region_name + "', " + transition_duration + ");", slideshow_interval * 1000);
                    }
                }
               
            }, slideshow_interval * 1000);
            
            // set some trigger elements to stop the slideshow
            var stop_triggers = software_$('#software_ad_region_' + ad_region_name + ' .menu').find('a') // menu items
                .add('#software_ad_region_' + ad_region_name + ' .items_container') // ads container
            
            // create a function to stop the slideshow
            function stop_slideshow() {
                // remove the stop triggers
                stop_triggers.unbind('click.cycle');
                
                // stop the slideshow
                clearInterval(cycle_timer);
            }
            
            // bind the stop slideshow function to the stop triggers
            stop_triggers.bind('click.cycle', stop_slideshow);
        }
    });
}

// this function fades one ad in and one ad out
function software_fade_ads(selected_menu_item, ad_region_name, transition_duration) {
    // if there is not a selected menu item, then set it to the first menu item
    if ((!selected_menu_item) || (selected_menu_item == '')) {
        selected_menu_item = software_$('#software_ad_region_' + ad_region_name + ' ul.menu a:first')[0];
    }
    
    // get the selected ad id
    var selected_ad_id = selected_menu_item.href.substr(selected_menu_item.href.lastIndexOf('#') + 1);
    
    var current_ad_id = 0;
    
    // if there is a current menu item, then get the current ad's id
    if (software_$('#software_ad_region_' + ad_region_name + ' .menu a.current')[0]) {
        current_ad_id = software_$('#software_ad_region_' + ad_region_name + ' .menu a.current')[0].href.substr(software_$('#software_ad_region_' + ad_region_name + ' .menu a.current')[0].href.lastIndexOf('#') + 1);
    }
    
    // update the current menu item
    software_update_current_ad_menu_item(selected_menu_item);
    
    // if the transition duration is 0, then default it to one second
    if (transition_duration == 0) {
        transition_duration = 1000;
    }
    
    // fade in the new ad, and after the fade is complete set it's z-index to 1 so it's on top of the stack
    software_$(software_$('#software_ad_region_' + ad_region_name + ' .items_container #' + selected_ad_id)[0]).animate({
        opacity: 1
    }, transition_duration, function () {
        software_$(software_$('#software_ad_region_' + ad_region_name + ' .items_container #' + selected_ad_id)[0]).css('z-index', '1');
    });
    
    // fade out the old ad, and after the fade is complete set it's z-index to 0 so that it is under the current ad
    software_$(software_$('#software_ad_region_' + ad_region_name + ' .items_container #' + current_ad_id)[0]).animate({
        opacity: 0
    }, transition_duration, function () {
        software_$(software_$('#software_ad_region_' + ad_region_name + ' .items_container #' + current_ad_id)[0]).css('z-index', '0');
    });
}

// this function updates the current menu item
function software_update_current_ad_menu_item(object)
{
    software_$(object)
        .parents('ul:first')
            .find('a')
                .removeClass('current')
            .end()
        .end()
        .addClass('current');
}

function prepare_content_for_html(content)
{
    var chars = new Array ('&','à','á','â','ã','ä','å','æ','ç','è','é',
                         'ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô',
                         'õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À',
                         'Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë',
                         'Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö',
                         'Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<',
                         '>','¢','£','¤','¥','¦','§','¨','©','ª','«',
                         '¬','­','®','¯','°','±','²','³','´','µ','¶',
                         '·','¸','¹','º','»','¼','½','¾');

    var entities = new Array ('amp','agrave','aacute','acirc','atilde','auml','aring',
                            'aelig','ccedil','egrave','eacute','ecirc','euml','igrave',
                            'iacute','icirc','iuml','eth','ntilde','ograve','oacute',
                            'ocirc','otilde','ouml','oslash','ugrave','uacute','ucirc',
                            'uuml','yacute','thorn','yuml','Agrave','Aacute','Acirc',
                            'Atilde','Auml','Aring','AElig','Ccedil','Egrave','Eacute',
                            'Ecirc','Euml','Igrave','Iacute','Icirc','Iuml','ETH','Ntilde',
                            'Ograve','Oacute','Ocirc','Otilde','Ouml','Oslash','Ugrave',
                            'Uacute','Ucirc','Uuml','Yacute','THORN','euro','quot','szlig',
                            'lt','gt','cent','pound','curren','yen','brvbar','sect','uml',
                            'copy','ordf','laquo','not','shy','reg','macr','deg','plusmn',
                            'sup2','sup3','acute','micro','para','middot','cedil','sup1',
                            'ordm','raquo','frac14','frac12','frac34');

    for (var i = 0; i < chars.length; i++) {
        myRegExp = new RegExp();
        myRegExp.compile(chars[i],'g');
        content = content.replace (myRegExp, '&' + entities[i] + ';');
    }

    return content;
}

// this is the timer used for the picnik button animation
var software_edit_image_button_timer = Array;

function software_show_or_hide_image_edit_button(image_id, event) 
{
    clearTimeout(software_edit_image_button_timer[image_id]);
    
    image = document.getElementById(image_id);
    
    // if the edit button is hidden then update it's position and show it
    if (event.type == 'mouseover') {
        // if this is not a photo gallery page, then adjust the position of the picnik button
        if (!software_$('.software_photo_gallery_album')[0]) {
            // if the images parent's position is not relative then set the position to be relative,
            // and get the position of the parent and add it to the relative image position to get the screen position
            if (image.offsetParent.style.position != 'relative') {
                // get the orginal position styling for the object
                var orignal_position_styling = image.offsetParent.style.position;
                
                // set it's position to be relative
                image.offsetParent.style.position = 'relative';
                
                // get the image's dimensions
                var image_left_position = image.offsetParent.offsetLeft + image.offsetLeft;
                var image_top_position = image.offsetParent.offsetTop + image.offsetTop;
                
                // switch the position back to what it was originally
                image.offsetParent.style.position = orignal_position_styling;
                
            // else the parent is relative so we do not need to get the parent's position
            } else {
                var image_left_position = image.offsetLeft;
                var image_top_position = image.offsetTop;
            }
            
            // update button position
            document.getElementById("software_edit_button_for_" + image_id).style.left = image_left_position + "px";
            document.getElementById("software_edit_button_for_" + image_id).style.top = image_top_position + "px";
        }
        
        // show the image
        document.getElementById("software_edit_button_for_" + image_id).style.display = "block";
        
    // else if the event was a mouseout, then slide up the button to hide it.
    } else if (event.type == 'mouseout') {
        software_edit_image_button_timer[image_id] = setTimeout('software_$(document.getElementById("software_edit_button_for_' + image_id + '")).slideUp("fast");', 250);
    }
}

function software_show_form_view_directory_summary(summary)
{
    // do different things based on which summary was selected
    switch (summary) {
        case 'most_recent':
            // show and hide summary tables
            document.getElementById('software_form_view_directory_summary_table_most_viewed').style.display = 'none';
            document.getElementById('software_form_view_directory_summary_table_most_active').style.display = 'none';
            document.getElementById('software_form_view_directory_summary_table_most_recent').style.display = '';
            
            // update font weight for summary links
            document.getElementById('software_form_view_directory_summary_link_most_viewed').style.fontWeight = '';
            document.getElementById('software_form_view_directory_summary_link_most_active').style.fontWeight = '';
            document.getElementById('software_form_view_directory_summary_link_most_recent').style.fontWeight = 'bold';
            
            break
                
        case 'most_viewed':
            // show and hide summary tables
            document.getElementById('software_form_view_directory_summary_table_most_recent').style.display = 'none';
            document.getElementById('software_form_view_directory_summary_table_most_active').style.display = 'none';
            document.getElementById('software_form_view_directory_summary_table_most_viewed').style.display = '';

            // update font weight for summary links
            document.getElementById('software_form_view_directory_summary_link_most_recent').style.fontWeight = '';
            document.getElementById('software_form_view_directory_summary_link_most_active').style.fontWeight = '';
            document.getElementById('software_form_view_directory_summary_link_most_viewed').style.fontWeight = 'bold';
            
            break
                
        case 'most_active':
            // show and hide summary tables
            document.getElementById('software_form_view_directory_summary_table_most_recent').style.display = 'none';
            document.getElementById('software_form_view_directory_summary_table_most_viewed').style.display = 'none';
            document.getElementById('software_form_view_directory_summary_table_most_active').style.display = '';
            
            // update font weight for summary links
            document.getElementById('software_form_view_directory_summary_link_most_recent').style.fontWeight = '';
            document.getElementById('software_form_view_directory_summary_link_most_viewed').style.fontWeight = '';
            document.getElementById('software_form_view_directory_summary_link_most_active').style.fontWeight = 'bold';
            
            break;
    }
}

// this function is responsible for initializing the edit region dialog
function software_initialize_edit_region_dialog()
{
    // initialize the edit region dialog
    software_$(software_$('#' + 'software_edit_region_dialog')[0]).dialog({
        autoOpen: false,
        modal: true,
        dialogClass: 'standard',
        open: function() {
            // set the dialog box's default width and height
            var dialog_width = 750;
            var dialog_height = 587;
            
            // if the dialog's new width is greater than the default, then set the width
            if ((software_$(window).width() * .75) >= dialog_width) {
                dialog_width = software_$(window).width() * .75;
            }
            
            // if the dialog's new height is greater than the default, then set the width
            if ((software_$(window).height() * .75) >= dialog_height) {
                dialog_height = software_$(window).height() * .75;
            }
            
            // set the width and height of the dialog based on the size of the window
            software_$('.standard.ui-dialog').css({
                width: dialog_width,
                height: dialog_height
            });
            
            var scrollbar_position = 0;
            
            // if there is a pag y offest, then get the scrollbar pos
            if (window.pageYOffset) {
                scrollbar_position = window.pageYOffset;
                
            // else this is probally IE, so get the scrollbar position for IE
            } else {
                scrollbar_position = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
            }
            
            // set the left position, by subtracting the width of the window from the width of the dialog and dividing by 2
            var dialog_top = (software_$(window).height() - software_$('.standard.ui-dialog').height()) / 2;
            
            // if the scrollbar is not at the very top of the page, then adjust the dialog box's top position
            if (scrollbar_position != 0) {
                dialog_top = dialog_top +    scrollbar_position;
            }
            
            // set the left position, by subtracting the width of the window from the width of the dialog and dividing by 2
            var dialog_left = (software_$(window).width() - software_$('.standard.ui-dialog').width()) / 2;
            
            // set the dialog box's position
            software_$('.standard.ui-dialog').css({
                top: dialog_top + 'px',
                left: dialog_left + 'px'
            });
            
            // remove the close button from the dialog
            software_$('.ui-dialog-titlebar-close').css('display','none');
        },
        close: function() {
            // destroy the text editor instance
            tinyMCE.execCommand('mceRemoveControl', false, 'software_edit_region_textarea');
            
            // clear the content
            document.getElementById('software_edit_region_textarea').value = '';
        },
        resize: function() {
            // if this is the old version of TinyMCE then resize it in a certain way
            if (tinyMCE.majorVersion == '2') {
                // set the text editor's width based on the dialog box
                software_$(software_$('#' + 'software_edit_region_dialog .mceEditorIframe')[0]).css({ 'width':  parseInt(software_$('.standard.ui-dialog').width() - 60) })
                
                // set the text editor's height based on the dialog box
                software_$(software_$('#' + 'software_edit_region_dialog .mceEditorIframe')[0]).css({ 'height':  parseInt(software_$('.standard.ui-dialog').height() - 240) })
                    
            // else this is the newer version of TinyMCE, so resize it in a different way
            } else {
                // set the text editor's width based on the dialog box
                software_$(software_$('#' + 'software_edit_region_dialog #software_edit_region_textarea_ifr')[0]).css({ 'width':  parseInt(software_$('.standard.ui-dialog').width() - 60) })
                
                // set the text editor's height based on the dialog box
                software_$(software_$('#' + 'software_edit_region_dialog #software_edit_region_textarea_ifr')[0]).css({ 'height':  parseInt(software_$('.standard.ui-dialog').height() - 240) })
            }
        }
    });
}

// this function is responsible for showing the edit region dialog
function software_open_edit_region_dialog(region_id, region_type, region_name, region_order)
{
    // open the dialog
    software_$(software_$('#' + 'software_edit_region_dialog')[0]).dialog('open');
    
    var region_name_for_title_bar = '';
    
    // if region type is page region, then set the region name
    if (region_type == 'pregion') {
        region_name_for_title_bar = 'Page Region #' + region_order;
    
    // else this is a common region, so the region name
    } else {
        region_name_for_title_bar = 'Common Region: ' + region_name;
    }
    
    // add the text editor title content to the title bar
    software_$('#' + 'software_edit_region_dialog')[0].parentNode.firstChild.firstChild.innerHTML = '<table class="title_bar_table"><tr><td style="width: 33%;">Rich-text Editor</td><td style="width: 33%; text-align: center;">' + region_name_for_title_bar + '</td><td style="width: 33%; text-align: right"><a href="javascript:void(0)" onclick="window.open(\'/' + software_directory + '/help.php?article=0080_rich_text_editor\', \'popup\', \'toolbar=no,location=no,directories=no,status=yes,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=600,height=520\')">Help</a></td></tr></table>';
    
    // update the hidden form fields with the values for this region
    software_$('#' + 'software_edit_region_dialog #region_id')[0].value = region_id;
    software_$('#' + 'software_edit_region_dialog #region_type')[0].value = region_type;
    
    // if there is a region order, then update the region order hidden field
    if (region_order != '') {
        document.getElementById('region_order').value = region_order;
    }
    
    // make ajax call to get the content from the database and set content for textarea value
    document.getElementById('software_edit_region_textarea').value = software_$.ajax({
        type: 'GET',
        url: '/' + software_directory + '/get_region_content.php',
        data: 'page_id=' + software_$('#software_edit_region_dialog #page_id')[0].value + '&region_id=' + region_id + '&region_type=' + region_type,
        async: false
    }).responseText;
    
    // initiate the editor
    tinyMCE.execCommand('mceAddControl', false, 'software_edit_region_textarea');
}

// this function is called once the editor is done loading
// the editor is resized to fit the dialog
// we have to have this separate function because we have to wait until the mceAddControl is completely done or the resize will not work
function software_activate_edit_region_dialog()
{
    // if this is the old version of TinyMCE then run code after a delay
    if (tinyMCE.majorVersion == '2') {
        // set the text editor's width based on the dialog box
        software_$(software_$('#' + 'software_edit_region_dialog .mceEditorIframe')[0]).css({ 'width':  parseInt(software_$('.standard.ui-dialog').width() - 60) })
        
        // set the text editor's height based on the dialog box
        software_$(software_$('#' + 'software_edit_region_dialog .mceEditorIframe')[0]).css({ 'height':  parseInt(software_$('.standard.ui-dialog').height() - 240) })
        
    // else this is the newest version of TinyMCE, so run code immediately
    } else {
        // set the text editor's width based on the dialog box
        software_$(software_$('#' + 'software_edit_region_dialog #software_edit_region_textarea_ifr')[0]).css({ 'width':  parseInt(software_$('.standard.ui-dialog').width() - 60) })
        
        // set the text editor's height based on the dialog box
        software_$(software_$('#' + 'software_edit_region_dialog #software_edit_region_textarea_ifr')[0]).css({ 'height':  parseInt(software_$('.standard.ui-dialog').height() - 240) })
    }
}

// this function initializes the photo gallery
function software_init_photo_gallery(thumbnails)
{
    // prepare the thumbnails
    software_$(thumbnails).each(function(index) {
        // save the thumbnail properties so that we can access them later
        var object_id = this[0];
        
        // get the image object
        var image = software_$('.software_photo_gallery_album #' + object_id)[0];
        
        // add mouseover and mouseout listeners to the image so that we can add a hover effect
        software_$(image).mouseover(function() { software_$(image).addClass('image_hover'); });
        software_$(image).mouseout(function() { software_$(image).removeClass('image_hover'); });
        
        // get the type of object (photo or album)
        var object_type = object_id.substr(0, object_id.lastIndexOf('_'));
        
        // if this is an album, then adjust it's frame's width and height, 
        // and then add a click event listener to send the browser to the next level of the photo gallery
        if (object_type == 'album') {
            // set a dealy to resize the album frames, 
            // this is required so that safari will correctly render the album frames
            setTimeout (function () {
                // adjust the width and height for the ablum frames
                software_$(software_$(software_$('.software_photo_gallery_album #' + object_id)[0].parentNode).find('#album_frame_1')[0]).css('width', software_$(image).outerWidth(true))
                software_$(software_$(software_$('.software_photo_gallery_album #' + object_id)[0].parentNode).find('#album_frame_1')[0]).css('height', software_$(image).outerHeight(true))
                software_$(software_$(software_$('.software_photo_gallery_album #' + object_id)[0].parentNode).find('#album_frame_2')[0]).css('width', software_$(image).outerWidth(true))
                software_$(software_$(software_$('.software_photo_gallery_album #' + object_id)[0].parentNode).find('#album_frame_2')[0]).css('height', software_$(image).outerHeight(true))
            }, 250);
            
            // add a click listener to send the browser to the next level of the photo gallery
            software_$(image).click(function() { 
                // get the album's folder id
                var folder_id = this.id.substr(this.id.lastIndexOf('_') + 1);
                
                // send the user to the next level of the photo gallery
                window.location = '/pages/' + software_page_name + '?folder_id=' + folder_id;
            });
        }
    });
    
    // initialize lightbox for all photos
    software_$('.software_photo_gallery_album .photo a.link').lightBox();
}
