// fixes IE7 z-index bug for object card info divs
//$j(function() {
//    // check to make sure the current browser is IE7
//    if ($j.browser.msie && $j.browser.version == 7) {
//        var zIndexNumber = 1000;
//        $j('li').each(function() {
//            $j(this).css('zIndex', zIndexNumber);
//            zIndexNumber -= 10;
//        });
//    }
//});

// Close the share popup
$j('#sharemeclose').live('click', function () {
    //$j('#sharemeform').remove()
    $j('.shareme-container').hide();
    $j('.shareme-container').empty();
    return false;
})

$j(".CollectionDepartmentLink").live('click', function(e) {
    if ($j('.loadingDepartment').length == 0) {
        $j(this).append('<div class="loadingDepartment"><span>Just a moment...searching more than 65,000 images.</span></div>');
    }
    return true;
});

$j(".img-wrapper li.collection > a > img").live('mouseover', function (e) {
    // have collection items display summary info on rollover,
    // position of the box is based on window width and box location
    var infobox = $j(this).parent().siblings('.drop')
    var width = $j(this).closest('li').width();

    if ($j(this).offset().left + 350 > $j(window).width()) {
        infobox.css('left', (width * -1) - 10)
        infobox.addClass('left')
    } else {
        infobox.css('left', width - 10);
        infobox.removeClass('left')
    }
    $j(this).closest('li').addClass('expand')
});

$j(".img-wrapper li.collection > a > img").live('click', function(e) {
    // don't want the object card to be on top of the popup panel because of the high z-index value
    $j(this).closest('li').removeClass('expand')
});

$j(".img-wrapper li.collection > a > img").live('mouseout', function(e) {
    $j('.img-wrapper .expand').removeClass('expand')
})

/// <reference path="jquery-1.3.2.min-vsdoc.js" />
$j("#externalPageButton").live('click', function() {
    var url = ($j(this).attr('href'));
    if ($j(this).attr("target") == "_blank") {
        window.open(url);
    }
    else {
        $j(location).attr('href', url);
    }
});

// Generic list toggle.
$j('.info .toggle').live('click', function() {
    $j('#slidepanel_' + $j(this).attr('id')).toggle();
    return false;
});

// Generic list toggle for Safari 3.2.2 (css query was not working)
// This will look for all elements whose id value begins with 'toggle'
$j("*[id^='toggle']").live('click', function() {
    $j('#slidepanel_' + $j(this).attr('id')).toggle();
    return false;
});

$j("#print").live('click', function() {
    $j("#popupform").printElement({ overrideElementCSS: ['/../../css/print.css', { href: '/../../css/print.css', media: 'print'}], printMode: 'popup', leaveOpen: false });
    return false;
});



function VScroll(parent) {
    var view = $j("<div class='gutter'><a class='grab' href='#'></a></div>")
    var scrollparent = $j(parent)

    var that = {
        init: function() {
            var total_h = scrollparent.find('ul').height()
            var mask_h = scrollparent.height()
            if (mask_h >= total_h) return

            var pct = Math.floor((mask_h / total_h) * 100)
            view.find('a.grab').css('height', pct + "%")
            scrollparent.append(view)
            view.find('a.grab').draggable({
                axis: 'y', containment: 'parent',
                start: that.startScroll,
                drag: that.updateScroll,
                stop: that.stopScroll
            })
        },
        updateScroll: function(e, ui) {
            var loc = ui.position.top
            var tot = view.height()
            var pct = Math.max(0, loc / tot)
            scrollparent.find('ul').css('margin-top', -pct * scrollparent.find('ul').height())
        },
        startScroll: function() {
            view.find('a.grab').addClass('dragging')
        },
        stopScroll: function() {
            view.find('a.grab').removeClass('dragging')
        }
    }
    that.init()
    return view
}

function Scroller(initialMag) {
    // takes an optional init argument (an integer 0–4) setting the position for the slider
    // at loadtime.
    var width = $j('.scroller').width()
    var scrollsnap = 16
    var magstep = initialMag || 0
    magstep = Math.min(4, magstep)

    var that = {
        init: function() {
            if ($j(".thumb").size() == 0) return

            $j(".thumb").draggable({ axis: 'x', containment: 'parent',
                grid: [scrollsnap, 0],
                stop: that.magnify
            })
            $j(".thumb").css('left', scrollsnap * magstep) // set the initial position if specified
        },

        magnify: function(newMagstep, ui) {
            // snaps to a 5-step scale. magstep will be in range [0, 4]
            var newstep = ui.position.left / scrollsnap
            if (newstep != magstep) {
                magstep = newstep
                CollectionService("", -1, magstep, "");

                //alert('change magnification to ' + magstep)
            }
        }
    }

    that.init()
    return that
}

