// main arkive javascript file
// will not function unless all files in the arkive folder have been loaded first
// (so get the script tag ordering right for dev sites and
// JS combiner/compressor for live)
//
// Ensure that the load order of specific sub-classes is irrelevant by
// including only functions and data in those files; all "in-line" statements
// must be included in execution order in this file only.
//
// most functions and data will be stored in the org.arkive namespace to
// prevent conflicts with 3rd party libraries and browser extensions
//
// org.arkive object must be created in the calling page first (e.g. Site.master view)
//
// JQuery 1.4 must have been loaded before this script executes


// updates the page state by inspecting current preferences
// typically deals only with those settings that can be preserved across more
// than one page view
org.arkive.updatePageState = function () {

    var loggerSetByCookie = false;

    // Maybe call update methods of child objects once number of state items gets large?
    org.arkive.stateParams = org.arkive.hash.getUrlVars();
    // determine exact text we want to display
    //TODO: stop relying on presense of hash tag to initiate state detection
    if (window.location.hash) {
        org.arkive.speciesArea.textType = org.arkive.speciesArea.determineTextType(org.arkive.stateParams["text"]);
        if (!org.arkive.speciesArea.textType) //TODO: this logic can be removed after above function call does what we need
        {
            if (arkivePageType == 'ThemePage')
                org.arkive.speciesArea.textType = 'Overview';
            else
                org.arkive.speciesArea.textType = 'Description';
        }
        org.arkive.speciesArea.textLocation = org.arkive.stateParams["textLocation"];
        org.arkive.speciesArea.enableSmoothScroll = org.arkive.stateParams["enableSmoothScroll"];

        //TODO: un-necessary to keep assigning these after initial page load but does no harm
        if (org.arkive.stateParams["mediaCredit"] == "true")
            org.arkive.speciesArea.initialModalPopup = "mediaCredit";
        else if (org.arkive.stateParams["cornellCredit"] == "true")
            org.arkive.speciesArea.initialModalPopup = "cornellCredit";
        else if (org.arkive.stateParams["linkingInfo"] == "true")
            org.arkive.speciesArea.initialModalPopup = "linkingInfo";
        else if (org.arkive.stateParams["view"] == "slideshow")
            org.arkive.speciesArea.initialModalPopup = "slideshow";


        if (org.arkive.stateParams["logging"] == "on") {
            log4javascript.setEnabled(true);
            org.arkive.logger = log4javascript.getDefaultLogger();
            $j.cookie('org.arkive.logger', 'on', { expires: 7 });
        }
        else {
            loggerSetByCookie = true;
        }
        if (org.arkive.stateParams["logging"] == "off") {
            log4javascript.setEnabled(false);
            $j.cookie('org.arkive.logger', 'off', { expires: 7 });
            org.arkive.logger = log4javascript.getNullLogger();
            loggerSetByCookie = false;
        }
    } else {
        if (arkivePageType == 'ThemePage')
            org.arkive.speciesArea.textType = 'Overview';
        else
            org.arkive.speciesArea.textType = 'Description';
        org.arkive.speciesArea.textLocation = undefined;
        org.arkive.speciesArea.enableSmoothScroll = null;
        loggerSetByCookie = true;
    }

    if (loggerSetByCookie) {
        if ($j.cookie("org.arkive.logger") == "on") {
            log4javascript.setEnabled(true);
            org.arkive.logger = log4javascript.getDefaultLogger();
        } else {
            log4javascript.setEnabled(false);
            org.arkive.logger = log4javascript.getNullLogger();
        }
    }

    org.arkive.logger.debug("org.arkive.updatePageState() complete");
};

//};

org.arkive.googleApiFeedReady = function () {
    org.arkive.logger.debug("Google API Feeds module loaded");
    // This runs immediately if the DOM has already been loaded
    $j(document).ready(function () {
        org.arkive.logger.debug("Creating Google Feed instance");
        // Create a feed instance that will grab the feed for this page.
        var feed = new google.feeds.Feed(org.arkive.latestBlogFeed.url);
        feed.setNumEntries(org.arkive.latestBlogFeed.numItems);

        org.arkive.latestBlogFeed.container = $j(".blogPostContainer");

        // Calling load sends the request off.  It requires a callback function.
        if (org.arkive.latestBlogFeed.container.length > 0) {
            feed.load(org.arkive.latestBlogFeed.Loaded);
            org.arkive.logger.debug("Feed load request made");
        }
    });
};

