
$(document).ready(function () {
    
    handleInputs();
	
	// main menu hack for ipad
	fixMainMenu();
	
    switch (getUrlVarsFrom(document.location.href, true)['tabid']) {
    case undefined:
		initObjectHighlights();
		break;
	case '1':
		initObjectHighlights();
		break;
    case '6':
        setObjectDetail();
        break;
	case '20':
		setupCatalogues();
		break;
	case '21':
		setupCatalogues();
		break;
    case '22':
        loadMap();
        break;
    case '24':
        initMonumental();
        break;
    case '44':
        initArtistList();
        break;
    case '45':
        initArtistDescription();
        break;
    case '46':
        initEvents();
        break;
	case '47':
        initExhibitionDetails();
        break;
	
    case '148':
        adjustPostImage();
        break;
    case '149':
        adjustPostImage();
        break;
    }
	
	
	
	$('a.tooltip').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " - ",
        fade: 250
    });

	initFooterArtistList();

});


function initObjectHighlights() {
	
	if ($('.system-message').html() != null) {
		
		$('.section.sign-up .form').html($('.system-message').html());
		
	}
	
	if ($('.error').html() != null) {
		$('.section.sign-up .form').prepend('<div class="error-message">' + $('.error').html() + "</div>" );
		
	}
	
}

function initFooterArtistList(){
	
	$('td#BottomPane ul.artists > li > a').each(function (index, domEle) {
		
		$(domEle).next('div.artist-list')
		.css({
			'clip': 'auto',
			'position' : 'relative',
			'display' : 'none'
		});
		
		
        $(domEle).click(function () {
            
			$(domEle).next('div.artist-list')
			.slideToggle();

		return false;

        })
		
		
    })
	
}

function fixMainMenu(){
	
	$('ul.mainMenu > li').hover(
	function(){
		
		$(this).children('ul').css('display', 'block');
		
	},
	function(){
		
		$(this).children('ul').css('display', 'none');
		
	})
	
	$('ul.mainMenu > li > ul').css('display', 'none');
	
}