function Collection() {
    var filters = null
    var active = {}
    var MENU_TMPL = '<div class="row"><div class="query l"><label>and</label><div class="select"><a href="#">%%SELECT%%</a><div class="drop1"><ul>%%ALTSELECTS%%</ul></div></div><label>is</label><div class="select large"><a href="#">%%SUBSELECT%%</a><div class="drop1" style="padding-bottom:60px"><ul>%%ALTSUBSELECTS%%</ul></div></div></div><a class="btn-close" href="#">Close</a><a href="#">%%ABOUT%%</a></div>'
    var INPUT_TMPL = '<div class="row"><div class="query l"><label>and</label><div class="select"><a href="#">%%SELECT%%</a><div class="drop1"><ul>%%ALTSELECTS%%</ul></div></div><label>is</label><input type="text" value="%%HINT%%" /></div><a class="btn-close" href="#">Close</a></div>'
    var CONTAINS_TMPL = '<div class="row"><div class="query l"><label>and</label><div class="select"><a href="#">%%SELECT%%</a><div class="drop1"><ul>%%ALTSELECTS%%</ul></div></div><label>contains</label><input type="text" value="%%HINT%%" /></div><a class="btn-close" href="#">Close</a></div>'
    var RANGE_TMPL = '<div class="row"><div class="query l"><label>and</label><div class="select"><a href="#">%%SELECT%%</a><div class="drop1"><ul>%%ALTSELECTS%%</ul></div></div><div class="small"><input type="text" value="%%RANGE1%%" /><label>&amp;</label><input type="text" value="%%RANGE2%%" /></div></div><a class="btn-close" href="#">Close</a>'
    // % SELECT
    // % ALTSELECTS
    // % SUBSELECT
    // % ALTSUBSELECTS
    // % HINT | RANGE1,RANGE2

    var that = {
        init: function (filtermap) {
            filters = filtermap
            for (var cat in filters) active[cat] = null

            //Build the initial row in the search option
            var deptRow = $j(that.buildrow('Keywords', ''));
            $j('.picture-form fieldset .row').eq(0).before(deptRow)
            that.reorder()

            //Check if the searchoption needs to be opened
            var searchoption = $j.query.get('searchoption');

            if (searchoption == "1") {
                //$j(".add-header-box a.btn-search").click();
                that.populatesearch();

                if ($j.browser.msie && $j.browser.version < 8) {
                    $j(".picture-form").show()
                } else {
                    $j(".picture-form").slideDown()
                }
                $j(".add-header-box a.btn-search").removeClass('btn-search').addClass('hide-link').text('hide search options')
            }

            //
            // event listeners for relevant markup elts
            //
            $j(".picture-form a.btn-clear").live('click', function () {
                // collapses the filter rows and erases all the queries
                that.hide(true)
                return false
            })
            $j(".add-header-box a.hide-link").live('click', function () {
                // collapses the filter rows but saves the queries and filter-state
                that.hide();
                return false
            })

            $j(".add-header-box a.btn-search").live('click', function () {
                //Check if there is a search option in the session and load them if it there.
                that.populatesearch();
                // expands the filter rows
                if ($j.browser.msie && $j.browser.version < 8) {
                    $j(".picture-form").show()
                } else {
                    $j(".picture-form").slideDown()
                }
                $j(".add-header-box a.btn-search").removeClass('btn-search').addClass('hide-link').text('hide search options')
                return false
            })

            $j(".picture-form a.btn-search").live('click', function () {
                // submits the search
                that.submit()
                return false
            })

            $j('.picture-form fieldset .btn-close').live('click', function () {
                // row-delete button
                if ($j('.picture-form fieldset .row').size() == 2) return
                that.drop($j(this).closest('.row'))
                return false
            })

            $j('.picture-form fieldset .btn-add').click(function () {
                // new filter button
                that.add()
                return false
            })


            $j('.picture-box .select').live('click', function (e) {
                // show the filter dropdown on click
                var dismiss = $j(this).hasClass('expand')
                $j('.picture-box .select').removeClass('expand')

                if (!dismiss) {
                    $j(this).addClass('expand')

                    var selectionsList = $j(this).find('> .drop1')
                    if (selectionsList.find('.grab').length == 0) {
                        VScroll(selectionsList)
                    }

                } else {

                    if (!$j(e.target).hasClass('select') && !$j(e.target).hasClass('sortheader')) {
                        var text = $j(e.target).text();
                        CollectionService("", -1, 9, text);
                        //var rurl = RemoveHashInUrl(document.location.href);
                        //$j(location).attr('href', rurl + "?type=refreshsortorder=" + text);
                    }
                }
                //return false;

            })

            $j('.row .query .select').live('click', function (e) {
                if ($j(e.target).hasClass("grab") || $j(e.target).hasClass("drop1")) {
                    return false
                }

                // show the filter dropdown on click
                var dismiss = $j(this).hasClass('expand')
                $j('.row .query .select').removeClass('expand')

                if (!dismiss) {
                    $j(this).addClass('expand')

                    var selectionsList = $j(this).find('> .drop1')
                    if (selectionsList.find('.grab').length == 0) {
                        VScroll(selectionsList)
                    }
                }
                return false
            })

            $j('.row .query input').live('keyup', function (e) {
                // add user input to the active queries dict
                var newquery = $j(e.target).val()
                var which = $j(e.target).prevAll('.select').find('a:eq(0)').text()
                active[which] = newquery
            })

            $j('a.filter').live('click', function () {
                // change this filter row to a different category type
                var filterRow = $j(this).closest('.row')
                var newFilter = $j(this).text()
                that.refilter(filterRow, newFilter)
                return false
            })

            $j('a.filter-q').live('click', function () {
                var filterRow = $j(this).closest('.row')
                var newQuery = $j(this).text()
                that.query(filterRow, newQuery)
                return false
            })

            $j(".picture-gallery > li > a > img").live('mouseover', function (e) {
                // have collection items display summary info on rollover,
                // position of the box is based on window width and box location
                var infobox = $j(this).parent().siblings('.drop')
                var width = $j(this).closest('li').width();
                if ($j(this).offset().left + 250 > $j(window).width()) {
                    infobox.css('left', -168)
                    infobox.addClass('left')
                } else {
                    infobox.css('left', width - 10);
                    infobox.removeClass('left')
                }
                $j(this).closest('li').addClass('expand')
            });

            $j(".picture-gallery > li > a > img").live('mouseout', function (e) {
                $j('.picture-gallery .expand').removeClass('expand')
            })

            if ($j.browser.msie) {
                $j(".picture-gallery > li > .drop").live('mouseenter', function (e) {
                    $j('.picture-gallery .expand').removeClass('expand')
                })
            }
            //
            // done setting up event listeners
            //

            $j(".related-gallery li").live('mouseover', function () {
                // have collection items display summary info on rollover,
                // position of the box is based on window width and box location
                //if ($j(this).offset().left + 250 > $j(window).width()) {
                if ($j(this).offset().left > $j(".related-gallery").offset().left + 350) {
                    $j(this).find('.drop').addClass('left')
                } else {
                    $j(this).find('.drop').removeClass('left')
                }
                $j(this).closest('li').addClass('hover')
                //$j(this).addClass('hover')
            })

            $j(".related-gallery li").live('mouseout', function () {
                $j(this).closest('li').removeClass('hover')
                //$j(this).removeClass('hover')
            })

            //
            // done setting up event listeners
            //
        },
        centermenu: function (hoveritem) {
            // scroll the dropdown menu by a bit if it goes off the screen
            // and the user is hovering over one of the first/last visible items
            var menudiv = $j(hoveritem).closest('.drop1')
            var screenheight = $j(window).height()
            var menutop = menudiv.offset().top - $j('body').scrollTop()
            var menubot = menutop + menudiv.height()
            var item_y = menutop + $j(hoveritem).position().top

            if (item_y + 80 > screenheight && menubot > screenheight) {
                $j(menudiv).css('top', menudiv.position().top - 25)
            } else if (item_y < 80 + 24 && menudiv.position().top < 22) {
                $j(menudiv).css('top', Math.min(22, menudiv.position().top + 25))
            }

        },
        submit: function () {
            // collect all the current filter info so the collections content can be refetched
            var opts = ''
            for (var k in active) if (active[k] != null) opts += k + ": " + active[k] + "\n"
            //alert(opts)
            CollectionService(opts, 1, 9, "");
        },
        buildrow: function (category, catvalue) {
            var select = category
            var altselects = '<ul></ul>'// CONTAINS_TMPLgets filled in by .reorder  '<ul><li><a href="#">'+availFilters.slice(1).join('</a></li><li><a href="#">') + '</a></li></ul>'

            if (filters[select].constructor == Array) {
                // it's a dropdown
                //var subselect = filters[select][0]
                var subselect = "";
                var id = 0;

                if (catvalue != "") {
                    jQuery.each(filters[select], function (i, val) {
                        if (catvalue == val) {
                            subselect = val
                            id = i;
                        }
                    });

                    if (id != 0) {
                        subselect = filters[select][id];
                    }
                    else {
                        var nidx = filters[select].push(catvalue);
                        subselect = filters[select][nidx - 1];
                    }
                } else {
                    subselect = filters[select][0];
                }

                var altsubselects = '<li><a class="filter-q" href="#">' + filters[select].slice(1).join('</a></li><li><a class="filter-q" href="#">') + '</a></li>'
                var filtRow = MENU_TMPL.replace(/%%SELECT%%/, select)
                               .replace(/%%ALTSELECTS%%/, altselects)
                               .replace(/%%SUBSELECT%%/, subselect)
                               .replace(/%%ALTSUBSELECTS%%/, altsubselects)
                               .replace(/%%ABOUT%%/, '')
                active[select] = subselect
            } else {
                var hint = filters[select]
                if (hint == "contains") {

                    var value = "";

                    if (catvalue != "")
                        value = catvalue;

                    var filtRow = CONTAINS_TMPL.replace(/%%SELECT%%/, select)
                                  .replace(/%%ALTSELECTS%%/, altselects)
                                  .replace(/%%HINT%%/, value)
                                  .replace(/%%ABOUT%%/, '')
                    // it's a textfield
                    active[select] = value;

                } else if (hint.indexOf('|') == -1) {
                    var value = hint;

                    if (catvalue != "")
                        value = catvalue;

                    var filtRow = INPUT_TMPL.replace(/%%SELECT%%/, select)
                                  .replace(/%%ALTSELECTS%%/, altselects)
                                  .replace(/%%HINT%%/, value)
                                  .replace(/%%ABOUT%%/, '')
                    // it's a textfield
                    active[select] = value
                }

                else {
                    // it's a range
                    var range1 = hint.split("|")[0]
                    var range2 = hint.split("|")[1]
                    var filtRow = RANGE_TMPL.replace(/%%SELECT%%/, select)
                                  .replace(/%%ALTSELECTS%%/, altselects)
                                  .replace(/%%RANGE1%%/, range1)
                                  .replace(/%%RANGE2%%/, range2)
                                  .replace(/%%ABOUT%%/, '')
                    active[select] = [range1, range2]
                }
            }

            return filtRow
        },
        seen: function (catname) {
            var newCats = []
            for (var cat in filters) {
                var seen = false
                for (var i = 0; i < currentCats.length; i++) {
                    if (cat == currentCats[i]) seen = true
                }
                if (!seen) newCats.push(cat)
            }
        },

        add: function () {
            var availFilters = []
            for (var cat in active) if (active[cat] == null) availFilters.push(cat)
            if (availFilters.length <= 1) return
            var select = availFilters[0]

            var filtRow = $j(that.buildrow(select, ''));
            var lastIdx = $j('.picture-form fieldset .row').size() - 1
            $j('.picture-form fieldset .row').eq(lastIdx).before(filtRow)
            that.reorder()

            var newIdx = $j('.picture-form fieldset .row').size() - 2
            $j('.picture-form fieldset .row').eq(newIdx).hide().slideDown()
        },
        drop: function (droprow) {
            var rowname = droprow.find('.select a').eq(0).text()
            active[rowname] = null
            droprow.fadeTo('slow', 0).slideUp(function () {
                $j(this).remove()
                that.reorder()
            })
        },
        reorder: function () {
            var alternatives = []
            for (var cat in active) if (active[cat] == null) alternatives.push(cat)
            var altlines = '<ul><li><a class="filter" href="#">' + alternatives.join('</a></li><li><a class="filter" href="#">') + '</a></li></ul>'
            $j(".picture-form .row").each(function (i) {
                $j(this).find('.select').eq(0).find(".drop1").html(altlines)
            })
            $j('.row .l').each(function (i) {
                if (i == 0) {
                    $j(this).find('label').eq(0).hide()
                    $j(this).find('.select').eq(1).removeClass('middle')
                    $j(this).find('.select').eq(1).removeClass('center')
                    $j(this).find('.select').eq(1).addClass('large')
                    $j(this).find('input').removeClass('middle')
                    $j(this).find('input').addClass('large')
                } else {
                    $j(this).find('label').eq(0).show()
                    $j(this).find('.select').eq(1).removeClass('large')
                    $j(this).find('.select').eq(1).addClass('middle')
                    $j(this).find('input').removeClass('large')
                    $j(this).find('input').addClass('middle')
                }
            })
        },
        refilter: function (rowElt, category) {
            var oldCat = $j(rowElt).find('.select a').eq(0).text()
            active[oldCat] = null

            var newRow = that.buildrow(category, '')
            $j(rowElt).html($j(newRow).html())
            that.reorder()
        },
        query: function (rowElt, selection) {
            var category = $j(rowElt).find('.select a').eq(0).text()
            var altSelections = filters[category].slice()
            for (var i in altSelections) if (altSelections[i] == selection) altSelections.splice(i, 1)
            var alternatives = '<li><a class="filter-q" href="#">' + altSelections.join('</a></li><li><a class="filter-q" href="#">') + '</a></li>'

            $j(rowElt).find('.select:last > a').text(selection)
            $j(rowElt).find('.select:last .drop1 ul').html(alternatives)
            $j(rowElt).find('.select:last').removeClass('expand')
            active[category] = selection
        },
        hide: function (shouldClear) {


            var cleanup = function () {
                var lastIdx = $j('.row').size() - 1
                if (shouldClear) $j('.row').each(function (i) {
                    var rowname = $j(this).find('.select a').eq(0).text()
                    if (active[rowname] != undefined) active[rowname] = null
                    if (i < lastIdx) $j(this).remove()
                })
            }

            $j(".picture-form").slideUp(function () {
                var lastIdx = $j('.row').size() - 1
                if (shouldClear) $j('.row').each(function (i) {
                    var rowname = $j(this).find('.select a').eq(0).text()
                    if (active[rowname] != undefined) active[rowname] = null
                    if (i < lastIdx) $j(this).remove()
                })

                if (shouldClear) {
                    var deptRow = $j(that.buildrow('Keywords', ''));
                    $j('.picture-form fieldset .row').eq(0).before(deptRow)
                }
                that.reorder()
            })
            $j(".add-header-box a.hide-link").removeClass('hide-link').addClass('btn-search').text('search collections')

            CMA.Web.CollectionService.ClearCollectionSearchFilters(
                        function (result) {
                            //                            if (result == "1") {
                            //                            }
                        }
                        , ServiceError, ServiceTimeout);
        },

        populatesearch: function () {
            CMA.Web.CollectionService.GetCollectionSearchInfo(
                        function (result) {
                            if (result != "" && (result.indexOf("META") == -1) && result.toString().split('|')[1] != "1") {
                                //Clear the default search option in the Advanced search
                                var lastIdx = $j('.row').size() - 1;
                                shouldClear = true;
                                if (shouldClear) $j('.row').each(function (i) {
                                    var rowname = $j(this).find('.select a').eq(0).text()
                                    if (active[rowname] != undefined) active[rowname] = null
                                    if (i < lastIdx) $j(this).remove()
                                });

                                //Get the search option from the session and populate that in the Advanced Search
                                var array = result.toString().split('|')[0].split('\n');
                                jQuery.each(array, function (i, val) {
                                    if (val == "") return;

                                    var s = val.split(':');
                                    var filtRow = $j(that.buildrow(s[0], jQuery.trim(s[1])));
                                    var lastIdx = $j('.picture-form fieldset .row').size() - 1
                                    $j('.picture-form fieldset .row').eq(lastIdx).before(filtRow)
                                    that.reorder()

                                    var newIdx = $j('.picture-form fieldset .row').size() - 2
                                    $j('.picture-form fieldset .row').eq(newIdx).hide().slideDown()
                                });
                            }
                        }
                        , ServiceError, ServiceTimeout);

        }
    }

    var url = "http://" + document.location.host + "/layouts/jsongenerator.aspx";
    //$j.getJSON('../../js/filters.txt', function(data) {
    $j.getJSON(url, function(data) {
        that.init(data)
        //that.hide(true);
    })

    return that
}


