// Add a script or stylsheet link resource to the head section of a page...
function loadjscssfile(filename, filetype, callback) {
    
    // External JavaScript file...
    if (filetype == "js") {
        var fileref = document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("src", filename);

    // External CSS file...
    } else if (filetype == "css") {
        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }

    // Establish callback if specified...
    if (typeof(callback) != "undefined") {
        
        // IE
        if (fileref.readyState) {
            fileref.onreadystatechange = function() {
                if (fileref.readyState == "loaded" || fileref.readyState == "complete") {
                    fileref.onreadystatechange = null;
                    callback();
                }
            };
            
        // Safari webkit...
        } else if (/safari/.test(navigator.userAgent.toLowerCase()) && !/chrome/.test(navigator.userAgent.toLowerCase())) {
            var img = document.createElement('img');
            img.onerror = function() {
                callback();
            }
            img.src = filename;
            
        // Others...
        } else {
            fileref.onload = function() {
                callback();
            };
        }
    }

    // Add the script/link to the head of the parent page...
    if (typeof fileref != "undefined") {
        document.getElementsByTagName("head")[0].appendChild(fileref);
        console.log(filename + ' added to head of host page...');
    }
}

// Variable to hold already loaded JS & CSS filenames...
var filesadded = "";

// Check to see if src is already loaded, if not, add it...
function checkloadjscssfile(filename, filetype, loadcheck, callback) {
    var farray = filename.split("/");
    var checkname = farray[farray.length - 1];
    if ((filesadded.indexOf("[" + checkname + "]") == -1) && (loadcheck == "undefined")) {
        loadjscssfile(filename, filetype, callback);
        filesadded += "[" + checkname + "]";
    } else {
        if (loadcheck) console.log(checkname + " already running!");
        else console.log(checkname + " file already loaded!");
        if (typeof(callback) != "undefined") callback();
    }
}

// Load a stylesheet template...
window.loadStylesheet = function(stylesheetID) {
    if (!$('#ssid' + stylesheetID).length) {
        $('<style id="ssid' + stylesheetID + '" type="text/css">@import url("//www.cristina.org/css2.ncf?s=cgpn&templateid=' + localStorage.getItem("templateid") + '&ssid=' + stylesheetID + '")</style>').appendTo("head");
    }
}

// Remove a tylesheet template...
window.removeStylesheet = function(stylesheetID) {
    $('#ssid' + stylesheetID).prop('disabled', true).remove();
}

// Load all required scripts/styles, in order, then build application interface...
var nocheck = "undefined";
checkloadjscssfile("//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", "js", typeof(jQuery), function() {
    checkloadjscssfile("//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js", "js", typeof(jQuery.ui), function() {
        checkloadjscssfile("//www.cristina.org/includes/js/smartpaginator/smartpaginator.css?ver=4.3.1", "css", nocheck);
        checkloadjscssfile("//www.cristina.org/includes/js/smartpaginator/smartpaginator.js?ver=4.3.1", "js", nocheck);
        checkloadjscssfile("//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/black-tie/jquery-ui.css", "css", nocheck);
        checkloadjscssfile("//www.cristina.org/includes/js/fb_remote/floatbox.js", "js", typeof(fb), function() {
            checkloadjscssfile("//www.cristina.org/includes/js/fb_remote/floatbox.css", "css", nocheck);
            checkloadjscssfile("//www.cristina.org/css2.ncf?partnerid=&projectid=&locationid=&s=npl&random=&npl_templateid=51", "css", nocheck, function() {
                buildApp();
            });
        })
    });
});


