// DreamStudio Gallery
// Legacy version.  Page moved to /jquery/gallery
// Copy protected - Do not copy or alter this version.

jQuery.url = function () { var segments = {}; var parsed = {}; var options = { url: window.location, strictMode: false, key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], q: { name: "queryKey", parser: /(?:^|&)([^&=]*)=?([^&]*)/g }, parser: { strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/} }; var parseUri = function () { str = decodeURI(options.url); var m = options.parser[options.strictMode ? "strict" : "loose"].exec(str); var uri = {}; var i = 14; while (i--) { uri[options.key[i]] = m[i] || "" } uri[options.q.name] = {}; uri[options.key[12]].replace(options.q.parser, function ($0, $1, $2) { if ($1) { uri[options.q.name][$1] = $2 } }); return uri }; var key = function (key) { if (!parsed.length) { setUp() } if (key == "base") { if (parsed.port !== null && parsed.port !== "") { return parsed.protocol + "://" + parsed.host + ":" + parsed.port + "/" } else { return parsed.protocol + "://" + parsed.host + "/" } } return (parsed[key] === "") ? null : parsed[key] }; var param = function (item) { if (!parsed.length) { setUp() } return (parsed.queryKey[item] === null) ? null : parsed.queryKey[item] }; var setUp = function () { parsed = parseUri(); getSegments() }; var getSegments = function () { var p = parsed.path; segments = []; segments = parsed.path.length == 1 ? {} : (p.charAt(p.length - 1) == "/" ? p.substring(1, p.length - 1) : path = p.substring(1)).split("/") }; return { setMode: function (mode) { strictMode = mode == "strict" ? true : false; return this }, setUrl: function (newUri) { options.url = newUri === undefined ? window.location : newUri; setUp(); return this }, segment: function (pos) { if (!parsed.length) { setUp() } if (pos === undefined) { return segments.length } return (segments[pos] === "" || segments[pos] === undefined) ? null : segments[pos] }, attr: key, param: param} } ();

var jsonLink = '';
var host = '';
var galleryid; // Optional, a ManagementSuite ItemID.
var thumbnail = '';
var photoUrlLarge = '';
var thumbContainer = '';
var slideContainer = '';
var numberArrows = true;
var ua = 0;
var galleryDataModified = new Array();
//var scrollTo; // Name or id of tag to slide to
var currentIndex = 0;
var slideCount = 0;
var galleryJqxhr;