function Cal() {
    var MONTHS = 'January February March April May June July August September October November December'.split(' ')
    var HEADER = '<li class="week">S</li>	<li class="week">M</li>	<li class="week">T</li>	<li class="week">W</li>	<li class="week">T</li>	<li class="week">F</li>	<li class="week">S</li>'

    var _m = null
    var _y = null
    var _target = null
    var _choice = null
    var that = {
        init: function () {
            var now = new Date()
            that.update(now.getMonth(), now.getFullYear())

            $j('.calendar-drop .next').live('click', function () {
                if (_m == 11) that.update(0, _y + 1)
                else that.update(_m + 1, _y)
                return false
            })
            $j('.calendar-drop .prev').live('click', function () {
                if (_m == 0) that.update(11, _y - 1)
                else that.update(_m - 1, _y)
                return false
            })
            $j('.calendar-drop li a').live('click', function () {
                var day = $j(this).text()
                $j(_target).val((_m + 1) + "." + day + "." + _y)
                that.hidecal()
                return false
            })
            //            $j(".calendar-form input").focus(function() {
            //                that.showcal(this);
            //                return false
            //            })

            $j('.calendar-drop .date a.month').live('click', function () {
                var numberofDaysinMonth = new Date(_y, _m+1, 0).getDate();

                var firstdayofMonth = ((_m + 1) + "." + "1" + "." + _y);
                var lastdayofMonth = ((_m + 1) + "." + numberofDaysinMonth + "." + _y);

                $j('.calendar-form #idstartdate').val(firstdayofMonth);
                $j('.calendar-form #idenddate').val(lastdayofMonth);
                that.hidecal()

                return false;
            });

            $j(".calendar-form input").live('click', function (e) {
                that.showcal(this);
                return false
            })

            $j('.calendar-form .select').live('click', function (e) {
                // show the filter dropdown on click
                var dismiss = $j(this).hasClass('expand')
                $j('.calendar-form .select').removeClass('expand')

                if (!dismiss) {
                    $j(this).addClass('expand')
                }
            })

            $j('.calendar-form #submit a').live('click', function () {
                $j(this).removeAttr('href');
                var sdate = $j('.calendar-form #idstartdate').val();
                var edate = $j('.calendar-form #idenddate').val();
                if (sdate == 'start date')
                    alert('Please select a start date.');

                if (edate == 'end date')
                    alert('Please select a end date.');

                if (sdate != 'start date' && edate != 'end date') {
                    var eventtype = $j.query.get('eventtype');
                    var url = document.location.href.split('?')[0] + "?daterange=" + sdate + "-" + edate;

                    if (eventtype != "") {
                        url = url + "&eventtype=" + eventtype;
                    }

                    $j(location).attr('href', url);
                }
                //return true;

            })

            $j(".btn-calendar").live('click', function () {
                if (_target) that.hidecal()
                else that.showcal($j(this).prev())
                return false
            })
        },

        showcal: function (targetField) {

            _target = $j(targetField)
            var parsedDate = new Date(_target.val())
            if (!isNaN(parsedDate)) {
                _choice = parsedDate
                that.update(_choice.getMonth(), _choice.getFullYear())
            } else {
                _choice = null
            }
            $j(_target).siblings('.calendar-drop').show()
        },

        hidecal: function () {

            $j(_target).siblings('.calendar-drop').hide()
            _target = null
        },

        update: function (mnth, yr) {

            // redraw the calendar for the specified month and yr
            _m = mnth; _y = yr
            var today = new Date()
            today = new Date(today.getFullYear(), today.getMonth(), today.getDate())
            var dayStepper = new Date(yr, mnth, 1)
            var thisMonth = dayStepper.getMonth()

            var calrows = [HEADER]
            for (var i = 0; i < dayStepper.getDay(); i++) calrows.push('<li>&nbsp;</li>')

            while (dayStepper.getMonth() == mnth) {
                if (dayStepper.getDay() == 1) calrows.push('<li>' + dayStepper.getDate() + '</li>')
                else if (("" + dayStepper) == ("" + _choice)) calrows.push('<li><a class="active" href="#">' + dayStepper.getDate() + '</a></li>')
                else calrows.push('<li><a href="#">' + dayStepper.getDate() + '</a></li>')

                dayStepper.setDate(dayStepper.getDate() + 1)
            }
            //$j('.calendar-drop .date strong').text(MONTHS[mnth] + " " + yr)
            $j('.calendar-drop .date a.month').text(MONTHS[mnth] + " " + yr)
            $j('.calendar-drop ul').html(calrows.join(""))
        }
    }

    that.init()
    return that
}


function Search() {

    // when the search field gets focus, wipe any placeholder text
    // but preserve any previous user input
    $j('#header fieldset input').focus(function() {
        $j(this).addClass('active')
        if (this.value == 'search') {
            this.value = ''
        }
    })

    // when defocusing, add back the placeholder text if the field
    // has no input or if it's all whitespace
    $j('#header fieldset input').blur(function() {
        if (this.value.match(/^[ ]*$/)) {
            $j(this).removeClass('active')
            this.value = 'search'
        }
    })

}