org.arkive.googleApiMapsReady = function () {
    org.arkive.logger.debug("Google API Maps module loaded");

    // Processes any Google Maps functions that are queued ready for the APi to be loaded.
    while (org.arkive.maps.google.processQueue.length > 0) {
        var first = org.arkive.maps.google.processQueue.shift();
        if (typeof org.arkive.maps.google[first] === "function")
            org.arkive.maps.google[first]();
    }

    // Overide push to be a function to ensure functions after the API loads are called immediately.
    org.arkive.maps.google.processQueue = {};
    org.arkive.maps.google.processQueue.push = function (fnc) {
        org.arkive.maps.google[fnc]();
    }
};

$j(function () {
    $j('ul#navmenu').superfish({ delay: 300 }); // initialise header drop-down menus

    org.arkive.tracker.setupEvents();

    // record "on load" events defined in page DOM
    org.arkive.tracker.DOMteOnLoad();

    // initialise the correct hash fragment for links to text pages
    org.arkive.speciesArea.convertNonJSTextLinkFragments();
    // look for hash changes every 0.1 seconds (e.g. back buttons, etc.)
    setInterval(org.arkive.hash.poll, 100);
    // modify credit links on-click so they don't cause loaded page to be scrolled to position of overlay
    $j("a[href$='#mediaCredit']").click(function () {
        if (this.href.length < 6 || this.href.substr(this.href.length - 5) != '=true') {
            this.href = this.href + "=true";
        }
    });

    // start loading delayed load images (e.g. related species)
    for (var key in org.arkive.delayedLoadImages.RS) // TODO: extend to iterate through all object in delayedLoadImages - maybe need to make it an array?
    {
        rsVal = org.arkive.delayedLoadImages.RS[key];

        var width = 0;
        var height = 0;
        var src = "";
        var title = "";
        var alt = "";

        var src = rsVal.src;
        if (src == null) {
            $j('#' + key).replaceWith("");
            continue;
        }

        var width = rsVal.width;
        if (width == null) {
            $j('#' + key).replaceWith("");
            continue;
        }

        var height = rsVal.height;
        if (height == null)
            height = width;

        var alt = rsVal.alt;
        if (alt == null)
            alt = "";

        var title = rsVal.title;
        if (title == null)
            title = alt;

        $j('#' + key).replaceWith('<img src="' + src + '" width="' + width + '" height="' + height + '" title="' + title + '" alt="' + alt + '"/>');

    }
    // hide any divs that indicate we're still waiting for the image placeholders to be created
    $j('.delayedLoadImgPlaceholder').remove();
});

// Set some things we're not in a hurry to execute to happen on document load
$j(window).load(function () {
    // Temporary user survey popup
    if (navigator.userAgent.indexOf('MSIE 6') === -1 && $j.cookie('userSurvey2012Popup') !== 'true') {
        setTimeout(function () { $j('#userSurvey2012Popup').slideDown(); }, 2000);
        $j('#userSurvey2012Later').click(function () {
            $j('#userSurvey2012Popup').slideUp();
            var surveyReminder = new Date();
            surveyReminder.setTime(surveyReminder.getTime() + (5 * 60 * 1000));
            $j.cookie('userSurvey2012Popup', 'true', { path: '/', expires: surveyReminder });
            return false;
        });
        $j('#userSurvey2012Close').click(function () {
            $j('#userSurvey2012Popup').slideUp();
            $j.cookie('userSurvey2012Popup', 'true', { path: '/', expires: 365 });
            return false;
        });
        $j('#userSurvey2012Never').click(function () {
            $j('#userSurvey2012Popup').slideUp();
            $j.cookie('userSurvey2012Popup', 'true', { path: '/', expires: 365 });
            return false;
        });
        $j('#userSurvey2012Link').click(function () {
            $j('#userSurvey2012Popup').slideUp();
            $j.cookie('userSurvey2012Popup', 'true', { path: '/', expires: 365 });
            return true;
        });
    }
});

// establish the desired first-run state of this page
org.arkive.updatePageState();

// log performance data (TODO: verify page URLs logged by this method are sensible)
//CPT 20111220: Moved before page view tracking in case GA (since Nov) needs this flag set before tracking the page request
org.arkive.tracker.performance();

// track the initial page view and any custom events, forcing a hit to the "landing page" if we are just defaulting to a text view
//if (arkivePageType.substr(0, 11) === "SpeciesText" && (window.location.hash == "" || window.location.hash == "#"))
//    org.arkive.tracker.page(window.location.path);
//else
org.arkive.tracker.page();

org.arkive.tracker.pageLoadEvents();

