// DCP Common JS which loads on every page


// Namespaces
var dcp = {};
dcp.config = {};


// Config

// URL to the Solr instance
dcp.config.solrURL = "/wp-content/themes/dcp-reloaded/solrproxy.php";
dcp.config.quotesURL = "/wp-content/themes/dcp-reloaded/quotes.txt";
dcp.config.siteRoot = document.location.protocol+"//"+document.location.host;
dcp.config.defaultSearchInputText = "Enter a keyword here";

// A map of fields which will be considered when generating the related fields
// The keys are what will appear in a Solr result in brackets: "specimens / samples (scientific)"
// From this (compring it to the stuf comes back from Solr) the categories of related searches can be established for the sidebar
dcp.relatedFields = {
    "set": "Letter sets",
    "people": "People",
    "place": "Places",
    "scientific": "Scientific terms",
    "flora": "Plants",
    "fauna": "Animals",
    "organism": "Organisms",
    "geological": "Geology",
    "human_group": "Groups",
    "societal": "Societies &amp institutions",
    "health": "Health",
    "business": "Business"
};

dcp.months = {
    "1": "January",
    "2": "February",
    "3": "March",
    "4": "April",
    "5": "May",
    "6": "June",
    "7": "July",
    "8": "August",
    "9": "September",
    "10": "October",
    "11": "November",
    "12": "December"
};

// Page init function executing first on every page
dcp.commonPageInit= function() {


    // Init main menu
    $(".top_nav_container").bigomenu({
        baseClass: "bigomenu"
    });

    // Get config data stored in cookies
    var storedConfig = $.cookies.get("darwin-correspondence-project-config");
    if (storedConfig !== null) {
        dcp.config = $.extend({}, dcp.config, storedConfig);
    }

    // Show body - avoid jumping
    $("body").css("display","block");

};


/**
 * solrRequest
 * Constructs a Solr search query in JSONP
 * @param {String} i_key The Solr index we want to search on
 * @param {String} i_value The value we are looking for (the search query)
 * @param {int} i_startItem The item number from where the results will be returned (for pagination etc...)
 * @param {int} i_itemsPerPage The number of items we are expecting from the search
 * callback {Function} callback Callback function to be executed when the response comes back (success and data will be passed as params)
 */
dcp.solrRequest = function(i_query, i_startItem, i_itemsPerPage, callback) {

    // Need basics
    if (typeof i_query !== "string") {
        callback(false);
        return;
    }

    // Defaults
    var query = i_query;
    var startItem = i_startItem || 0;
    var itemsPerPage = i_itemsPerPage || 20;

    $.ajax({

        url: dcp.config.solrURL,
        data: {
            "q": query,
            "version": "2.2",
            "start": startItem,
            "rows": itemsPerPage,
            "indent": "on",
            "wt": "json"
        },
        dataType: "json",
        success: function(data, textStatus, jqXHR) {

            // Dedupe data from Solr
            for (var i=0, il = data.response.docs.length; i<il; i++) {

                var doc = data.response.docs[i];
                var sanitisedDocData = {};

                for (var docDataKey in doc) {

                    var docDataPart = doc[docDataKey];

                    if ($.isArray(docDataPart) && docDataPart.length > 1) {

                        // Paul Irish rocks... taken from his duck punching of jQuery.unique
                        var dedupedArray = $.grep(docDataPart,function(v,k){
                            return $.inArray(v,docDataPart) === k;
                        });

                        sanitisedDocData[docDataKey] = dedupedArray;

                    } else {
                        sanitisedDocData[docDataKey] = docDataPart;
                    }

                }

                data.response.docs[i] = sanitisedDocData;


            }

            if (typeof callback === "function") {
                callback(true, data);
            }

        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Could not load data from Solr! Please contact the site administrator to fix this right away!");
            if (typeof callback === "function") {
                callback(false, {});
            }
        }

    });

};


dcp.quotes = function(container_selector) {

    var $container = $(container_selector);
    var $quotesData = $('<ul></ul>').attr("id", "quotes-data").hide();

    // Add a random quote
    var getQuote = function(n) {
        var $q = $($(".darwin_quote", $quotesData)[n]);
        $("blockquote", $q).after('<div class="signature_container"><img src="'+dcp.config.siteRoot+'/wp-content/themes/dcp-reloaded/images/darwin_signature.png" alt="Charles Darwin signature" /></div>')
        return $q.html();
    };

    $.get(dcp.config.quotesURL, function(rawQuotes){

        var rqArray = rawQuotes.match(/[^\r\n]+/g);
        var temp = "";
        for (var i=0, il=rqArray.length; i<il; i++) {
            temp += '<li class="darwin_quote">'+rqArray[i]+'</li>';
        }
        $quotesData.html(temp);



        // Add random quote to container
        $container.html(getQuote(dcp.randomFromTo(0,$(".darwin_quote", $quotesData).length)));

        // Add signature


        // Add data to DOM after the container
        $container.after($quotesData);



    });


};

// Store config JSON in a cookie
dcp.storeConfigCookie = function(o) {

    var configToStore = $.extend(dcp.config, o);
    var expirationDate = new Date();
    expirationDate.setFullYear(parseInt(expirationDate.getFullYear(),10) + 1);
    var cookieOptions = {
        "expiresAt": expirationDate
    };
    $.cookies.set("darwin-correspondence-project-config", configToStore, cookieOptions);
};


// Reverses a name string - not very cleverly yet
dcp.nameReverse = function(name) {

    var namesplit = name.split(",");
    var ret = name;
    if (namesplit.length > 1) {
        ret = namesplit.reverse().join(" ");
    }
    return ret;
};


// Random number between two integers
dcp.randomFromTo = function(from, to){
    return Math.floor(Math.random() * (to - from + 1) + from);
};




// Start
$(document).ready(function(){

    dcp.commonPageInit();

});