function Popup() {
    var visible = false
    var info = null
    var slideIdx = 0

    var that = {
        showsIFR: function() {
            //            var gotham = { src: '../../swf/gotham.swf', wmode: 'transparent', color: "#ffffff" };
            //            sIFR.replace(gotham, {
            //                selector: '.popup-container .popup .content .section-body h2 span',
            //                css: '.sIFR-root { color:#ffffff;}'
            //            });
        },

        show: function() {
            if (visible) return
            visible = true

            //var top_y = Math.max(0, $j('body').scrollTop() - 60)
            var top_y = Math.max(0, $j(window).scrollTop() - 60)

            $j('.popup-container').css('top', top_y)

            $j('.popup-bg').stop(true).show()
            $j('.popup-container').stop(true).show()

            //            if ($j.browser.msie) {
            //                $j('.popup-bg').stop(true).show()
            //                $j('.popup-container').stop(true).show()
            //            } else {
            //                $j('.popup-bg').stop(true).css('opacity', 0).show().animate({ opacity: 1 }, 'slow')
            //                $j('.popup-container').stop(true).css('opacity', 0).show().animate({ opacity: 1 }, 'slow')
            //                $j('.popup .image-holder img').animate({ opacity: 1 }, 'slow')
            //            }

            //            var gotham = { src: '../../swf/gotham.swf', wmode: 'transparent', color: "#ffffff" };
            //            sIFR.replace(gotham, {
            //                selector: '.popup-container .popup .content .section-body h2 span',
            //                css: '.sIFR-root { color:#fff;}'

            //            });
        },

        hide: function() {
            if (!visible) return
            visible = false

            $j('.popup-bg').hide();
            $j('.popup-container').hide();
            $j('.popup-container').empty();
            //$j('.popup .image-holder img').attr('src', '')
            slideIdx = -1

            //            if ($j.browser.msie) {
            //                $j('.popup-bg').hide()
            //                $j('.popup-container').hide()
            //                //$j('.popup .image-holder img').attr('src', '')
            //                slideIdx = -1
            //                return
            //            }

            //            $j('.popup-bg').stop(true).show().animate({ opacity: 0 }, 'slow', function() {
            //                $j('.popup-bg').hide()
            //            })
            //            $j('.popup-container').stop(true).show().animate({ opacity: 0 }, 'slow', function() {
            //                $j('.popup-container').hide()
            //                $j('.popup .image-holder img').attr('src', '').css('opacity', 0)

            //                slideIdx = -1
            //            })
        },

        insertPictionVideo: function(url) {

            var videoAnchor;
            //url = "http://localhost/flowplayervideo.aspx?videourl=http://flashy.flowplayer.org/video/flowplayer-700.flv";
            //url = "http://localhost/layouts/flowplayervideo.aspx?videourl=http://dam01.clevelandart.org:7777/vnla/ump.show_public_image?v_umo=4658926&quality=WEB";
            $j(".popup-container .popup .image-holder .image-section img").hide();
            //$j(".popup-container .popup .image-holder .image-section div.info").hide();
            $j(".popup-container .popup .controls .pagin").hide();

            if ($j.browser.msie) {
                if (document.location.host == url.split('/')[2]) {
                    $j.get(url, function(data1) {
                        videoAnchor = $j(data1).filter("#video")[0].innerHTML;
                        $j(".popup-container .popup .image-holder .image-section").append(data1);
                    })
                }
            } else {
                $j('.popup-container .popup .image-holder .image-section').stop(true).animate({ opacity: 0 }, 'slow', function() {
                    $j.get(url, function(data1) {
                        videoAnchor = $j(data1).filter("#video")[0].innerHTML;
                        $j(".popup-container .popup .image-holder .image-section").append(videoAnchor);
                        $j('.popup-container .popup .image-holder .image-section').animate({ opacity: 1 }, 'slow');
                    });
                });
            }
        },

        removePictionVideo: function() {
            $j(".popup-container .popup .image-holder .image-section img").show();
            $j(".popup-container .popup .image-holder .image-section .info").show();
            $j(".popup-container .popup .controls .pagin").show();
            if ($j("#video").length > 0) {
                $j("#video").unbind();
                $j("#video").remove();
            }
            if ($j("#flowplayerflowplayer").length > 0) {
                // Safari doesn't insert the video div so we need to remove the object tags.
                $j("#flowplayerflowplayer").unbind();
                $j("#flowplayerflowplayer").remove();
            }
        },

        select: function(subnavElt) {

            var url = subnavElt;


            var itemid = gup("ItemId", url);
            var simpleurl = ""; //

            if ($j("#video").length > 0 || $j("#flowplayerflowplayer").length > 0) {
                that.removePictionVideo();
            }

            if (url.indexOf('/uid') == -1) {
                simpleurl = url
            } else {
                simpleurl = url.substring(0, url.indexOf('/uid')) + "?ItemId=" + itemid;
            }

            if ($j.browser.msie) {
                if (document.location.host == url.split('/')[2]) {

                    $j.get(simpleurl, function(data1) {
                        //$j('.popup-container .popup .content').append('<div class="section-body">' + data1 + "</div>")
                        $j('.popup .content .section-body').empty();
                        $j('.popup .content .section-body').html(data1);
                        that.showsIFR();
                    })
                }
                else {
                    window.open(url);
                }
                return;
            }

            //Since Firefox does not send the host information in the url for the links at the same server, check for it, if there http:// is there 
            //then this is a external link.

            if (url.startsWith("http://")) {
                window.open(url);
                return;
            }

            $j('.popup .content .section-body').stop(true).animate({ opacity: 0 }, 'slow', function() {
                $j.get(simpleurl, function(data1) {
                    $j('.popup .content .section-body').html(data1)
                    //$j('.popup .content h2').html('<span>' + info.content[newIdx].header + '</span>')
                    $j('.popup .content .section-body').animate({ opacity: 1 }, 'slow')
                    that.showsIFR();
                });
            });
        },

        selectwithquerystring: function(subnavElt) {

            var url = subnavElt;

            if ($j("#video").length > 0 || $j("#flowplayerflowplayer").length > 0) {
                that.removePictionVideo();
            }

            if ($j.browser.msie) {
                if (document.location.host == url.split('/')[2]) {

                    $j.get(url, function(data1) {
                        //$j('.popup-container .popup .content').append('<div class="section-body">' + data1 + "</div>")
                        $j('.popup .content .section-body').empty();
                        $j('.popup .content .section-body').html(data1);
                        that.showsIFR();
                    })
                }
                else {
                    window.open(url);
                }
                return;
            }

            //Since Firefox does not send the host information in the url for the links at the same server, check for it, if there http:// is there 
            //then this is a external link.

            if (url.startsWith("http://")) {
                window.open(url);
                return;
            }

            $j('.popup .content .section-body').stop(true).animate({ opacity: 0 }, 'slow', function() {
                $j.get(url, function(data1) {

                    $j('.popup .content .section-body').html(data1)
                    //$j('.popup .content h2').html('<span>' + info.content[newIdx].header + '</span>')
                    //$j('.popup-container .popup .content .section-body h2 span').animate({ opacity: 1 }, 'slow')
                    $j('.popup .content .section-body').animate({ opacity: 1 }, 'slow')
                    that.showsIFR();
                });
            });
        },

        prepareFetch: function (anchor) {
            var url = $j(anchor).attr("href");
            if ($j(anchor).attr("id") == "externalPage") {
                if ($j(anchor).attr("target") == "_blank") {
                    window.open(url);
                }
                else {
                    $j(location).attr('href', url);
                }
            }
            else {
                var path = $j(anchor).attr("pathname");
                var sidebar = gup('sidebar', url);
                var uid = gup('uid', url);
                var pid = gup('pid', url);
                var eventtype = gup('eventtype', url);
                var sidebar = gup('sidebar', url);
                var isCardLayout = gup('iscardlayout', url);
                var pid = gup('pid', url);
                var islookup = gup('islookup', url);

                CMA.Web.CMAHelperService.IsMemberContent(path,
                        function(result) {

                            if (result != "") {
                                var array = result.toString().split('|');

                                if (array[0] == "True") {
                                    that.IsMemberOrPress("member", "article", url, path);
                                }
                                else {
                                    if (isCardLayout == "1") {
                                        var curl = url.substring(0, url.indexOf('/iscardlayout'));
                                        $j(location).attr('href', curl);
                                    }
                                    else if (uid != "") {
                                        //                                        var mUrl = url.substring(0, url.indexOf('?'))
                                        //                                        that.fetchPage(mUrl);
                                        if (pid == "") {

                                            var mUrl = "";
                                            if (url.indexOf('?') != -1) {
                                                mUrl = url.substring(0, url.indexOf('?'))
                                            }
                                            else {
                                                mUrl = url.substring(0, url.indexOf("/uid"));
                                            }

                                            if (sidebar != "") {
                                                mUrl = mUrl + '/upageid/' + uid + "/sidebar/" + sidebar;
                                            }
                                            else {
                                                mUrl = mUrl + '/upageid/' + uid;
                                            }

                                            if (islookup != "")
                                                mUrl = mUrl + "/islookup/" + islookup;

                                            that.fetchPage(mUrl);
                                        }
                                        else {
                                            $j(location).attr('href', url);
                                            return false;
                                        }
                                    }
                                    else if (eventtype != "") {
                                        var mUrl = url.substring(0, url.indexOf("/eventtype")) + "?eventtype=" + eventtype;
                                        $j(location).attr('href', mUrl);
                                        return true;
                                    }
                                    else {
                                        that.fetchPage(url)
                                    }
                                }
                            }
                        }
                        , ServiceError, ServiceTimeout);

            }
            return false;
        },

        prepareFetchDeeplink: function (anchor) {
            var url = $j(anchor).attr("href");
            if ($j(anchor).attr("id") == "externalPage") {
                if ($j(anchor).attr("target") == "_blank") {
                    window.open(url);
                }
                else {
                    $j(location).attr('href', url);
                }
            }
            else {
                var uid = gup('uid', url);
                var pid = gup('pid', url);
                var eventtype = gup('eventtype', url);
                var sidebar = gup('sidebar', url);
                var isCardLayout = gup('iscardlayout', url);

                if (isCardLayout == "1") {
                    url = url.substring(0, url.indexOf('/iscardlayout'));
                    $j(location).attr('href', url);
                }
                else if (uid != "") {

                    if (pid == "") {

                        var mUrl = "";
                        if (url.indexOf('?') != -1) {
                            mUrl = url.substring(0, url.indexOf('?'))
                        }
                        else {
                            mUrl = url.substring(0, url.indexOf("/uid"));
                        }

                        if (sidebar != "") {
                            that.fetchPage(mUrl + '?upageid=' + uid + "&sidebar=" + sidebar);
                        }
                        else {
                            that.fetchPage(mUrl + '?upageid=' + uid);
                        }
                    }
                    else {
                        $j(location).attr('href', url);
                        return false;
                    }
                }
                else if (eventtype != "") {
                    $j(location).attr('href', url);
                    return true;
                }
                else {
                    that.fetchPage(url)
                }
            }

        },

        fetch: function(jsonUrl) {
            $j.getJSON(jsonUrl, function(data) {
                info = data
                var folios = ''
                if (data.img) {
                    // single image
                    $j('.popup .image-holder img').attr('src', data.img)
                    $j('.popup .image-holder img').removeClass('slideshow')
                    $j('.popup .controls .pagin div').hide()
                    $j('.popup .controls .pagin div ul').hide()
                    $j('.popup .image-holder .info').hide()
                } else if (data.slideshow) {
                    // list of images (i.e., slideshow)
                    $j('.popup .image-holder img').addClass('slideshow')
                    $j('.popup .controls .pagin div').show()
                    for (var i = 1; i <= data.slideshow.length; i++) {
                        folios += '<li><a href="#">' + i + '</a></li>'
                    }
                    $j('.popup .controls .pagin div ul').show().html(folios)
                    that.slideshow(0)
                }

                if (info.kind == 'day-summary') {
                    $j('.controls .btn-next').text('next day').show()
                    $j('.controls .btn-prev').text('previous day').show()
                } else if (info.kind == 'event-summary') {
                    $j('.controls .btn-next').text('next event').show()
                    $j('.controls .btn-prev').text('previous event').show()
                } else {
                    $j('.controls .btn-next').hide()
                    $j('.controls .btn-prev').hide()
                }

                $j('.popup .content').html('<h2><span>' + data.content[0].header + '</span></h2>')
                $j('.popup .content').append('<div class="section-body">' + data.content[0].text + "</div>")

                var subnavTxt = []
                for (var i in data.content) if (data.content[i].subnav) subnavTxt.push(data.content[i].subnav)
                $j('.popup .sidebar ul').html("<li><a href='#' class='active'>" + subnavTxt.join("</a></li><li><a href='#'>") + '</a></li>')
                $j(".popup .wrapper .sidebar a").eq(0).addClass('active').removeAttr('href')
                that.show()
            })
        },

        fetchPage: function(url) {
            // Add year query string if filter value has been set.  Used for prev/next popup links.
            var year = $j("#hfCardFilter").val();
            var requestUrl = url;

            // if # then do nothing
            if (requestUrl == "#") {
                return
            }

            if (year != "") {
                // Check if query strings already exist.
                if (url.indexOf("?") == -1) {
                    // url has no query string parameters.
                    url = url + "?Filter=" + encodeURI(year); // encode in case special characters are used.
                }
                else {
                    url = url + "&Filter=" + encodeURI(year);
                }
            }

            $j.get(url, function (data) {
                $j('.popup-container').empty();
                $j('.popup-container').html(data);

                //Populate the Image box
                if ($j('.popup-container .popup .controls .pagin div li a')[0] != null) {

                    var url = $j('.popup-container .popup .controls .pagin div li a')[0].href;
                    //var url = sidebarli.href
                    if (document.location.host == url.split('/')[2]) {
                        $j.get(url, function(data1) {

                            $j('.popup-container .popup .image-holder .image-section').empty();

                            $j('.popup-container .popup .image-holder .image-section').append(data1);
                        })
                    }

                    $j(".popup-container .popup .controls .pagin div li a").eq(0).addClass('active')
                    //$j(".popup .wrapper .sidebar a").eq(0).addClass('active')
                }

                sidebar = gup('sidebar', requestUrl);

                //Not sure why we have this code below, need to find out but it is breaking Hi-res image..
                //if (sidebar == "") {
                //    sidebar = $j.query.get('sidebar');
                //}

                var sidebarHref = "";
                var id = 0;

                if (sidebar != "") {
                    var sidebarli = $j('.popup-container .popup .sidebar ul li');

                    jQuery.each(sidebarli, function(i, val) {
                        if (sidebar == val.firstChild.innerHTML) {
                            sidebarHref = val.firstChild.href;
                            id = i;
                        }
                    });

                }

                if (sidebarHref != "") {
                    var url = sidebarHref
                    if (document.location.host == url.split('/')[2]) {
                        var itemid = gup("ItemId", url);
                        var simpleurl = url.substring(0, url.indexOf('/uid')) + "?ItemId=" + itemid;

                        $j.get(simpleurl, function(data1) {
                            //$j('.popup-container .popup .content').append('<div class="section-body">' + data1 + "</div>")
                            $j('.popup-container .popup .content .section-body').html(data1);
                        })
                    }

                    $j(".popup .wrapper .sidebar a").eq(id).addClass('active')

                }
                else if ($j('.popup-container .popup .sidebar ul li')[0] != null && $j("#departments a").length == 0) {
                    var sidebarli = $j('.popup-container .popup .sidebar ul li')[0].firstChild;

                    //$j('.popup-container .popup .content').html('<h2><span>' + sidebarli.innerHTML + '</span></h2>');

                    var url = sidebarli.href
                    if (document.location.host == url.split('/')[2]) {
                        var itemid = gup("ItemId", url);
                        var upageid = gup("upageid", url);

                        var simpleurl = ""; //

                        if (url.indexOf("/uid") == -1) {
                            simpleurl = url
                        } else {
                            simpleurl = url.substring(0, url.indexOf('/uid')) + "?ItemId=" + itemid;
                        }


                        $j.get(simpleurl, function(data1) {
                            //$j('.popup-container .popup .content').append('<div class="section-body">' + data1 + "</div>")
                            $j('.popup-container .popup .content .section-body').html(data1);
                            that.showsIFR();
                        });
                    }

                    $j(".popup .wrapper .sidebar a").eq(0).addClass('active');


                    //if the sidebar has only one item, then hide it
                    if ($j('.popup-container .popup .sidebar ul li').size() == 1) {

                        $j(".popup .wrapper .sidebar a").eq(0).hide();

                    };
                }
                that.show()
            })
        },

        IsMemberContent: function(url) {

            var ismembercontent = false;

            CMA.Web.CMAHelperService.IsMemberContent(url.substring(0, url.indexOf('?')),
            function(result) {

                if (result != "") {
                    var array = result.toString().split('|');

                    if (array[0] == "True") {
                        ismembercontent = true;
                    }
                }
            }
            , ServiceError, ServiceTimeout);

            return ismembercontent
        },

        IsMemberOrPress: function (type, linktype, url, path) {
            var uid = gup('uid', url);
            CMA.Web.CMAHelperService.IsMemberOrPress(type, url,
                                function(result) {

                                    if (result != "") {
                                        var array = result.toString().split('|');

                                        if ((array[0].toLowerCase() == "member") || (array[0].toLowerCase() == "press")) {
                                            if (linktype.toLowerCase() == "sidebar") {
                                                var mUrl = url.substring(0, url.indexOf('/uid'))
                                                that.select(mUrl);
                                            }
                                            else {
                                                if (uid != "") {
                                                    var mUrl = url.substring(0, url.indexOf('/uid'))
                                                    that.fetchPage(mUrl);
                                                }
                                                else {
                                                    that.fetchPage(url);
                                                }
                                            }
                                        }
                                        else {
                                            var redirecturl = "http://" + document.location.host + "/global/Restricted Access.aspx?type=" + type; //+"&pid=" + pid;
                                            that.fetchPage(redirecturl);
                                        }
                                    }
                                }
                                , ServiceError, ServiceTimeout);
            return false;
        },

        fetchIframe: function(url) {
            iframeurl = "http://" + document.location.host + "/global/IFrame Page.aspx";

            $j.get(iframeurl, function(data) {


                $j('.popup-container').empty();
                $j('.popup-container').scroll();
                //$j('.popup-container').html(data);
                $j('.popup-container').append('<div class="iframe-body">' + data + "</div>")

                //Build the iFrame
                var oIFrame = BuildIFrame();
                oIFrame.id = "RegisterationIFrame";

                $j('.popup-container .popup .content .section-body').height(2200);

                $j('.popup-container .popup .content .section-body').html(oIFrame);

                oIFrame.src = url;

                if ($j.browser.msie) {
                    var fheight = oIFrame.document.body.scrollHeight + 1500;
                    IFrameresize(oIFrame.id, fheight);
                }
                else {
                    var fheight = $j('#RegisterationIFrame').scrollHeight;
                    IFrameresize(oIFrame.id, fheight + 1500);
                }
                that.show();

            });
        },


        slideshow: function (showIdx) {
            if (showIdx == slideIdx) return
            slideIdx = showIdx

            var url = $j('.popup-container .popup .controls .pagin div li a')[showIdx].href;
            var imagesrc = "";
            var info = "";

            if (document.location.host == url.split('/')[2]) {
                $j.get(url, function(data1) {

                    imagesrc = $j(data1).filter('img')[0].src;
                    imagealt = $j(data1).filter('img')[0].alt;
                    if ($j(data1).filter('.info') != null && $j(data1).filter('.info')[0] != null)
                        info = $j(data1).filter('.info')[0].innerHTML;

                    $j('.popup-container .popup .image-holder .image-section img').attr('src', imagesrc);
                    $j('.popup-container .popup .image-holder .image-section img').attr('alt', imagealt);
                    $j('.popup-container .popup .image-holder .image-section .info').html(info);

                    //                    if ($j.browser.msie) {
                    //                        $j('.popup-container .popup .image-holder .image-section img').attr('src', imagesrc);
                    //                        $j('.popup-container .popup .image-holder .image-section img').attr('alt', imagealt);
                    //                        $j('.popup-container .popup .image-holder .image-section .info').html(info);
                    //                    } else {
                    //                        $j('.popup .image-holder img').stop(true).animate({ opacity: 0 }, 'slow', function() {
                    //                            $j('.popup .image-holder .loading').show()
                    //                            // wait for the image to load before we fade the element back up
                    //                            $j('.popup .image-holder img').load(function() {
                    //                                $j('.popup .image-holder .loading').hide()
                    //                                $j('.popup .image-holder img').animate({ opacity: 1 }, 'slow')
                    //                            });
                    //                            //                            // wait for the image to load before we fade the element back up
                    //                            //                            $j('.popup .image-holder img').load(function() {
                    //                            //                                $j('.popup .image-holder img').animate({ opacity: 1 }, 'slow')
                    //                            //                            });
                    //                            $j('.popup .image-holder img').attr('src', imagesrc)
                    //                            $j('.popup .image-holder .image-section .info').html(info);
                    //                            $j('.popup .image-holder img').animate({ opacity: 5 }, 'fast');
                    //                        });
                    //                    }
                });
            }


            $j(".popup .controls .pagin div ul li > a").removeClass('active')
            $j(".popup .controls .pagin div ul li > a").eq(showIdx).addClass('active')
        },
        step: function(target) {
            var newIdx = slideIdx
            if (newIdx < 0) {
                newIdx = 0;
            }
            var target = $j(target)
            if (target.hasClass('prev')) {
                newIdx--
            } else if (target.hasClass('next')) {
                newIdx++
            }
            newIdx = Math.max(newIdx, 0)

            //newIdx = Math.min(newIdx, info.slideshow.length - 1)
            var length = $j('.popup-container .popup .controls .pagin div li').length
            newIdx = Math.min(newIdx, length - 1)
            that.slideshow(newIdx)
        }

    }
    // Search popup
    $j("#header .header-wrapper .wrapper a.btn-search").live('click', function() {
        var url;
        //var url = $j(".btn-search").context.activeElement.href
        if (!$j.browser.msie) {
            url = ($j(this).attr('href'))
        }
        else {
            url = this.href;
        }

        // Get text user entered and add to query string.
        url = url + encodeURI($j("#header fieldset input").val());
        $j(location).attr('href', url);
        //that.fetchPage(url)
        return false
    })

    $j("#header fieldset input").live('keypress', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            //alert("event handler has been reached");
            var url;
            //var url = $j(".btn-search").context.activeElement.href
            if (!$j.browser.msie || parseInt($j.browser.version) == 7) {
                url = $j("#header .header-wrapper .wrapper a.btn-search").attr('href');
            }
            else {
                url = $j("#header .header-wrapper .wrapper a.btn-search")[0].href
            }

            // Get text user entered and add to query string.
            url = url + encodeURI($j(this).val());
            $j(location).attr('href', url);
            //that.fetchPage(url)
            return false;
        }
    });

    // for any labeled image box, load the canned popup contents html (packaged in a json file)
    $j(".event > a").live('click', function() {
        that.prepareFetch(this);
        return false
    })

    $j(".txt .link-on > a").live('click', function() {
        that.prepareFetch(this);
        return false;
    })

    $j(".txt p > a").live('click', function() {
        that.prepareFetch(this);
        return false
    })
    
    $j(".popup .content > a").live('click', function() {
        that.prepareFetch(this);
        return false;
    })

    // for full-bleed image boxes, load the alternative canned popup with a slideshow
    $j(".collection > a").live('click', function() {
        //var url = $j(".collection > a").context.activeElement.href
        var url = $j(this).attr("href");
        var uid = gup('uid', url);
        var coid = gup('coid', url);
        var islookup = gup('islookup', url);

        if ($j(this).attr("id").toLowerCase() == "logocard") {
            window.location(url);
        }
        else if (uid != "") {

            var mUrl = url.substring(0, url.indexOf('/uid'))

            that.fetchPage(mUrl + '?upageid=' + uid + '&coid=' + coid + '&islookup=' + islookup);
        }
        else {
            that.fetchPage(url)
        }
        return false
    });

    $j(".picture-gallery li > a").live('click', function() {
        //var url = $j(".picture-gallery li > a").context.activeElement.href
        var url = $j(this).attr("href");
        var uid = gup('uid', url);
        var coid = gup('coid', url);
        var dept = gup('dept', url);

        if (uid != "") {
            var mUrl = url.substring(0, url.indexOf('/uid'))
            that.fetchPage(mUrl + '?coid=' + coid + '&dept=' + dept);
        }
        //that.fetchPage(url)
        return false
    })

    $j(".picture-gallery .noimage a").live('click', function() {
        //var url = $j(".picture-gallery li > a").context.activeElement.href
        var url = $j(this).attr("href");
        var uid = gup('uid', url);
        var coid = gup('coid', url);
        var dept = gup('dept', url);

        if (uid != "") {
            var mUrl = url.substring(0, url.indexOf('/uid'))
            that.fetchPage(mUrl + '?coid=' + coid + '&dept=' + dept);
        }
        //that.fetchPage(url)
        return false
    })

    $j(".related-gallery li > a").live('click', function() {
        //var url = $j(".picture-gallery li > a").context.activeElement.href
        var url = $j(this).attr("href");

        var uid = gup('uid', url);
        var coid = gup('coid', url);
        var dept = gup('dept', url);

        if (uid != "") {
            var mUrl = url.substring(0, url.indexOf('/uid'))
            that.fetchPage(mUrl + '?coid=' + coid + '&dept=' + dept);
        }
        return false
    })

    $j(".related-gallery .noimage a").live('click', function() {
        var url = $j(this).attr("href");

        var uid = gup('uid', url);
        var coid = gup('coid', url);
        var dept = gup('dept', url);

        if (uid != "") {
            var mUrl = url.substring(0, url.indexOf('/uid'))
            that.fetchPage(mUrl + '?coid=' + coid + '&dept=' + dept);
        }
        return false
    })

    // all the other image-boxes in the day take you to the same canned event listing for now
    //  $j('.calendar-box .img-wrapper li.featured a').live('click', function(){
    //    that.fetch('data/single-event.json')
    //    return false
    //  })

    // the first link box in each day is a summary
    $j('.calendar-box .img-wrapper li.summary a').live('click', function() {
        var url = $j(this).attr("href");
        that.fetchPage(url);

        return false
    })

    // the close button inside the popup dismisses it
    $j(".iframe-body .controls > a").live('click', function() {

        CMA.Web.CMAHelperService.GetRestrictedContentUrl(
                    function(result) {
                        if (result != "") {
                            $j(location).attr('href', result);
                        }
                        else {
                            var rurl = RemoveHashInUrl(document.location.href);
                            if (rurl.indexOf('?pid') != -1)
                                rurl = rurl.substring(0, rurl.indexOf('?pid'));
                            $j(location).attr('href', rurl);
                        }
                    }
                    , ServiceError, ServiceTimeout);
        return false;
    });

    // the close button inside the popup dismisses it
    $j(".controls > a").live('click', function() {

        var classtype = ($j(this).attr('class'))
        var url = ($j(this).attr('href'))

        if (classtype == "btn-prev" || classtype == "btn-next") {
            if (url.charAt(url.length - 1) == "#") return;
            //if (url == "#") return
            that.fetchPage(url)
        }
        else {
            that.hide()
        }
        return false
    })

    $j("#thumbnail_slidepanel_link .btn-wrapper a.btn").live('click', function() {
        var url = $j(this).attr('href');

        var isPopup = gup('ispopup', url);

        if ($j(this).attr("id") == "externalPage") {
            if ($j(this).attr("target") == "_blank") {
                window.open(url);
            }
            else {
                $j(location).attr('href', url);
            }
        }
        else {
            if (isPopup == "1") {
                that.prepareFetch(this);
            }
            else {
                $j(location).attr('href', url);
            }
        }
        return false
    });

    $j("#interpretationbacklink").live('click', function() {
        var url;
        if ($j("#video").length > 0) {
            that.removePictionVideo();
        }
        if (!$j.browser.msie) {
            url = $j(".popup .wrapper .sidebar a.active").attr('href');
        }
        else {
            url = $j(".popup .wrapper .sidebar a.active")[0].href;
        }


        that.select(url);
    });

    $j("#interpretationlist li .info .btn-wrapper a").live('click', function() {
        var url;
        var videoUrl;
        if (!$j.browser.msie) {
            url = ($j(this).attr('href'))
        }
        else {
            url = this.href;
        }
        if (url.charAt(url.length - 1) == "#") return;
        // Check if audio player was embed
        if ($j("#audioPlayer" + $j(this).attr("id")).length > 0) {
            $j("#audioPlayer" + $j(this).attr("id")).show();
        }
        // Holds link to get embedded video for the media header.
        else if ($j("#videoLink" + $j(this).attr("id")).length > 0) {
            if (!$j.browser.msie) {
                videoUrl = $j("#videoLink" + $j(this).attr("id")).attr("href");
            }
            else {
                videoUrl = $j("#videoLink" + $j(this).attr("id"))[0].href;
            }
            that.insertPictionVideo(videoUrl);
            that.selectwithquerystring(url);
        }
        else {
            that.selectwithquerystring(url);
        }
        return false;
    });

    $j(".exhibition-list .btn-wrapper #thumbnail_link a.btn").live('click', function() {
        var url = ($j(this).attr('href'))

        if ($j(this).attr("id") == "externalPage") {
            if ($j(this).attr("target") == "_blank") {
                window.open(url);
            }
            else {
                $j(location).attr('href', url);
            }
        }
        else {
            $j(location).attr('href', url);
        }
        return false
    })

    $j(".exhibition-list .btn-wrapper a.btn").live('click', function() {
        var url = ($j(this).attr('href'))
        if (url.charAt(url.length - 1) == "#") return;
        //if (url == "#") return thumbanil_slidepanel_link
        //if (url == "#") return thumbanil_slidepanel_link
        if ($j(this).attr("id") == "externalPage" || $j(this).attr("target") == "_blank") {
            if ($j(this).attr("target") == "_blank") {
                window.open(url);
            }
            else {
                $j(location).attr('href', url);
            }
        }
        else {
            that.fetchPage(url)
        }
        return false
    })

    $j(".exhibition-list .info h3 > a").live('click', function() {
        var url = ($j(this).attr('href'))
        if (url.charAt(url.length - 1) == "#") return;
        //if (url == "#") return
        that.fetchPage(url)
        return false
    })

    $j(".exhibition-list li > a").live('click', function() {
        var url = ($j(this).attr('href'))
        if (url.charAt(url.length - 1) == "#") return;
        //if (url == "#") return
        that.fetchPage(url)
        return false
    })

    $j(".exhibition-list li a").live('click', function() {
        var url = $j(this).attr('href');

        var isPopup = gup('ispopup', url);

        if ($j(this).attr("id") == "externalPage" || $j(this).attr("target") == "_blank") {
            if ($j(this).attr("target") == "_blank") {
                window.open(url);
            }
            else {
                $j(location).attr('href', url);
            }
        }
        else {
            if (isPopup == "1") {
                that.prepareFetch(this);
            }
            else {
                $j(location).attr('href', url);
            }
        }
        return false
    });

    $j("#pressfiltersubmit a").live('click', function() {
        var url;
        if (!$j.browser.msie) {
            url = ($j(this).attr('href'))
        }
        else {
            url = this.href;
        }
        if (url.charAt(url.length - 1) == "#") return;
        // Add filtering options to query string.
        url = url + "&daterange=" + $j("[id$=idstartdate]")[0].value + "-" + $j("[id$=idenddate]")[0].value + "&category=" + $j("#presscategory :selected").val();
        that.selectwithquerystring(url);
        return false
    })

    $j("#presslist .r a").live('click', function() {
        var url;
        if (!$j.browser.msie) {
            url = ($j(this).attr('href'))
        }
        else {
            url = this.href;
        }
        if (url.charAt(url.length - 1) == "#") return;
        that.fetchPage(url)
        return false
    })

    // also, clicking the greyed out backdrop will close the popup
    $j(".popup-container").live('mousedown', function (e) {
               if (e.target.id.toString() == "pnlContent" || e.target == this || e.target.id.toString() == "popupform") {
					if ($j("#pnlContent h2").length) {
						that.hide()
						return false
						}
					//that.hide()
                   //return false
                }
    })

    // slideshow folio links will jump to the corresponding img
    $j(".popup .controls .pagin div ul li > a").live('click', function() {
        var i = Number($j(this).text())
        that.slideshow(i - 1)
        return false
    })

    // the fwd/back arrows in the slideshow control area
    $j(".controls .pagin div a").live('click', function() {
        that.step(this)
        return false
    })

    //Login Control event handlers
    $j('a#idlogin').live('click', function() {
        //var url = $j("#search-form a").context.activeElement.href
        var url = $j(this).attr("href");

        that.fetchPage(url)
        return false;
    })

    $j('#idLogin-txt-mark > a').live('click', function() {
        //var url = $j("#idLogin-txt-mark > a").context.activeElement.href
        var url = $j(this).attr("href");

        that.fetchPage(url)
        return false;
    })

    $j('a#idlogout').live('click', function() {
        CMA.Web.CMAHelperService.Logout(
            function(result) {
                if (result != "") {
                    if (result == "Success") {
                        $j('#iduname').text("");
                        var rurl = RemoveHashInUrl(document.location.href);
                        if (rurl.indexOf('?pid') != -1)
                            rurl = rurl.substring(0, rurl.indexOf('?pid'));
                        
                        $j(location).attr('href', rurl);
                    }
                }
            }
            , ServiceError, ServiceTimeout);

        return false;
    })

    // the close button inside the popup dismisses it
    $j(".login-controls > a").live('click', function() {
        that.hide();
        return false;
    })

    $j('.login-form .btn-wrapper a.joinus').live('click', function() {
        var url = $j(this).attr("href");
        that.fetchIframe(url);
        return false;
    })

    //this if for the sign up link in the comment/tag pages in the collection object panel
    $j('a.commentsignup').live('click', function() {
        var url = $j(this).attr("href");
        that.fetchIframe(url);
        return false;
    })
    
    $j(".txt-mark .link-on > a").live('click', function() {
        that.prepareFetch(this);
        return false;
    })

    $j(".txt-mark div a").live('click', function() {
        var url = $j(this).attr("href");
        var isPopup = gup('ispopup', url);
        if (isPopup == "1") {
            that.fetchPage(url)
        }
        else {
            that.fetchIframe(url);
        }
        //that.fetchIframe(url);
        //that.fetchPage(url)
        return false;
    })

    $j("#footer .copyright ul li > a").live('click', function() {
        that.prepareFetch(this);
        return false;
    })

    $j(".popup .image-holder .image-section .info a").live('click', function() {
        that.prepareFetch(this);
        return false;
    })

    $j('.login-form p a').live('click', function() {
        var url = $j(this).attr("href");

        that.fetchPage(url)
        return false;
    })

    //this if for the Login link in the comment/tag pages in the collection object panel
    $j('a.commentlogin').live('click', function() {
        var url = $j(this).attr("href");

        that.fetchPage(url)
        return false;
    })

    $j(".login-form .btn-wrapper a#idSubmit").live('click', function() {
        CMA.Web.CMAHelperService.ProcessForgetPassword($j("#idEmail").val(),
            function(result) {
                if (result != "") {
                    var array = result.toString().split('|');

                    if (array[0] == "0") {
                        $j('#idMain').hide();
                        $j('#idSuccess').html(array[1]);
                    }
                    else if (array[0] == "1") {
                        $j('#idError').html(array[1]);
                    }
                }
            }
            , ServiceError, ServiceTimeout);
    })

    $j(".login-form .btn-wrapper a#idSubmitChangePassword").live('click', function() {
        CMA.Web.CMAHelperService.ProcessChangePassword($j("#idOldPassword").val(), $j("#idNewPassword").val(), $j("#idCNewPassword").val(),
            function(result) {
                if (result != "") {
                    var array = result.toString().split('|');

                    if (array[0] == "0") {
                        $j('#idMain').hide();
                        $j('#idSuccess').html(array[1]);
                    }
                    else if (array[0] == "1") {
                        $j('#idError').html(array[1]);
                    }
                }
            }
            , ServiceError, ServiceTimeout);

        return false;
    })

    $j(".login-form .btn-wrapper a.btn-login").live('click', function() {

        var id = $j(this).attr("id");

        if (id == "#idForgot") {
            CMA.Web.CMAHelperService.ProcessForgetPassword($j("#idEmail").val(),
            function(result) {
                if (result != "") {
                    var array = result.toString().split('|');

                    if (array[0] == "0") {
                        that.hide();
                        //$j(location).attr('href', document.location.href);
                        var rurl = RemoveHashInUrl(document.location.href);
                        if (rurl.indexOf('?pid') != -1)
                            rurl = rurl.substring(0, rurl.indexOf('?pid'));
                        
                        $j(location).attr('href', rurl);
                    }
                    else {
                        $j('#idError').html(array[1]);
                    }
                }
            }
            , ServiceError, ServiceTimeout);
        } else {

            var isRemember = $j('#cbRemember').is(':checked');

            var url = $j(this).attr("href");
            var pid = gup("pid", url);
            var type = gup("type", url);

            CMA.Web.CMAHelperService.AuthenticateLogin($j("#idEmail").val(), $j("#idPassword").val(), isRemember, type,
            function(result) {
                if (result != "") {
                    var array = result.toString().split('|');

                    if (array[0] == "Success") {
                        if ((array[2].toLowerCase() == "member") || (array[2].toLowerCase() == "press")) {
                            that.hide();

                            if (array[3] != null) {
                                $j(location).attr('href', array[3]);
                            }
                            else {
                                var rurl = RemoveHashInUrl(document.location.href);
                                if (rurl.indexOf('?pid') != -1)
                                    rurl = rurl.substring(0, rurl.indexOf('?pid'));                               
                                $j(location).attr('href', rurl);
                            }
                        }
                        else if (array[2].toLowerCase() == "not") {
                            //need to change the logic below, we need to refresh the page and open the resticted access page
                            var redirecturl = "http://" + document.location.host + "/global/Restricted Access.aspx?type=" + type;
                            that.fetchPage(redirecturl);
                        }
                        else {
                            that.hide();
                            var rurl = RemoveHashInUrl(document.location.href);
                            if (rurl.indexOf('?pid') != -1) {
                                rurl = rurl.substring(0, rurl.indexOf('?pid'));

                                if (array[1] != "")
                                    rurl = rurl + "?pid=" + array[1];
                            }

                            $j(location).attr('href', rurl);

                        }
                    }
                    else {
                        $j('#idError').html(result);
                    }
                }
            }
            , ServiceError, ServiceTimeout);
        }

        return false;

    })

    $j('#nav li a').live('click', function() {
        //      var path = $j("#nav li a").context.activeElement.pathname;
        //      var url = $j("##nav li a").context.activeElement.href
        var path = $j(this).attr("pathname");
        var url = $j(this).attr("href");

        if ($j(this).text() == "calendar admin") {
            window.open(url);
            return false;
        }

        if ($j(this).attr("id") == "externalPage") {
            if ($j(this).attr("target") == "_blank") {
                window.open(url);
                return false;
            }
            else {
                $j(location).attr('href', url);
            }
        }
		
		if ($j(this).text() == "URL Tracker") {
		    window.open(url);
            return false;
		}
		
		if ($j(this).text() == "User Extract") {
		    window.open(url);
            return false;
		}

        var linktext = $j(this).text();
        if (linktext == "profile" || linktext.startsWith("Hello,")) {

            that.fetchIframe(url);
            return false;
        }
        else if (linktext == "change password") {
            that.fetchPage(url);
            return false;
        }
        else if (linktext == "logout") {
            CMA.Web.CMAHelperService.Logout(
            function(result) {
                if (result != "") {
                    if (result == "Success") {
                        var rurl = RemoveHashInUrl(document.location.href);
                        if (rurl.indexOf('?pid') != -1)
                            rurl = rurl.substring(0, rurl.indexOf('?pid'));
                                                        
                        $j(location).attr('href', rurl);
                    }
                }
            }
            , ServiceError, ServiceTimeout);

            return false;
        }


        CMA.Web.CMAHelperService.IsArticlePanel(path,
            function(result) {
                if (result != "") {
                    var array = result.toString().split('|');

                    if (array[0] == "True") {
                        that.fetchPage(url)
                    }
                    else {
                        $j(location).attr('href', url);
                    }
                }
            }
            , ServiceError, ServiceTimeout);

        return false;

    })


    $j("#reproduceimage").live('click', function() {
        var url;
        if (!$j.browser.msie) {
            url = ($j(this).attr('href'))
        }
        else {
            url = this.href;
        }
        that.select(url);
        return false;
    })

    //Event Handlers for Restric Access restrict-access-form
    $j("#restrict-access-form div #register a.btn").live('click', function() {
        var url = $j(this).attr('href');
        that.fetchIframe(url);
        return false;
    })

    $j("#restrict-access-form div #login a.btn").live('click', function() {
        var url = $j(this).attr('href');
        that.fetchPage(url);
        return false;
    })
    // clicking a sidebar link replaces the popup's body content but doesn't change the title

    $j(".popup .wrapper .sidebar a").live('click', function () {

        //if the user click the active link then return
        if ($j(this).hasClass('active')) return false
        var url;

        if (!$j.browser.msie) {
            url = ($j(this).attr('href'))
        }
        else {
            url = this.href;
        }

        if (this.id == "sharethis") {
            $j.get(url, function (data1) {
                //var top_y = Math.max(0, $j(window).scrollTop() + 150);
				var top_y = $j('.image-holder').height() - 25 //pos.top Math.max(0, $j(window).scrollTop() + 150);
                $j('.shareme-container').show();
                $j('.shareme-container').css('top', top_y)
                $j('.shareme-container').append(data1);
            })
            return false;
        }

        //var path = $j(this).attr("pathname");
        var path = location.pathname.substring(0, location.pathname.indexOf("/uid/"));
        var type = gup('type', url);
        var isCardLayout = gup('iscardlayout', url);
        var isPopup = gup('ispopup', url);

        if (isCardLayout == "1") {
            var curl = url.substring(0, url.indexOf('/iscardlayout'));
            $j(location).attr('href', curl);
        }
        if ($j(this).attr("id") == "externalPage") {
            if ($j(this).attr("target") == "_blank") {
                window.open(url);
            }
            else {
                $j(location).attr('href', url);
            }
            return false;
        }

        // if this is departments sidebar, do a fetchPage.
        if ($j("#departments a").length > 0 || isPopup == "1") {
            if (url.charAt(url.length - 1) == "#") return;
            //if (url == "#") return
            that.prepareFetch(this);
        }
        else {
            if (this.id != "print" && this.id != "sharethis") {
                if (type == "new") {
                    $j(".popup .wrapper .sidebar a").removeClass('active')
                    $j(location).attr('href', url);
                    $j(this).addClass('active');
                }
                else {
                    $j(".popup .wrapper .sidebar a").removeClass('active')
                    //$j('.popup-container .popup .content').empty();
                    //$j('.popup-container .popup .content').html('<h2><span>' + $j(this).context.innerHTML + '</span></h2>');

                    // check if this is a Press Release Hi-Res link
                    if (this.id == "highreslist") {
                        that.IsMemberOrPress("press", "sidebar", url, path);
                    }
                    else {
                        that.select(url);
                    }
                    $j(this).addClass('active');
                }
            }

        }
        return false;
    })
    that.hide()
    return that
}