if (arkivePageType.substr(0, 11) === "SpeciesText"
 || arkivePageType.substr(0, 12) === "SpeciesImage"
 || arkivePageType.substr(0, 12) === "SpeciesVideo"
 || arkivePageType === "SpeciesUserImageList"
 || arkivePageType === "SpeciesGoogleEarthPlugin"
 || arkivePageType === "EcoRegionImage"
 || arkivePageType === "EcoRegionVideo"
 || arkivePageType === "EcoRegionGoogleEarthPlugin"
 || arkivePageType === "ThemePage") {

    //org.arkive.tracker.textPage();

    // convert hash fragments in the URL to the correct format
    org.arkive.speciesArea.convertNonJSTextLocationFragments();

    //org.arkive.speciesArea.updatePageState();

    $j(function () {
        if (arkivePageType.substr(0, 11) === "SpeciesText" || arkivePageType.substr(0, 9) == "EcoRegion" || arkivePageType === "ThemePage")
            org.arkive.speciesArea.OnTextLoaded();
        else
            org.arkive.speciesArea.loadTextAsync();

        if (arkivePageType.substr(0, 7) === "Species" || arkivePageType.substr(0, 9) === "EcoRegion")
            org.arkive.speciesArea.setupOverlays();

        // make sure various links that move around the species area page preserve text & other states
        $j('#mediaNavigation a').add('#mediaListSelect a').add('#mediaList a').add('#actionMenu2 a').add('#action-googleEarth a').click(function () {
            var href = org.arkive.speciesArea.mediaChooser.adjustHref();
            if (href) {
                if (this.href.indexOf('#') < 0)
                    this.href = this.href + '#' + href;
                else
                    this.href = this.href + '&' + href;
            }
        });

        // add in text colour switcher
        $j('#inTextOptions').append('<span id="textColourControls"><a title="Change text background colour" href="#colour=toggle" id="tcDandL"><img src="/images/species/textDandL.gif" alt="Change text background colour"/></a></span>');
        $j('#textColourControls a').click(function () {
            if (arkivePageType == 'ThemePage')
                var tc = $j('#textContent');
            else
                var tc = $j('#speciesTextContent');
            if (tc.hasClass('light')) {
                tc.removeClass('light');
                $j.cookie('org.arkive.speciesArea.textColour', 'dark', { path: '/' });
                org.arkive.tracker.event("TextBackground", "Change", "dark");
            } else if (!tc.hasClass('light')) {
                tc.addClass('light');
                $j.cookie('org.arkive.speciesArea.textColour', 'light', { path: '/' });
                org.arkive.tracker.event("TextBackground", "Change", "light");
            }
            return false;
        });

        if ($j.cookie('org.arkive.speciesArea.textColour') == 'light')
            $j('#speciesTextContent').addClass('light');

        // Add slideshow link to "action" menu
        if (arkivePageType == "SpeciesTextAll" || arkivePageType == "SpeciesImage") {
            $j('ul#actionMenu1').prepend('<li id="action-slideshow"><a href="#" title="View a slideshow of photos of the ' + org.arkive.commonName.toLowerCase() + '" class="slideshow">Slideshow</a></li>');
        }

        if (arkivePageType === "SpeciesUserImageList" && !arkiveIsOffline)
            org.arkive.ugc.flickr.requestImages();
    });
}

if (arkiveIsOffline) {
    $j(document).ready(function () {
        var links = $j('a').each(org.arkive.linkDisabler);

        // PayPal donations
        $j('input#PayPalDonateButton').click(function (evt) { evt.stopPropagation(); evt.preventDefault(); return false; });
    });
}