function loadGallery()
{
    galleryJqxhr = $.getJSON(jsonLink, function (data) {
        //alert(jsonLink);
        // top do: Simplify, look at Facebook reader
        var parentTitle = '';
        if (data.parentTitle) {
            $.each(data.parentTitle, function (i, id) {
                if (id.id) {
                    parentTitle = id.id;
                }
            });
        }
        // top do: Simplify, look at Facebook reader
        var parentLink = '';
        if (data.parentLink) {
            $.each(data.parentLink, function (i, id) {
                if (id.id) {
                    parentLink = id.id;
                }
            });
        }

        $('<div class="parentTitle"><a href="' + parentLink + '">' + parentTitle + '</a></div>').prependTo('#gallery-container');

        if (data.parentLink) {
            // top do: Simplify, look at Facebook reader
            $.each(data.ua, function (i, id) {
                if (id.id) {
                    ua = id.id;
                }
            });
        }
        galleryDataModified.length = 0; // Clear the array for reload
        $.each(data.results, function (i, id) {
            galleryDataModified.push(id);
        });

        // Then combine and/or sort galleryDataModified - to be impliment, sort sample in core/event/calendar.aspx.
        //galleryDataModified.sort(sortMyObjects);
        $('#thumb-holder').html('');
        $('#slide-numbers').html('');
        slideCount = 0;

        var navNumber = '<div onclick="previousSlide();return;"><img src="/core/elements/arrows/black-back-sm.gif" /></div>';
        if (numberArrows && galleryDataModified.length > 1) {
            $(navNumber).appendTo('#slide-numbers');
        }
        $.each(galleryDataModified, function (index, id) {
            slideCount++;
            if (id.imageSmall) {
                thumbnail = host + id.imageSmall;
            } else if (id.thumbnail) {
                thumbnail = host + id.thumbnail;
            }
            if (id.imageLarge) {
                photoUrlLarge = host + id.imageLarge;
            } else {
                photoUrlLarge = host + id.image;
            }
            // Useful for other sites: $(\'#slide-numbers a\').removeClass(\'activeNav\');$(this).addClass(\'activeNav\');
            if (galleryDataModified.length > 1) {
                navNumber = '<a href="#id=' + id.id + '" id="nav' + index + '" onclick="goIndex(' + index + ')">' + (index + 1) + '</a>';
                $(navNumber).appendTo('#slide-numbers');
            }
            thumbContainer = '<div class="thumb-container" onclick="goIndex(' + index + ');scrollTo(\'#gallery-container\')"><div class="thumb-mask"><img class="thumb-class" src="' + thumbnail + '" alt="" /></div>';
            if (id.title) thumbContainer += '<div class="thumb-text">' + id.title + '</div>';
            thumbContainer += '</div>';
            $(thumbContainer).appendTo('#thumb-holder');
        });
        if (numberArrows) {
            navNumber = '<div onclick="nextSlide();"><img src="/core/elements/arrows/black-next-sm.gif" /></div>';
            $(navNumber).appendTo('#slide-numbers');
        }
        //alert('got data');
    });
}
function previousSlide() {
    if (currentIndex == 0) {
        goIndex(slideCount - 1);
    } else {
        goIndex(currentIndex - 1);
    }
}
function nextSlide() {
    if (currentIndex == (slideCount - 1)) {
        goIndex(0);
    } else {
        goIndex(currentIndex + 1);
    }
}
function goIndex(number) {
    $('#content-holder').hide(); // Resides in GP MasterPage.
    $('#showContent').show(); // Resides in GP MasterPage.
    showImage(number);
}
function showImage(index) {

    galleryJqxhr.complete(function () {

        //showImageReady(index, 1);
        //return;

        //setInterval(showImageReady(index, 1), 0); // No delay
        //setInterval(showImageReady(index, 2), 100); // Checks 10 times a second.

        //alert('showImage ' + index);
        //window.location.hash = 'slide=' + (index + 1);

        $('#thumb-holder').attr('style', 'z-index:1');
        currentIndex = index;

        $('#slide-numbers a').removeClass('activeNav');
        $('#nav' + index).addClass('activeNav');

        $('#slide-numbers').show();
        $('#slide-number-holder').show();

        $('#slideshow-holder').show();
        //alert('slideCount ' + slideCount);
        //if (galleryDataModified.length == 0) alert('No data found, or a delay has occured during processing.');

        slideContainer = '<div class="slide-text">';
        if (galleryDataModified[index].title) slideContainer += '<div class="slide-title">' + galleryDataModified[index].title + '</div>';
        if (ua >= 6) {
            if (galleryDataModified[index].id > 0) {
                // s=' + galleryDataModified[index].id + '&
                slideContainer += '<a href="/net/content/upload.aspx?imageid=' + galleryDataModified[index].id + '&parentid=' + galleryid + '"><img src="/core/elements/arrows/dot-pointer-on-white.gif" alt="" /> Edit Image</a><br />';
                slideContainer += '<a href="/net/content/categoryedit.aspx?itemid=' + galleryDataModified[index].id + '"><img src="/core/elements/arrows/dot-pointer-on-white.gif" alt="" /> Edit Categories</a><br />';
                // To do: Parse the s value
                // &s=' + $.url.param("s") + '
                slideContainer += '<a href="/net/content/upload.aspx?popup=0&siteid=' + $.url.param("siteid") + '&parentid=' + galleryid + '"><img src="/core/elements/arrows/dot-pointer-on-white.gif" alt="" /> Add Image</a><br />';
            }
            if (galleryDataModified[index].typeID != 98000 && galleryDataModified[index].typeID != $.url.param("tid")) {
                slideContainer += '<a href="<%=SetLink("/location/gallery/imagegallery.aspx?1=2")%>&tid=' + galleryDataModified[index].typeID + '"><img src="/core/elements/arrows/dot-pointer-on-white.gif" alt="" /> ' + galleryDataModified[index].typeTitlePlural + ' at all Parks</a><br />';
            }
        }
        //alert('showImageC ' + index);
        slideContainer += '</div>';
        slideContainer += '<div class="slide-class"><img class="slide-image" src="' + host + galleryDataModified[index].imageLarge + '" alt="" /></div>';

        slideContainer += '</div>';

        $('#slide-container').html(slideContainer);



        // Not only when the DOM is ready, but when the images have finished loading,
        // BUGBUG - but this only works on initial load.
        $(window).bind('load', function () {
            // run the cross fade plugin against selector
            //$('img.fade').crossfade();
            //alert('done');
        });
        $('.slide-nav-button').show();

    });
}
function showImageReady(index, attempts) {
    if (attempts > 10000) {
        alert('attempts: ' + attempts + ' galleryDataModified.length: ' + galleryDataModified.length);
        return;
    }
    if (galleryDataModified.length == 0) {
        //alert('Loading images' + attempts);
        setInterval(showImageReady(index, attempts + 1), 50); // Checks 5 times a second.
        return;
    }
    alert('attempts: ' + attempts + ' galleryDataModified.length: ' + galleryDataModified.length);
 
}
function hideImage() {
    $('#slideshow-holder').hide();
    $('#slide-numbers').hide();
}

//if (scrollTo) {
function scrollTo(target) {
    //get the top offset of the target anchor
    //var target_offset = $("#gallery-container").offset();
    var target_offset = $(target).offset();
    var target_top = target_offset.top;

    //goto that anchor by setting the body scroll top to anchor top
    $('html, body').animate({ scrollTop: target_top }, 500);
}