///////////////////////////////////////////////////////////////////////////////////////////
jQuery.fn.delay = function(time, func) {
    this.each(function() {
        setTimeout(func, time);
    });

    return this;
};

// set up gotham for sifr text replacement
	gotham = { src: '../../swf/gotham.swf', wmode: 'transparent', color: "#ffffff" };
	sIFR.activate(gotham);

/*IE 6 hover plagin*/
eval(function(p, a, c, k, e, r) { e = function(c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) r[e(c)] = k[c] || e(c); k = [function(e) { return r[e] } ]; e = function() { return '\\w+' }; c = 1 }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p } ('9 u=k(){9 g=/^([^#.>`]*)(#|\\.|\\>|\\`)(.+)$/;k u(a,b){9 c=a.J(/\\s*\\,\\s*/);9 d=[];n(9 i=0;i<c.l;i++){d=d.v(o(c[i],b))};6 d};k o(a,b,c){a=a.z(" ","`");9 d=a.r(g);9 e,5,m,7,i,h;9 f=[];4(d==8){d=[a,a]};4(d[1]==""){d[1]="*"};4(c==8){c="`"};4(b==8){b=E};K(d[2]){w"#":7=d[3].r(g);4(7==8){7=[8,d[3]]};e=E.L(7[1]);4(e==8||(d[1]!="*"&&!x(e,d[1]))){6 f};4(7.l==2){f.A(e);6 f};6 o(7[3],e,7[2]);w".":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};7=d[3].r(g);4(7!=8){4(e.j==8||e.j.r("(\\\\s|^)"+7[1]+"(\\\\s|$)")==8){q};m=o(7[3],e,7[2]);f=f.v(m)}y 4(e.j!=8&&e.j.r("(\\\\s|^)"+d[3]+"(\\\\s|$)")!=8){f.A(e)}};6 f;w">":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};m=o(d[3],e,">");f=f.v(m)};6 f;w"`":5=p(b,d[1]);n(i=0,h=5.l;i<h;i++){e=5[i];m=o(d[3],e,"`");f=f.v(m)};6 f;M:4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};f.A(e)};6 f}};k p(a,b){4(b=="*"&&a.F!=8){6 a.F};6 a.p(b)};k x(a,b){4(b=="*"){6 N};6 a.O.G().z("P:","")==b.G()};6 u}();k Q(a,b){9 c=u(a);n(9 i=0;i<c.l;i++){c[i].R=k(){4(t.j.H(b)==-1){t.j+=" "+b}};c[i].S=k(){4(t.j.H(b)!=-1){t.j=t.j.z(b,"")}}}}4(D.I&&!D.T){D.I("U",V)}', 58, 58, '||||if|listNodes|return|subselector|null|var||||||||limit||className|function|length|listSubNodes|for|doParse|getElementsByTagName|continue|match||this|parseSelector|concat|case|matchNodeNames|else|replace|push|childNodes|nodeType|window|document|all|toLowerCase|indexOf|attachEvent|split|switch|getElementById|default|true|nodeName|html|hoverForIE6|onmouseover|onmouseout|opera|onload|ieHover'.split('|'), 0, {}))
/*parametrs [selector, hover_class]*/
function ieHover() {
    hoverForIE6("#nav li, .select, .picture-gallery li", "hover");
}