org.arkive.linkDisabler = function (index) {
    var link = $j(this);

    var l = link.attr('href');
    if (!l) return;

    // Email links
    if (l.indexOf('mailto:') == 0) {
        //link.bind('mouseup', { cat: 'Link', act: 'mailto', lab: l.substr(7) }, clickEventHandler);
        link.replaceWith(link.html());
        return;
    }

    // search links
    if (l.indexOf('/search') == 0 || l.indexOf('/scripts/php/download-documents.php') == 0) {
        link.replaceWith(link.html());
        return;
    }

    // External links        
    var matches = l.match(/^((\/tracker\/)?\w{3,5}:\/)|(\/?feeds\/)\//); // check for http:// or ftp://
    if (!matches || l.indexOf('://offline.arkive.org') == 0) return;
    link.replaceWith(link.html());
};

// Generic function to smoothly (by sliding) toggle an element - relies on jQuery. 
// Also, the show/hide link must immediately precede the element to show/hide
function showHide(e) {
    var lnk = $j(e.target);
    var div = lnk.next();
    div.slideToggle();
    if (lnk.html().toLowerCase().indexOf('show') > -1) {
        lnk.html(lnk.html().replace('Show', 'Hide').replace('show', 'hide'));
    } else {
        lnk.html(lnk.html().replace('Hide', 'Show').replace('hide', 'show'));
    }
    e.preventDefault();
}

// callback function to get the currently selected search type
// to appropriately modify the auto-suggest script behaviour
function getSearchType(el, qString) {
    if (document.getElementById('searchClientField').value) {
        var searchType = document.getElementById('searchClientField').value;
        qString += '&searchType=' + searchType;
        return qString;
    }
}

// directs the browser to the appropriate page when user
// selects a result from the auto-complete suggestions
function searchGo(selItem) {
    var loc = selItem.getElementsByTagName('span')[1].innerHTML;
    if (loc != '') {
        window.location = "/" + loc;
    } else if (!arkiveIsOffline) {
        document.getElementById('s').submit();
    }
}

// Sets up dynamic species choosing bits on the Abu Dhabi microsite landing page
function AbuDhabiInit() {

    var defaultSpecies = "oryx";
    var currentSpecies = defaultSpecies;
    var currentSelection = window.location.hash.substr(1);

    // Check to see whether page was loaded with alternative species pre-selected and change if necessary
    if (currentSelection != "" && currentSelection != defaultSpecies)
        changeAbDabSel(currentSelection);

    // Check current browser URL to see if it has changed
    setInterval(function () {
        if (window.location.hash.substr(1) != currentSelection) {
            changeAbDabSel(window.location.hash.substr(1));
        }
    }, 250);

    // Set event handler on media choose thumbs to change main image on click
    $j('.scrollable a.abdabfsl').click(function (e) {
        e.preventDefault();
        var id = $j(this).attr('id').substr(9);
        changeAbDabSel(id);
    });

    // Function to change the main image in response to click or URL change
    function changeAbDabSel(id) {
        var selection = id == "" ? defaultSpecies : id;
        $j('#abdabfsi-' + currentSpecies).hide();
        $j('#abdabfsh-' + currentSpecies).hide();
        $j('#abdabfsi-' + selection).show();
        $j('#abdabfsh-' + selection).show();
        currentSpecies = selection;
        currentSelection = id;
        // Set correct hash on URL in case this was called in response to a click
        if (id != "")
            window.location.hash = id;
    }
}


// Function to initialise the dynamic behaviour on generic "theme" pages
function ThemePageInit() {

    var defaultItem = $j('div[id^=item_]').attr('id').substr(5);
    var currentItem = defaultItem;

    // Set event handler on media chooser thumbs to change main image on click
    $j('.scrollable a, ').click(function (e) {
        var id = $j(this).attr('id').substr(7);
        changeThemeItemSel(id);
        return false;
    });

    // Set event handler on media chooser thumbs to change main image on click
    $j('.mediaChooser a, ').click(function (e) {
        var id = $j(this).attr('id').substr(7);
        //$j('a#select_' + currentItem).parent().removeAttr('id');
        //$j('.mediaChooser td').removeAttr('id');
        changeThemeItemSel(id);
        //$j(this).parent().attr('id', 'curAsset');
        return false;
    });

    // Function to change the main image in response to click or URL change
    function changeThemeItemSel(id) {
        var selection = id == "" ? defaultItem : id;
        var p = $j('#item_' + selection);
        if (p.length > 0) {
            $j('#item_' + currentItem).hide();
            p.show();
            //update media chooser highlighted asset
            $j('a#select_' + currentItem).parent().removeAttr('id');
            $j('a#select_' + selection).parent().attr('id', 'curAsset');
            currentItem = selection;
        }
    }

    $j('.prevPageLink, .nextPageLink').click(function () {
        var item = $j(this).parents('._themeContentItem');
        if (this.className == 'prevPageLink')
            var next = item.prev();
        else
            var next = item.next();
        if (next.length == 1) {
            var id = next[0].id.substr(5);
            changeThemeItemSel(id);
            // centre current asset in media chooser
            var curAss = $j('td#curAsset');
            var offset = curAss.position().left + (curAss.width() / 2) - 299;
            var maxOffset = $j('#lyr1').width() - 598;
            offset = (offset < 0 ? 0 : (offset > maxOffset ? maxOffset : offset));
            $j('#lyr1').css('left', '-' + offset + 'px');
            configureScrollButtons(maxOffset, 0 - offset);
        }
        return false;
    });
}

if (arkiveIsOffline)
    document.onkeypress = function (e) { return e.keyCode != 122 };

/*
* jQuery UI Autocomplete HTML Extension
*
* Copyright 2010, Scott González (http://scottgonzalez.com)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* http://github.com/scottgonzalez/jquery-ui-extensions
*/
(function ($) {

    var proto = $.ui.autocomplete.prototype,
	initSource = proto._initSource;

    function filter(array, term) {
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
        return $.grep(array, function (value) {
            return matcher.test($("<div>").html(value.label || value.value || value).text());
        });
    }

    $.extend(proto, {
        _initSource: function () {
            if (this.options.html && $.isArray(this.options.source)) {
                this.source = function (request, response) {
                    response(filter(this.options.source, request.term));
                };
            } else {
                initSource.call(this);
            }
        },

        _renderItem: function (ul, item) {
            var altTerm1 = "";
            var altTerm2 = "";
            if (this.term.indexOf("'s ") >= 0 || this.term.indexOf("'s") == this.term.length - 2)
                altTerm1 = this.term.replace("'s ", "s ");
            if (altTerm1.indexOf("'s") == altTerm1.length - 2)
                altTerm1 = altTerm1.substring(0, altTerm1.length - 2) + "s";

            if (this.term.indexOf("s ") >= 0 || this.term.indexOf("s") == this.term.length - 1)
                altTerm2 = this.term.replace("s ", "'s ");
            if (altTerm2.indexOf("s") >= 0 && altTerm2.indexOf("s") == altTerm2.length - 1)
                altTerm2 = altTerm2.substring(0, altTerm2.length - 1) + "'s";

            var regMatch = $j.ui.autocomplete.escapeRegex(this.term);
            if (altTerm1 != "")
                regMatch += "|" + $j.ui.autocomplete.escapeRegex(altTerm1);
            if (altTerm2 != "")
                regMatch += "|" + $j.ui.autocomplete.escapeRegex(altTerm2);

            item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + regMatch + ")(?![^<>]*>)(?![^&;]+;)", "gi")
            , '<span class="ui-autocomplete-term">$1</span>');
            return $("<li/>")
			.data("item.autocomplete", item)
			.append($("<a/>")[this.options.html ? "html" : "text"](item.label))
			.appendTo(ul);
        }

    });

})(jQuery);