function getUrlVarsFrom(url, preventUnwantedVars) {
    var vars = [],
        hash;
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        if (preventUnwantedVars == 1) {
            if (hash[0] != 'lg' && hash[0] != 'objectid' && hash[0] != 'tabindex' && hash[0] != 'page' && hash[0] != 'keyword' && hash[0] != 'mediaid') {
                if (hash[0] == 'categoryid' && hash[1] == 0) {} else {
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
            }
        } else {
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}




//MENU FUNCTIONS

function nrKeys(a) {
    var i = 0;
    for (key in a) {
        i++;
    }
    return i;
}

function compareAssociativeArrays(a, b) {
    if (a == b) {
        return true;
    }
    if (nrKeys(a) != nrKeys(b)) {
        return false;
    }
    for (key in a) {
        if (a[key] != b[key]) {
            return false;
        }
    }
    return true;
}




function handleLanguageMenu() {

    $("ul.langMenu > li > a").each(function (index, domEle) {
        var currentLg = getUrlVarsFrom(window.location.href, false)['lg'],
            newLg = getUrlVarsFrom($(domEle).attr('href'), false)['lg'];
        if (currentLg != newLg) {

            if (currentLg === undefined) {
                if (getUrlVarsFrom(window.location.href, false).length > 1) {
                    $(domEle).bind('click', function () {
                        window.location = window.location.href + '&lg=' + newLg;
                        return false;
                    })
                }
            } else {
                $(domEle).bind('click', function () {
                    window.location = window.location.href.replace('lg=' + currentLg, 'lg=' + newLg);
                    return false;
                })
            }

        } else {
            $(domEle).bind('click', function () {
                window.location = window.location.href;
                return false;
            })

        }

    })

}


function highlightCurrent() {
    //check for matches on menu
    $("ul.mainMenu a").each(function (index, domEle) {
        if (compareAssociativeArrays(getUrlVarsFrom(window.location.href, 1), getUrlVarsFrom($(domEle).attr('href'), 1))) {
            $(domEle).addClass('active');
        }
    })


}

// Placeholder text on input

function handleInputs() {


    //handle text input
    $('div.inputBox').each(function (index, domEle) {

        var target;
        if ($(domEle).children('input').length > 0) {
            target = 'input';
        } else {
            target = 'textarea'
        }

        if ($('label', domEle).length == 0 || $('span.label').length > 0) {
            $(domEle).append('<label />');
            $('label', domEle).attr('for', $(target, domEle).attr('id'));
            $('label', domEle).html($('.label', domEle).html().replace(':', ''));
            $('span.label', domEle).remove();
        }



        if ($(target, domEle).val() != '') {
            $('label', domEle).css('display', 'none');
        }
        $(target, domEle).focus(function () {
            if ($(this).val() == '') {
                $('label', domEle).animate({
                    opacity: 0.25
                }, 250);
            }
        });

        $(target, domEle).blur(function () {
            if ($(this).val() == '') {
                $('label', domEle).css('display', 'block');
                $('label', domEle).animate({
                    opacity: 1
                }, 250);

            }
        });
        $(target, domEle).keydown(function () {

            $('label', domEle).css('display', 'none');

        });

        $(target, domEle).change(function () {
            if ($(this).val() == '') {
                $('label', domEle).css('opacity', 1);

            }
        });


    });
}




// Set minimum page size, so that the footer gets on the bottom
var contentHeight;

function setContentHeight() {
    var headerHeight, footerHeight = 239;
    $('.top').length > 0 ? headerHeight = 85 : headerHeight = 0;
    if ($(window).height() - headerHeight - footerHeight > contentHeight) {$('.contentPane').css('height', $(window).height() - headerHeight - footerHeight + 'px')} else {  $('.contentPane').css('height', '')};
}

$(window).load(function () {
    contentHeight = $('.content').height();
    setContentHeight();
	$('div.bottom')
	.css({
		'clip': 'auto',
		'position' : 'relative',
		'display' : 'none'
	})
	.fadeIn();
    $(window).resize(function () {
        setContentHeight();
    });
})


// map functions (contact page)

function loadMap() {
    if (GBrowserIsCompatible()) {
        var map1 = new GMap2(document.getElementById("map1"));
        var point = new GLatLng(51.507655, -0.139274);
        map1.setCenter(point, 15);
        var marker = new GMarker(point);
        map1.addOverlay(marker);
        map1.addControl(new GSmallMapControl());

        var map2 = new GMap2(document.getElementById("map2"));
        var point = new GLatLng(51.511056, -0.144897);
        map2.setCenter(point, 15);
        var marker = new GMarker(point);
        map2.addOverlay(marker);
        map2.addControl(new GSmallMapControl());


    }
}


//slideshow
margins = 59 + 58;
var	intervalHandle = null;
function createHomePageImages(imageUrl, imgWidth, imgHeight, container) {

    var partPercentage = 0.1,
        partSize = 350,
        //size of the slices
        imgSize = partSize * (100 / (partPercentage * 100)),
        // set default values for the screen size, those values will be updated on document ready
        zoom = 0,
        zoomRef = 0,
        difference, scrollLeft = 0,
        scrollTop = 0;

    function applyImgSizeToContainer() {
        $(container + ' .imageContainer').css('width', imgWidth + 'px').css('height', imgHeight + 'px');
    }

    function drawImage() {

        applyImgSizeToContainer();


        if ($(container + ' .layer.zoom').length == 0) $(container + ' .imageContainer').append("<div class='layer zoom'></div>");

        //clear container
        $(container + ' .imageContainer .layer').html('');

        //loop through image slices
        for (y = 0; y <= Math.ceil(imgHeight / partSize); y += 1) {
            var top = y * partPercentage;
            for (x = 0; x <= Math.ceil(imgWidth / partSize); x += 1) {
                var left = x * partPercentage;


                //check if slice is in the viewable area, and if so, append it
                if (((x + 1) * partSize >= scrollLeft && (x + 1) * partSize <= scrollLeft + screenWidth || x * partSize >= scrollLeft && x * partSize <= scrollLeft + screenWidth) && ((y + 1) * partSize >= scrollTop && (y + 1) * partSize <= scrollTop + screenHeight || y * partSize >= scrollTop && y * partSize <= scrollTop + screenHeight))
                //append image slices
                $(container + " .zoom").append("<img src='" + imageUrl + "?rgn=" + left + "," + top + "," + partPercentage + "," + partPercentage + "&wid=" + partSize + "&effect=bg,c9c9cb&qlt=97&cvt=jpeg' style='position:absolute; left:" + x * partSize + "px; top:" + y * partSize + "px' />");


            }
        }






    }

    function applyZoom() {

        if (screenWidth / screenHeight > imgWidth / imgHeight) {
            difference = 0;
            //scrollLeft=((($(window).height() / imgHeight) *  imgWidth) - screenWidth)/4;
            //$(container + ' .imageContainer').css('left', -scrollLeft);
			
			scrollLeft = (screenWidth - ((screenHeight / imgHeight) * imgWidth))/2;
            $(container + ' .imageContainer').css('left', scrollLeft);
			scrollTop = 0;
            $(container + ' .imageContainer').css('top', scrollTop);
			
        } else {
			
			
             scrollLeft = 0;
            $(container + ' .imageContainer').css('left', scrollLeft);
			scrollTop = (screenHeight - (($(window).width() / imgWidth) *  imgHeight))/2;
            $(container + ' .imageContainer').css('top', scrollTop); 
			
            difference = (screenWidth - ((screenHeight / imgHeight) * imgWidth));
        }
        // real width is ($(window).height() / imgHeight) *  imgWidth
        // start with image at fullscreen
        partPercentage = 1 / ((screenHeight + (difference * (imgHeight / imgWidth))) / partSize);


        var scrollLeft = parseFloat($(container + ' .imageContainer').css('left').replace('px', '')),
            scrollTop = parseFloat($(container + ' .imageContainer').css('top').replace('px', ''));

        //alert(screenWidth -(screenHeight / imgHeight) *  imgWidth);
        imgSize = partSize * (100 / (partPercentage * partSize));

    }


    function init() {
        //apply zoom
        applyZoom();
        drawImage();

    }


    $('.screen').height($(window).height() - margins);
    $('.screen').width($(window).width());
    //get screen size
    screenWidth = $('.screen').width();
    screenHeight = $('.screen').height();
    init();



}


function setupSlides() {
    var
    contempW = 4626,
        contempH = 2706,
        sc19W = 6144,
        sc19H = 3594;

    $('#slideshow').fadeOut(1);
    $('.contentPane').css({
        'background': 'url(media/sladmoremedia/img/loader.gif) 50% 50% no-repeat',
        'height': $(window).height() - 200,
        'width': '100%'
    });
	
	
	
	createHomePageImages("http://asimg.artsolution.net/tsmedia/SladmoreSlaphoto/jermyn.jpg", sc19W, sc19H, '.slide1');
    createHomePageImages("http://asimg.artsolution.net/tsmedia/SladmoreSlaphoto/bruton.jpg", contempW, contempH, '.slide2');
    

    var loaded = 0;
    var images = [];
    $('div.zoom img').each(function (index, domEle) {
        images.push($(domEle).attr('src'));



        $(domEle).load(function () {
            loaded += 1;

            if (loaded == images.length) {

$('.contentPane').css({
        'background': 'transparent'
        
    });
	
                $('#slideshow').fadeIn('slow', function () {
                    if (jQuery.browser.msie) this.style.removeAttribute("filter");
					if ($('#slideshow').length > 0) {
						if (intervalHandle) clearInterval(intervalHandle);
						intervalHandle = setInterval("slideSwitch()", 6000);
					}

                });


            }
        });
    });

}

function setupSlideShow() {

    $('#slideshow').prependTo('body');





    setupSlides();
	

    function resizeSlideShow() {
        setupSlides();
    }
  


	var winWidth = $(window).width(),
	winHeight = $(window).height(),
	resizeTimeout = false;
	
	$(window).resize(function(){
	
	onResize = function() {
	//The method which sets the LEFT css property which triggers 
	//window.resize again and it was a infinite loop in Internet Explorer
	resizeSlideShow();
	}
	
	//New height and width
	var winNewWidth = $(window).width(),
	winNewHeight = $(window).height();
	
	// compare the new height and width with old one
	if(winWidth!=winNewWidth || winHeight!=winNewHeight)
	{
	if (resizeTimeout != false) window.clearTimeout(resizeTimeout);
	resizeTimeout = window.setTimeout(onResize, 1000);
	}
	//Update the width and height
	winWidth = winNewWidth;
	winHeight = winNewHeight;
	});




}


function slideSwitch() {
    var $active = $('#slideshow > div.slide.active');

    if ($active.length == 0) $active = $('#slideshow > div.slide:last');

    // use this to pull the images in the order they appear in the markup
    var $next = $active.next().length ? $active.next() : $('#slideshow > div.slide:first');

    // uncomment the 3 lines below to pull the images in random order
    // var $sibs  = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next  = $( $sibs[ rndNum ] );
    $active.addClass('last-active');

    $next.css({
        opacity: 0.0
    }).addClass('active').animate({
        opacity: 1.0
    }, 1500, function () {
        if (jQuery.browser.msie) this.style.removeAttribute("filter");

        $active.removeClass('active last-active');
    });
}

function putTitlesOnTooltips() {
	
	$('.imageArea').each(function(index, domEle) {
		
			if ($(domEle).siblings('.title').length > 0) {
				
				$('a',domEle).addClass('tooltip').attr('title', $(domEle).siblings('.title').text());	
				
			}
		
		})
	
}

var biography = 0;
function initArtistDescription() {
var categoryid;
switch (getUrlVarsFrom(document.location.href, true)['artistcategoryid']) {
	case '21':
		categoryid=8976;
		break;
	case '22':
		categoryid=9017;
		break;
	case '23':
		categoryid=9016;
		break;
	case '24':
		categoryid=8977;
		$('span.artistnametitle').html($('span.artistnametitle').html().replace('Monumental', ''))
		break;
}

if (getUrlVarsFrom(document.location.href, true)['artistcategoryid']) 
$('.content.artistDetail a').each(function (index, domEle) {
		//Get artist Category, to show the right text on the object description
		if ($(domEle).parent().attr('id')!='artistListButton') 
		$(domEle).attr('href', $(domEle).attr('href') + '&categoryid=' + categoryid);
		
})


var site = new RegExp(/\[site:(.*?)\]/);
//alert($('.bioContent').html().match(site)[1]);

if ($('.bioContent').html().match(site)) {

$('ul.menu').append('<li><a href="' + RegExp.$1 + '" target="_blank">Artist website</a></li>');
$('li#artistListButton').html($('li#artistListButton').html() + '&nbsp; &#8226;');
//alert($('#artistListButton ').html());
$('.bioContent').html($('.bioContent').html().replace(site, ''));
}

	putTitlesOnTooltips();


    $('#biographyButton a').click(function () {

        
            $('.biography').slideToggle("slow", function(){ setContentHeight(); });
           
			
       
		
        return false;
    })

    

}


/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;
(function ($) {
    var helper = {},
        current, title, tID, IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
        track = false;
    $.tooltip = {
        blocked: false,
        defaults: {
            delay: 200,
            fade: false,
            showURL: true,
            extraClass: "",
            top: 15,
            left: 15,
            id: "tooltip"
        },
        block: function () {
            $.tooltip.blocked = !$.tooltip.blocked;
        }
    };
    $.fn.extend({
        tooltip: function (settings) {
            settings = $.extend({}, $.tooltip.defaults, settings);
            createHelper(settings);
            return this.each(function () {
                $.data(this, "tooltip", settings);
                this.tOpacity = helper.parent.css("opacity");
                this.tooltipText = this.title;
                $(this).removeAttr("title");
                this.alt = "";
            }).mouseover(save).mouseout(hide).click(hide);
        },
        fixPNG: IE ?
        function () {
            return this.each(function () {
                var image = $(this).css('backgroundImage');
                if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
                    image = RegExp.$1;
                    $(this).css({
                        'backgroundImage': 'none',
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
                    }).each(function () {
                        var position = $(this).css('position');
                        if (position != 'absolute' && position != 'relative') $(this).css('position', 'relative');
                    });
                }
            });
        } : function () {
            return this;
        },
        unfixPNG: IE ?
        function () {
            return this.each(function () {
                $(this).css({
                    'filter': '',
                    backgroundImage: ''
                });
            });
        } : function () {
            return this;
        },
        hideWhenEmpty: function () {
            return this.each(function () {
                $(this)[$(this).html() ? "show" : "hide"]();
            });
        },
        url: function () {
            return this.attr('href') || this.attr('src');
        }
    });

    function createHelper(settings) {
        if (helper.parent) return;
        helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();
        if ($.fn.bgiframe) helper.parent.bgiframe();
        helper.title = $('h3', helper.parent);
        helper.body = $('div.body', helper.parent);
        helper.url = $('div.url', helper.parent);
    }
    function settings(element) {
        return $.data(element, "tooltip");
    }
    function handle(event) {
        if (settings(this).delay) tID = setTimeout(show, settings(this).delay);
        else
        show();
        track = !! settings(this).track;
        $(document.body).bind('mousemove', update);
        update(event);
    }
    function save() {
        if ($.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler)) return;
        current = this;
        title = this.tooltipText;
        if (settings(this).bodyHandler) {
            helper.title.hide();
            var bodyContent = settings(this).bodyHandler.call(this);
            if (bodyContent.nodeType || bodyContent.jquery) {
                helper.body.empty().append(bodyContent)
            } else {
                helper.body.html(bodyContent);
            }
            helper.body.show();
        } else if (settings(this).showBody) {
            var parts = title.split(settings(this).showBody);
            helper.title.html(parts.shift()).show();
            helper.body.empty();
            for (var i = 0, part;
            (part = parts[i]); i++) {
                if (i > 0) helper.body.append("<br/>");
                helper.body.append(part);
            }
            helper.body.hideWhenEmpty();
        } else {
            helper.title.html(title).show();
            helper.body.hide();
        }
        if (settings(this).showURL && $(this).url()) helper.url.html($(this).url().replace('http://', '')).show();
        else
        helper.url.hide();
        helper.parent.addClass(settings(this).extraClass);
        if (settings(this).fixPNG) helper.parent.fixPNG();
        handle.apply(this, arguments);
    }
    function show() {
        tID = null;
        if ((!IE || !$.fn.bgiframe) && settings(current).fade) {
            if (helper.parent.is(":animated")) helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
            else
            helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
        } else {
            helper.parent.show();
        }
        update();
    }
    function update(event) {
        if ($.tooltip.blocked) return;
        if (event && event.target.tagName == "OPTION") {
            return;
        }
        if (!track && helper.parent.is(":visible")) {
            $(document.body).unbind('mousemove', update)
        }
        if (current == null) {
            $(document.body).unbind('mousemove', update);
            return;
        }
        helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
        var left = helper.parent[0].offsetLeft;
        var top = helper.parent[0].offsetTop;
        if (event) {
            left = event.pageX + settings(current).left;
            top = event.pageY + settings(current).top;
            var right = 'auto';
            if (settings(current).positionLeft) {
                right = $(window).width() - left;
                left = 'auto';
            }
            helper.parent.css({
                left: left,
                right: right,
                top: top
            });
        }
        var v = viewport(),
            h = helper.parent[0];
        if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
            left -= h.offsetWidth + 20 + settings(current).left;
            helper.parent.css({
                left: left + 'px'
            }).addClass("viewport-right");
        }
        if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
            top -= h.offsetHeight + 20 + settings(current).top;
            helper.parent.css({
                top: top + 'px'
            }).addClass("viewport-bottom");
        }
    }
    function viewport() {
        return {
            x: $(window).scrollLeft(),
            y: $(window).scrollTop(),
            cx: $(window).width(),
            cy: $(window).height()
        };
    }
    function hide(event) {
        if ($.tooltip.blocked) return;
        if (tID) clearTimeout(tID);
        current = null;
        var tsettings = settings(this);

        function complete() {
            helper.parent.removeClass(tsettings.extraClass).hide().css("opacity", "");
        }
        if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
            if (helper.parent.is(':animated')) helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
            else
            helper.parent.stop().fadeOut(tsettings.fade, complete);
        } else
        complete();
        if (settings(this).fixPNG) helper.parent.unfixPNG();
    }
})(jQuery);
//Resize image via changing the truespectra parameters