///////////////////////////////////////////////////////////////////////////////////////////
$j(document).ready(function() {
    var popup = new Popup()
    var search = new Search()
    var cal = new Cal()
    var collection = new Collection()
    //var scroller = new Scroller()

    //pathname = location.pathname.substring(0, location.pathname.indexOf("/pid/"));

    //querystring = urllocation[1].split('/');
    //uid = querystring[1];
    //    pid = gup("pid", location.pathname);
    //    ItemId = gup("ItemId", location.pathname);
    //    sidebar = gup("sidebar", location.pathname);
    //    daterange = gup("daterange", location.pathname);
    //    coid = gup("coid", location.pathname);
    //    dept = gup("dept", location.pathname);


    var urllocation = location.search;
    var pid = $j.query.get('pid');
    var ItemId = $j.query.get('ItemId');
    var sidebar = $j.query.get('sidebar');
    var mid = $j.query.get('mid');
    var userid = $j.query.get('userid');
    
    var sliderpos = Number($j.query.get('sliderpos'))
    if ($j.query.get('sliderpos').toString() == "") {
        sliderpos = 2;
    }

    //for collection object deep link
    var coid = $j.query.get('coid');
    var dept = $j.query.get('dept');

    var scroller = new Scroller(sliderpos)

    if (pid != "") {
        if (coid != "") {
            CMA.Web.CMAHelperService.GetItemData(pid, "",
            function(result) {
                if (result != "") {

                    var array = result.toString().split('|');
                    var itemIdArray = array[1].toString().split(',');
                    var itemPathArray = array[0].toString().split(',');
                    var popupUrl = "";

                    popupUrl = "http://" + document.location.host + itemPathArray[0] + "/coid/" + coid;

                    popup.fetchPage(popupUrl)

                    return false;
                }
            }
            , ServiceError, ServiceTimeout);
        }
        else {
            CMA.Web.CMAHelperService.GetItemData(pid, document.location.pathname,
            function(result) {
                if (result != "") {

                    var array = result.toString().split('|');
                    var itemIdArray = array[1].toString().split(',');
                    var itemPathArray = array[0].toString().split(',');
                    var profileredirect = array[2];
                    var popupUrl = "";


                    if (pid != "") {
                        popupUrl = "http://" + document.location.host + itemPathArray[0];
                    }

                    if (itemIdArray[0] != "") {
                        popupUrl = popupUrl + "/upageid/" + itemIdArray[0];
                    }

                    if (ItemId != "") {
                        popupUrl = popupUrl + "/ItemId/" + ItemId;
                    }

                    if (sidebar != "") {
                        popupUrl = popupUrl + "/sidebar/" + unescape(sidebar);
                    }

                    if (popupUrl != "") {

                        if (profileredirect == "1") {
                            popup.fetchIframe(popupUrl)
                        }
                        else if (profileredirect == "2") { //Unsubscribe redirect
                            popupUrl = popupUrl + "/mid/" + mid + "/userid/" + userid;
                            popup.fetchIframe(popupUrl);
                        }
                        else {
                            popup.fetchPage(popupUrl)
                        }
                        
                        return false;
                    }
                }
            }
            , ServiceError, ServiceTimeout);
        }
    }

    //http://localhost/visit/Plan%20Your%20Visit/Getting%20here.aspx?upage="visit/Plan%20Your%20Visit.aspx"

    $j("#main li").hide().each(function(i) {
        var card = $j(this)
        var dt = 0
        if (card.closest('.pagin').size() > 0) {
            card.show()
            return
        } else if ($j(this).closest('.picture-gallery').size() > 0) {
            dt = 20 * i
        } else {
            dt = 100 * i
        }
        card.delay(dt, function() {
            card.animate({ opacity: 'toggle' }, 'slow')
        })
    })

    //    $j("#main li").hide().each(function(i) {
    //        if ($j(this).closest('.pagin').size() > 0) {
    //            $j(this).show()
    //        } else {
    //            var card = $j(this)
    //            card.delay(100 * i, function() {
    //                card.animate({ opacity: 'toggle' }, 'slow')
    //            })
    //        }
    //    })

    // this is unneesary for deployment, but required for testing the standalone pages in the popups directory
    //    sIFR.replace(gotham, {
    //        selector: '.popup h2 span',
    //        css: '.sIFR-root { color:#fff; }'
    //    });

    // If this is a calendar page, use sifr for the date digits and Closed messages 
    sIFR.replace(gotham, {
        selector: '.calendar .date',
        css: '.sIFR-root { color:#ffffff; font-size:120px;}'
    });
    
    //    sIFR.replace(gotham, {
    //        selector: '.close-note span',
    //        css: '.sIFR-root { color:#fff; font-size:41px; line-height:50px;} a{color:#72c5d9; text-decoration:none;} a:hover{color:#72c5d9; text-decoration:underline;}',
    //        linkColor: ""
    //    });
    //    sIFR.replace(gotham, {
    //        selector: '.close-note p',
    //        css: '.sIFR-root { color:#fff; font-size:41px; line-height:50px;} a{color:#72c5d9; text-decoration:none;} a:hover{color:#72c5d9; text-decoration:underline;}',
    //        linkColor: ""
    //    });

})
// This capture if the Webservice call is on Error.
function ServiceError(ex) {
    //var control = document.getElementById("lblMessage");
    //$j(control).value = ex._message;
    alert("Error calling service method:\r\n" + ex._message);
}

// This capture if the Webservice call TimeOut.
function ServiceTimeout(message) {
    alert("Service call timed out");
}

function gup(name, url) {

    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
//    var regexS = "[\\?&]" + name + "=([^&#]*)";
//    var regex = new RegExp(regexS);
//    var results = regex.exec(url);
//    if (results == null)
//        return "";
//    else
//            return results[1];
//    
    var query = null;

    if (url.indexOf(name + "/") != -1) {
        query = url.substring(url.indexOf(name + "/")).split('/');
    }
    if (query != null) {
        return query[1];
    } else {
        return "";
    }
}


function hideLoginTags(name) {
    $j('#lblFullName').text(name + ", ");
}


function BuildIFrame() {
    var oIFrame = document.createElement("IFRAME");
    oIFrame.width = "745px";
    oIFrame.height = "100%";
    oIFrame.frameBorder = "0";
    return oIFrame;
}

function IFrameresize(id, height) {
    var oIFrame = $get(id);
    oIFrame.style.height = height + "px";
}

function RemoveHashInUrl(rurl) {
    var len = rurl.length;
    if (rurl.charAt(len - 1) == "#") {
        rurl = rurl.substring(0, len - 1)
    }

    return rurl;
}