function onAutocompleteClick(page) {
    window.location = 'http://' + window.location.hostname + ':' + window.location.port + page;
}




$j(function () {

    $j("#mainSearch_q").autocomplete({
        html: "html",
        //appendTo: "#s",
        select: function (event, ui) {
            org.arkive.tracker.event("Click", "AutoCompleteSearch", ui.item.value);
            setTimeout('onAutocompleteClick("' + ui.item.value + '");', 50);
            event.preventDefault();
        },
        open: function (event, ui) {
            $j(".ui-autocomplete li.ui-menu-item:odd").addClass("odd");
            $j(".ui-autocomplete li.ui-menu-item:even").addClass("even");
            if ($j.browser.msie && arkivePageType != 'SpeciesGoogleEarthPlugin')
                $j('#map3d').hide();
        },
        close: function (event, ui) {
            if ($j.browser.msie && arkivePageType != 'SpeciesGoogleEarthPlugin')
                $j('#map3d').show();
        },
        focus: function (event, ui) {
            event.preventDefault();
            $j('li.ui-menu-item').removeClass('ui-active-menuitem');
            $j('#ui-active-menuitem').parent().addClass('ui-active-menuitem');
        },

        source: function (request, response) {
            var currentSearchType = "species";
            currentSearchTypeId = $j('.searchModeTop_active').attr('id');
            if (currentSearchTypeId == "searchMode_arkive-images") {
                currentSearchType = "images";
            } else if (currentSearchTypeId == "searchMode_arkive-videos") {
                currentSearchType = "videos";
            } else if (currentSearchTypeId == "searchMode_arkive-info") {
                currentSearchType = "species";
            } else {
                response({});
                return;
            }
            if (currentSearchType == "species") {
                $j.ajax({
                    url: "/api/test/species/name/" + $j.trim(request.term),
                    dataType: "json",
                    success: function (data) {
                        response($j.map(data.results[0].Species, function (item) {
                            return {
                                label: item.CommonName + '<br/><span class="latinName">' + item.LatinName + '</span>',
                                value: item.RelativeURL
                            }
                        }));
                    }
                });
            } else {
                $j.ajax({
                    url: "/api/test/asset/caption/" + $j.trim(request.term) + "?media=" + currentSearchType,
                    dataType: "json",
                    success: function (data) {
                        response($j.map(data.results[0].Assets, function (item) {
                            return {
                                label: item.Captions[0].Value,
                                value: item.RelativeURL
                            }
                        }));
                    }
                });
            }
        },
        minLength: 2
    });
});