dimensions = new RegExp('cell=[0-9]*,[0-9]*');

var quality = new RegExp('qlt=[0-9]*');

//Load first image of artist hovered on the artist list


function initArtistList() {
	$('img.firstImage').each(function (index, domEle) {
		 
		 $(domEle).attr('src',$(domEle).attr('src').replace(dimensions, 'cell=311,600').replace(quality, 'qlt=70'));
		 
	})
	
	 
    $('td#ContentPane a.artistName').each(function (index, domEle) {
		
		//Get artist Category, to show the right text on the object description
		$(domEle).attr('href', $(domEle).attr('href') + '&artistcategoryid=' + getUrlVarsFrom(document.location.href, true)['artistcategoryid']);
		
        $(domEle).hover(function () {
            
			$('.sampleImage').html( $(domEle).parent().next().clone() );
			$('div.sampleImage img.firstImage').fadeIn('fast');

        }, function () {
           
			$('div.sampleImage img').fadeOut('fast',function(){
				
				$(this).remove();
			});
		


        })
		
		
    });
	
	

	
	


}


function setObjectDetail() {
    $('.col1 a img').load(function () {

        $('div.buttons').css('width', $('.col1 a img').width());
    })
	
	if ($('div.enquiry a').length > 0) {
		
		$('a.contact').attr('href', $('div.enquiry a').attr('href') + '?subject=' + $('h1 span.artist').text() + ': ' + $('span.title h2').text());
		$('div.enquiry a').remove();
	}
	
	
	
	$('#biographyButton a').click(function () {

        
            $('.biography').slideToggle("slow", function(){ setContentHeight(); });
           
			
       
		
        return false;
    })
}