function buildApp() {
    (function($) {

        defaultAppContent = '<div class="nplTransOverlay"></div><form name="nplRemote" id="nplRemote" style="padding:0px;margin:0px;" onsubmit="return false">' + 
            '<input type="hidden" name="mrid" id="nplMrid" value="">' + 
            '<input type="hidden" name="link_ref" id="nplLinkRef" value="">' + 
            '<input type="hidden" name="equip_types" id="nplEquipTypes" value="">' + 
            '<input type="hidden" name="org_types" id="nplOrgTypes" value="">' + 
            '<input type="hidden" name="latlon" id="nplLatlon" value="">' + 
            '<input type="hidden" name="scope" id="nplScope" value="address">' + 
            '<input type="hidden" name="server_name" id="nplServerName" value="www.cristina.org">' + 
            '<div id="nplSearchBox">' + 
            '  <div id="nplSearchContainer" style="position:relative;clear:both;">' + 
            '    <div class="nplSearch">' + 
            '      <div id="nplAdvancedButton" onclick="showAdvanced();">Advanced Search</div>' + 
            '      <label for="nplAddress">Find non-profits near...</label>' + 
            '      <input type="text" name="address" id="nplAddress" value="Address or City or Zip" onfocus="if (this.value.indexOf(\'Address or \') >= 0) { this.value = \'\'; }" onblur="if (!this.value) { this.value=\'Address or City or Zip\';setButton(); }" onkeypress="setButton();">' + 
            '    </div>' + 
            '    <div class="nplRadius">' + 
            '      <label for="nplWithin" style="white-space:nowrap;">Search radius...</label>' + 
            '      <select name="radius" id="nplWithin">' + 
            '        <option value="5">5 miles</option>' + 
            '        <option value="10">10 miles</option>' + 
            '        <option value="15">15 miles</option>' + 
            '        <option value="20">20 miles</option>' + 
            '        <option value="30">30 miles</option>' + 
            '        <option value="40">40 miles</option>' + 
            '        <option value="50" selected="">50 miles</option>' + 
            '        <option value="60">60 miles</option>' + 
            '        <option value="80">80 miles</option>' + 
            '        <option value="100">100 miles</option>' + 
            '        <option value="150">150 miles</option>' + 
            '      </select>' + 
            '    </div>' + 
            '    <div style="float:left;margin-top:20px;">' + 
            '      <input type="button" id="nplSearchButton" onclick="if (jQuery(\'#nplAddress\').val() && (jQuery(\'#nplAddress\').val().indexOf(\'Address or \') < 0)) { searchNPL(); } else { alert(\'Please enter an area to search...\'); }" value="Search">' + 
            '    </div>' + 
            '    <div id="nplAdvancedSearch">' + 
            '      <div class="nplAdvancedTabs"><span id="nplEquipTypeTab" onclick="equipOptions(true);">Equipment Needed</span><span id="nplOrgTypeTab" onclick="typeOptions(true);">Organization Types</span><span id="nplClearAdvanced" class="nplClearAdvanced" onclick="clearAdvanced();">Clear Advanced Options</span></div>' + 
            '      <div id="nplTypeOptions">' + 
            '        <div style="font-size:12px;font-weight:bold;margin-bottom:4px;">Types of organizations to search for:</div>' + 
            '        <div id="addTypes" style="padding:8px;margin-right:4px;">' + 
            '          <span id="addType-non_profit" onclick="selectType(\'non_profit\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Non-Profit 501c3</span> ' + 
            '          <span id="addType-voluntary" onclick="selectType(\'voluntary\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Voluntary Organization</span> ' + 
            '          <span id="addType-private_school" onclick="selectType(\'private_school\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Private School</span> ' + 
            '          <span id="addType-public_school" onclick="selectType(\'public_school\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Public School</span> ' + 
            '          <span id="addType-public_agency" onclick="selectType(\'public_agency\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Public Agency</span> ' + 
            '        </div>' + 
            '      </div>' + 
            '      <div id="nplEquipOptions">' + 
            '        <div style="font-size:12px;font-weight:bold;margin-bottom:4px;">Show non-profits in need of:</div>' + 
            '        <div style="padding:8px;margin-right:4px;">' + 
            '          <div id="addItems" style="margin-top:0px;line-height:22px;"><table border="0" style="width:100%">  <tr>    <td style="width:25%;padding:0px;padding-right:6px;"><div id="systems" class="yellowButton" style="font-size:11px;padding-top:0px;padding-bottom:0px;" onclick="selectCategory(\'systems\');">Computers...</div></td>    <td style="width:25%;padding:0px;padding-right:6px;"><div id="components" class="yellowButton" style="font-size:11px;padding-top:0px;padding-bottom:0px;" onclick="selectCategory(\'components\');">Components...</div></td>    <td style="width:25%;padding:0px;padding-right:6px;"><div id="devices" class="yellowButton" style="font-size:11px;padding-top:0px;padding-bottom:0px;" onclick="selectCategory(\'devices\');">Devices...</div></td>    <td style="width:25%;padding:0px;padding-right:6px;"><div id="others" class="yellowButton" style="font-size:11px;padding-top:0px;padding-bottom:0px;" onclick="selectCategory(\'others\');">Others...</div></td>  </tr>  <tr id="hiddenSystems" class="hiddenRow">    <td colspan="4"><span id="addItem-pc_desktop" onclick="selectItem(\'pc_desktop\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">PC Desktop System</span> <span id="addItem-pc_laptop" onclick="selectItem(\'pc_laptop\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">PC Laptop System</span> <span id="addItem-mac_desktop" onclick="selectItem(\'mac_desktop\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Mac Desktop System</span> <span id="addItem-mac_laptop" onclick="selectItem(\'mac_laptop\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Mac Laptop System</span> </td>  </tr>  <tr id="hiddenComponents" class="hiddenRow">    <td colspan="4"><span id="addItem-cdrom" onclick="selectItem(\'cdrom\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">CDROM Drive</span> <span id="addItem-drawing_tablet" onclick="selectItem(\'drawing_tablet\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Pen/Drawing Tablet</span> <span id="addItem-hard_disk" onclick="selectItem(\'hard_disk\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Hard Disk Drive</span> <span id="addItem-keyboard" onclick="selectItem(\'keyboard\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Keyboard</span> <span id="addItem-modem" onclick="selectItem(\'modem\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Modem</span> <span id="addItem-monitor" onclick="selectItem(\'monitor\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Monitor</span> <span id="addItem-mouse" onclick="selectItem(\'mouse\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Mouse</span> <span id="addItem-lan_nic" onclick="selectItem(\'lan_nic\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Network Interface Card</span> <span id="addItem-software" onclick="selectItem(\'software\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Software Item</span> <span id="addItem-sound_card" onclick="selectItem(\'sound_card\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Sound Card</span> <span id="addItem-video_card" onclick="selectItem(\'video_card\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Video Card</span> </td>  </tr>  <tr id="hiddenDevices" class="hiddenRow">    <td colspan="4"><span id="addItem-pc_cpu" onclick="selectItem(\'pc_cpu\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">PC CPU (Partial System)</span> <span id="addItem-allinone_unit" onclick="selectItem(\'allinone_unit\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">All-In-One Unit</span> <span id="addItem-answering_machine" onclick="selectItem(\'answering_machine\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Answering Machine</span> <span id="addItem-copier" onclick="selectItem(\'copier\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Copier</span> <span id="addItem-digital_camera" onclick="selectItem(\'digital_camera\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Digital Camera</span> <span id="addItem-fax_machine" onclick="selectItem(\'fax_machine\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Fax Machine</span> <span id="addItem-flatbed_scanner" onclick="selectItem(\'flatbed_scanner\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Flatbed Scanner</span> <span id="addItem-network_device" onclick="selectItem(\'network_device\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Switch or Router</span> <span id="addItem-pda" onclick="selectItem(\'pda\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Tablet or PDA</span> <span id="addItem-plotter" onclick="selectItem(\'plotter\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Plotter</span> <span id="addItem-printer" onclick="selectItem(\'printer\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Printer</span> </td>  </tr>  <tr id="hiddenOthers" class="hiddenRow">    <td colspan="4"><span id="addItem-misc_item" onclick="selectItem(\'misc_item\');" class="whiteButton" style="margin-right:4px;white-space:nowrap;">Miscellaneous Item</span> </td>  </tr></table></div>' + 
            '        </div>' + 
            '      </div>' + 
            '      <div id="nplCurrentSearch"><span>Chosen Options:&nbsp;</span><div id="nplTypesDisplay"></div><div id="nplInNeed">&nbsp;in need of&nbsp;</div><div id="nplItemsDisplay"></div><div style="clear:both"></div></div>' + 
            '    </div>' + 
            '  </div>' + 
            '</div>' + 
            '</form>';

        // Update the appContainer with default html...
        $('#nplContainer').html(defaultAppContent);

        // Separate the search results...
        defaultAppContent = '<div id="nplSearchResults">' + 
            '  <div id="nplInstrucText">Begin the process by providing a complete address OR zip code and a radius to be searched.  Your search results will include the name of the organization, its distance from your location, its Mission Statement as well as detailed information on the types of equipment they are seeking.  Once you identify an organization that meets your personal criteria, click the &#8220;Donate Now&#8221; button beneath their needs to start your online donation.</div>' + 
            '</div>';
            
        // Append the search results container if it doesn't already exist...
        if (!$('#nplSearchResults').length) $('#nplContainer').append(defaultAppContent);
        
        cancelBubble = function(windowEvent, exec) {
            var objEvent;
            try {
                objEvent = windowEvent;
                objEvent.cancelBubble = true;
            } catch (ex) {}
            if (exec) {
                eval(exec);
            }
        };
        
        $('#nplAddress').each(function() {
            var elem = $(this);
            elem.data('oldVal', elem.val());

            elem.bind("propertychange keyup input paste", function(event) {
                if (elem.data('oldVal') != elem.val()) {
                    elem.data('oldVal', elem.val());
                    setButton();
                }
            });
        });
        
        $('#nplAddress').keydown(function(e) {
            if (e.keyCode == 13) {
                searchNPL();
            }
        });
        
        setButton = function() {
            if ($('#nplAddress').val().indexOf("Neighborhood") >= 0) {

            } else {

            }
        };
        
        showAdvanced = function() {
            $('#nplAdvancedButton').toggleClass('live');
            if ($('#nplAdvancedButton').hasClass('live')) equipOptions();
                else $('#nplAdvancedSearch').fadeOut(200);
            $('#nplEquipTypeTab').click();
            localStorage.setItem("npl_search_mode", "advanced");
        }
        
        clearAdvanced = function() {
            $('#nplAdvancedSearch').fadeOut(200);
            $('#addItems span.forestButton, #addTypes span.forestButton').each(function( index ) { 
                $(this).removeClass('forestButton').addClass('whiteButton');
            });
            $('#nplOrgTypes, #nplEquipTypes').val('');
            $('#nplTypesDisplay, #nplItemsDisplay').html('');
            $('#nplInNeed, #nplCurrentSearch').hide();
            $('#nplAdvancedButton').removeClass('live').fadeIn(200);
            localStorage.setItem("npl_search_mode", "normal");
            localStorage.setItem("npl_last_tab","");
            localStorage.setItem("npl_last_category","");
            localStorage.setItem("npl_org_types",JSON.stringify(new Array()));
            localStorage.setItem("npl_equip_types",JSON.stringify(new Array()));
            //searchNPL();
        }
        
        typeOptions = function(storeVal) {
            $('#nplAdvancedSearch').show();
            $('#nplOrgTypeTab').addClass('live');
            $('#nplEquipTypeTab').removeClass('live');
            if ($('#nplEquipOptions').is(':visible')) {
                $('#nplEquipOptions').fadeOut(200, function() {
                    $('#nplTypeOptions').fadeIn(200);
                });
            } else {
                $('#nplTypeOptions').fadeIn(100);
            }
            if (storeVal) localStorage.setItem("npl_last_tab","nplOrgType");
        };
        
        equipOptions = function(storeVal) {
            $('#nplAdvancedSearch').fadeIn(200);
            $('#nplOrgTypeTab').removeClass('live');
            $('#nplEquipTypeTab').addClass('live');
            if ($('#nplTypeOptions').is(':visible')) {
                $('#nplTypeOptions').fadeOut(200, function() {
                    $('#nplEquipOptions').fadeIn(200);
                });
            } else {
                $('#nplEquipOptions').fadeIn(100);
            }
            if (storeVal) localStorage.setItem("npl_last_tab","nplEquipType");
        };
        
        selectItem = function(TABLE) {
            var itemsDisplay = '';
            var selectedItems = '';
            var buttons = $('#addItems span.forestButton, #addItems span.whiteButton');
            for (i = 0; i < buttons.length; i++) {
                if (buttons[i].id == 'addItem-' + TABLE) {
                    if (buttons[i].className == 'forestButton') {
                        buttons[i].className = 'whiteButton';
                    } else {
                        if (itemsDisplay) itemsDisplay += ' and ';
                        itemsDisplay += $('#' + buttons[i].id).html();
                        buttons[i].className = 'forestButton';
                        if (selectedItems) selectedItems += ',';
                        selectedItems += TABLE;
                    }
                } else {
                    if (buttons[i].className == 'forestButton') {
                        if (itemsDisplay) itemsDisplay += ' and ';
                        itemsDisplay += $('#' + buttons[i].id).html();
                        var splitID = buttons[i].id.split('-');
                        if (selectedItems) selectedItems += ',';
                        selectedItems += splitID[1];
                    }
                }
            }
            $('#nplItemsDisplay').html(itemsDisplay);
            if ($('#nplItemsDisplay').html() || $('#nplTypesDisplay').html()) $('#nplCurrentSearch').fadeIn(400);
            if ($('#nplTypesDisplay').html() && $('#nplItemsDisplay').html()) $('#nplInNeed').show();
                else $('#nplInNeed').hide();
            $('#nplEquipTypes').val(selectedItems);
            var itemTypes = new Array();

            $('#addItems td span.forestButton').each(function(i) {
                itemTypes.push($(this).attr('id').replace('addItem-',''));
            });

            // Update the localStorage in the browser...
            localStorage.setItem("npl_equip_types", JSON.stringify(itemTypes));

        };
        
        selectType = function(TYPE) {
            var typesDisplay = '';
            var selectedTypes = "";
            var buttons = $('#addTypes span.forestButton, #addTypes span.whiteButton');
            for (i = 0; i < buttons.length; i++) {
                if (buttons[i].id.indexOf(TYPE) != -1) {
                    if (buttons[i].className == 'forestButton') {
                        buttons[i].className = 'whiteButton';
                    } else {
                        if (typesDisplay) typesDisplay += ' or ';
                        typesDisplay += $('#' + buttons[i].id).html();
                        buttons[i].className = 'forestButton';
                        if (selectedTypes) selectedTypes += ',';
                        selectedTypes += TYPE;
                    }
                } else {
                    if (buttons[i].className == 'forestButton') {
                        if (typesDisplay) typesDisplay += ' or ';
                        typesDisplay += $('#' + buttons[i].id).html();
                        var splitID = buttons[i].id.split('-');
                        if (selectedTypes) selectedTypes += ',';
                        selectedTypes += splitID[1];
                    }
                }
            }
            $('#nplTypesDisplay').html(typesDisplay);
            if ($('#nplItemsDisplay').html() || $('#nplTypesDisplay').html()) $('#nplCurrentSearch').fadeIn(400);
            if ($('#nplTypesDisplay').html() && $('#nplItemsDisplay').html()) $('#nplInNeed').show();
                else $('#nplInNeed').hide();
            $('#nplOrgTypes').val(selectedTypes);

            var orgTypes = new Array();
            $('#addTypes span.forestButton').each(function(i) {
                orgTypes.push($(this).attr('id').replace('addType-',''));
            });

            // Update the localStorage in the browser...
            localStorage.setItem("npl_org_types", JSON.stringify(orgTypes));

        };

        showSpec = function(TABLE, PROJECTID) {
            $('#' + TABLE + '_showspec' + PROJECTID).toggle();
        };
        
        toggleVis = function(TABLE, PROJECTID) {
            $('#' + TABLE + '_hidden' + PROJECTID).slideToggle('slow');
            $('#' + TABLE + '_expand_collapse_image' + PROJECTID).toggleClass('collapseImage');
        };
        
        capitalizeFirstLetter = function(STRING) {
            return STRING.charAt(0).toUpperCase() + STRING.slice(1);
        };
        
        selectCategory = function(CATEGORY) {
            capCAT = capitalizeFirstLetter(CATEGORY);
            var buttons = $('#addItems div.forestButton, #addItems div.yellowButton');
            for (i = 0; i < buttons.length; i++) {
                capID = capitalizeFirstLetter(buttons[i].id);
                if (buttons[i].id.indexOf(CATEGORY) != -1) {
                    if (buttons[i].className == 'yellowButton') {
                        buttons[i].className = 'forestButton';
                        $('#hidden' + capCAT).addClass('visibleRow').removeClass('hiddenRow');
                        localStorage.setItem("npl_last_category",CATEGORY);
                    }
                } else {
                    buttons[i].className = 'yellowButton';
                    $('#hidden' + capID).addClass('hiddenRow').removeClass('visibleRow');
                }
            }
        };
        
        window.searchNPL = function() {
            $('#nplContainer .nplTransOverlay').fadeIn(200);
            $('#nplPaginatorContainer').hide();
            $('#nplSiteDesc').hide();
            $('#nplInstrucText').fadeOut(100);
            $('#nplRemote').attr('disable', 'true');
            $('#nplSearchResults').html('<div style="width:400px;height:200px;"><img src="//proto.cristina.org/images/ajax_loading.gif" style="margin-left:20px;float:right;">Loading search results, one moment...</div>');
            localStorage.setItem("npl_last_address",$('#nplAddress').val());
            localStorage.setItem("npl_last_radius",$('#nplWithin').val());
            
			$.ajax({
			        method: "POST",
			        dataType: 'jsonp',
			        url: "//www.cristina.org/npl.ncf",
			        data: {
			            ajax: 'search',
			            search: true,
			            scope: 'address',
			            address: $('#nplAddress').val(),
			            radius: $('#nplWithin').val(),
			            equip_types: $('#nplEquipTypes').val(),
			            org_types: $('#nplOrgTypes').val(),
			            templateid: '51',
			            pageid: '11',
			            server_name: $('#nplServerName').val(),
			            random: Math.round(new Date().valueOf() / 1000)
			        }
			    })
			    .done(function(response) {

                    // Go through returned org types and format for display...
                    if (response.search_summary.org_types) {
                        var orgTypesDisplay = "";
                        $.each(response.search_summary.org_types_display, function(index, org_type) {
                            if (orgTypesDisplay) orgTypesDisplay += "</span> or <span>";
                                else orgTypesDisplay += "<span>";
                            orgTypesDisplay += org_type;
                        });
                        if (orgTypesDisplay) orgTypesDisplay += "</span> ";
                    } else {
                        orgTypesDisplay = "";
                    }

                    // Go through retuned equip types and format for display...
                    if (response.search_summary.equip_types) {
                        var equipTypesDisplay = "";
                        $.each(response.search_summary.equip_types_display, function(index, equip_type) {
                            if (equipTypesDisplay) equipTypesDisplay += "</span> and <span>";
                                else equipTypesDisplay += "<span>";
                            equipTypesDisplay += equip_type;
                        });
                        if (equipTypesDisplay) equipTypesDisplay = " in need of " + equipTypesDisplay + "</span>";
                    } else {
                        equipTypesDisplay = "";
                    }
                    
                    // Output found <blah> summary...
                    $('#nplSearchResults').html('<div id="nplPartnersFound">Found <span id="nplNumFound">' + response.search_summary.found + '</span> ' + orgTypesDisplay + 'locations within <span>' + response.search_summary.radius + ' miles</span> of <span title="' + response.search_summary.latlon + '">' + response.search_summary.address + '</span>' + equipTypesDisplay + '...</div>');
                    
                    // Output top pagination container...
                    if (response.search_summary.found > 0) $('#nplSearchResults').append('<div id="nplPaginator1" class="nplPaginatorContainer"><div id="smart-paginator1"></div></div>');
                    
                    // Go through each returned partner and display their data...
                    if (response.search_summary.found > 0) {
                        $.each(response.partners, function(recipid, data) {
                            $('#nplSearchResults').append('<page id="' + recipid + '"></page>');
                            $('#' + recipid).append('<div class="nplOrgMission"><img id="mimg-' + recipid + '" src="//proto.cristina.org/images/expand_icon_vert_small.png"> <span>Mission Statement</span></div>');
                            $('#' + recipid).append('<div class="nplOrgName"><div>' + data.org_name + '</div></div>');
                            $('#' + recipid).append('<div id="mission-' + recipid + '" class="nplOrgMissionContainer"><div class="nplOrgMissionText">' + data.org_mission + '</div><br clear="all"><div class="nplOrgLearnMore"><div onclick="fb.start(\'//proto.cristina.org/npl.ncf?partnerid=' + data.partnerid + '&projectid=' + data.projectid + '&show_project=true&ajax=true&templateid=51&pageid=1\',{ width:\'780\', showPrint:true, contentScroll: true });">Click to Learn More...</div><br clear="all"></div></div>');
                            if (data.show_loc > 0) $('#' + recipid).append('<div class="nplOrgProject"><div class="nplMapLink" onclick="fb.start(\'//proto.cristina.org/npl.ncf?show_map=true&amp;ajax=true&amp;lat=' + data.lat + '&amp;lon=' + data.lon + '&amp;locationid=' + data.locationid + '&amp;templateid=51&amp;pageid=21&amp;lang=en\', { width:\'460\', height:\'500\' });cancelBubble();return false;">(' + data.distance + ' miles away)</div>' + data.project_name + '</div>');
                                else $('#' + recipid).append('<div class="nplOrgProject"><div class="nplDistance">(' + data.distance + ' miles away)</div>' + data.project_name + '</div>');
                            $('#' + recipid).append('<div class="nplOrgNeeds">' + data.equip_html + '</div>');
                        });
                    }
                    
                    // No partners found...
                    if ((response.search_summary.found == 0) && (response.search_summary.html || response.error)) {
                        if (response.error) $('#nplSearchResults').append(response.error);
                        $('#nplSearchResults').append(response.search_summary.html);
                    }

                    // Output bottom pagination container...
                    //if (response.search_summary.found > 0) $('#nplSearchResults').append('<div id="nplPaginator2" class="nplPaginatorContainer"><div id="smart-paginator2"></div></div>');

                    // Apply pagination to found results...
                    $('#smart-paginator1, #smart-paginator2').smartpaginator({
                        totalrecords: $('#nplNumFound').html(),
                        recordsperpage: 5,
                        initval: 0,
                        next: 'Next',
                        prev: 'Prev',
                        first: 'First',
                        last: 'Last',
                        theme: 'green',
                        datacontainer: 'nplSearchResults',
                        dataelement: 'page',
                        display: 'double',
                        onchange: onChange
                    });
                    
                    $('.nplPaginatorContainer').show();
                    if ($('#searchDefaultedText').html()) {
                        $('#searchDefaultedText').hide();
                    }

                    $('div.nplOrgMission').on('click', function() {
                        pageID = $(this).closest("page").attr("id");
                        if ($('#mission-' + pageID).is(':visible')) {
                            $('#mimg-' + pageID).attr('src',$('#mimg-' + pageID).attr('src').replace(/collapse/,'expand'));
                            $('#mission-' + pageID).slideToggle('slow');
                            
                        } else {
                            $('#mimg-' + pageID).attr('src',$('#mimg-' + pageID).attr('src').replace(/expand/,'collapse'));
                            $('#mission-' + pageID).slideToggle('slow');
                        }
                    });

                    $('#nplRemote').attr('disable', 'false');
    	            $('#nplContainer .nplTransOverlay').hide();
			    })
			    .complete(function(response) {
			        // No response, how odd...
			        if (!response.responseJSON) {
			            alert('Oops!\n\nThere was an error, please try again...');
			        }
			        $('#nplContainer .nplTransOverlay').hide();
			    });
			    
			    function onChange(newPageValue) {
			        //alert(newPageValue);
			    }
        };

        $(document).ready(function() {

            // Look for/set options in localStorage...
            localStorage.setItem("npl_templateid",51);
            storedOrgTypes = (JSON.parse(localStorage.getItem("npl_org_types")) === undefined) ? new Array() : JSON.parse(localStorage.getItem("npl_org_types"));
            if (!storedOrgTypes) {
                storedOrgTypes = new Array();
                localStorage.setItem("npl_org_types",JSON.stringify(storedOrgTypes));
            }
            storedEquipTypes = (JSON.parse(localStorage.getItem("npl_equip_types")) === undefined) ? new Array() : JSON.parse(localStorage.getItem("npl_equip_types"));
            if (!storedEquipTypes) {
                storedEquipTypes = new Array();
                localStorage.setItem("npl_equip_types",JSON.stringify(storedEquipTypes));
            }

            storedLastViewed = JSON.parse(localStorage.getItem("npl_last_viewed"));
            storedLastCategory = localStorage.getItem("npl_last_category");
            storedLastTab = localStorage.getItem("npl_last_tab");

            // Update the search address and radius fields with previous search if found...
            storedAddress = localStorage.getItem("npl_last_address");
            if (storedAddress) $('#nplAddress').val(storedAddress);
            storedRadius = localStorage.getItem("npl_last_radius");
            if (storedRadius) $('#nplWithin').val(storedRadius);

            // Set/pre-set the search mode...
            storedSearchMode = localStorage.getItem("npl_search_mode");
            if (!storedSearchMode) {
                storedSearchMode = 'normal';
                localStorage.setItem('npl_search_mode',storedSearchMode);
            }

            // Cached advanced search options found, pre-set them...
            if (storedOrgTypes.length || storedEquipTypes.length || (storedSearchMode == "advanced")) {

                // Display the last viewed advanced tab option...
                if (storedLastTab) $('#' + storedLastTab + 'Tab').click();
                    else $('#nplEquipTypeTab').click();

                // Pre-set any cached item type selections...
                if (storedEquipTypes) {

                    // Display the last viewed item category (computers, devices, etc..)
                    if (storedLastCategory) $('#' + storedLastCategory).click();

                    // Pre-set each cached item type selection...
                    $.each(storedEquipTypes, function(index,table) {
                        selectItem(table);
                    });
                }

                // Pre-set any cached organization type selections...
                if (storedOrgTypes) {

                    // Pre-set each cached org type selection...
                    $.each(storedOrgTypes, function(index,type) {
                        selectType(type);
                    });
                }

                // Finally, display the advanced search section...
                $('#nplAdvancedButton').hide();
                $('#nplAdvancedSearch').fadeIn(200);
            }

            // Address was either found by IP search or was cached, execute search on load...
            if (($('#nplAddress').val() != 'Address or City or Zip') && $('#nplAddress').val()) {
            	searchNPL();
            }
            $('#nplContainer .nplTransOverlay').hide();
        });
    })(jQuery)
}