function setupCatalogues() {
    $(".catalogueList > ul > li").each(function (index, domEle) {
        $('.longDescription', domEle).addClass('index' + $(domEle).index());
        $('.descriptionArea a', domEle).attr('rel','publicationLink').colorbox({
            width: "60%",
            inline: true,
            href: ".longDescription.index" + $(domEle).index()
        });
		$('.imageArea img', domEle).click(function(){$('.descriptionArea a', domEle).trigger('click');});
    })



}

function formatEventDate() {
	
	$('span.dates').each(function (index, domEle) {
		var date = $(domEle).text();
		var replace = new Array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");
		for (var i=0; i<replace.length; i++) {
			var regex = new RegExp( '(' + replace[i] + ',' + ')', 'gi' );
     		date = date.replace(regex, '');
		}

		$(domEle).html(date);
	})

}

function formatEventAddress() {



	$('span.address').each(function (index, domEle) {
		var firstLine=/(.*?)<br>/gi;
		
		$(domEle).html( $(domEle).html().match(firstLine)[0]);
	})
	
}

function initEvents() {
    $('ul.menu > li > a').each(function (index, domEle) {

        $(domEle).attr('href', $(domEle).attr('href') + '&isfair=' + getUrlVarsFrom(document.location.href, true)['isfair'])

    })
    if (getUrlVarsFrom(document.location.href, true)['isfair'] == 1) {
        $('div.titleBlock h1').html('Art Fairs ' + getUrlVarsFrom(document.location.href, true)['year'])
    } else {
        $('div.titleBlock h1').html('Exhibitions ' + getUrlVarsFrom(document.location.href, true)['year'])
    }
	
	for(var i = 0; i < $('div.list-wrapper div.wrapper').length; i++) {
		
		if ((i + 1) % 3 === 0) {
			
			var target= $($('div.list-wrapper div.wrapper')[i]);
			
			$('<br class="push" />').insertAfter(target);
		
		}
	}
	
	formatEventDate();
	formatEventAddress();
}

function adjustPostImage() {

    $('p.blogImageStyle img').each(function (index, domEle) {

        if ($(domEle).css('float') == 'right') $(domEle).css('margin-right', 10);
        if ($(domEle).css('float') == 'left') $(domEle).css('margin-left', 0);
    });
}

function monumentalSlideSwitch() {
    var $active = $('#slideshow IMG.active');

    if ($active.length == 0) $active = $('#slideshow IMG:last');

    // use this to pull the images in the order they appear in the markup
    var $next = $active.next().length ? $active.next() : $('#slideshow IMG:first');

    // uncomment the 3 lines below to pull the images in random order
    // var $sibs  = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next  = $( $sibs[ rndNum ] );

    $active.addClass('last-active');

    $next.css({
        opacity: 0.0
    }).addClass('active').animate({
        opacity: 1.0
    }, 1500, function () {
        $active.removeClass('active last-active');
    });
}




function initMonumental() {
	 if ($('#slideshow').length > 0) {
        setInterval("monumentalSlideSwitch()", 6000);
    }
	$(window).scroll(function () { 
		if ($(window).scrollTop() > $('td#TopPane').height()) {
				if ($(window).scrollTop() - $('td#TopPane').height() + $('div#slideshow').height() < $('div.col1').height())
					//$('#slideshow').css('top', $(window).scrollTop() - $('td#TopPane').height());
					$('#slideshow').animate({top:$(window).scrollTop() - $('td#TopPane').height()},{duration:500,queue:false});
			} else {
				
				$('#slideshow').stop().animate({top:0},{duration:500,queue:false});
				}

    });


}

function initExhibitionDetails() {
	
	putTitlesOnTooltips();
}

