$(document).ready(function () {

	// Call functions specific to each page
	switch (getUrlVarsFrom(document.location.href, true)['tabid']) {
	
	case '1':
        initHome();
        break;
    case undefined:
        initHome();
        break;
	case '45':
		activateToggle();
		break;
	case '5':
		inventory();
		break;
	case '6':
		objectDetail();
		break;
	case '46':
		exhibitionList();
		break;
	}
	
	highlightCurrent();
	adaptToScreenSize();
	
	$(window).load(function(){
		adaptToScreenSize();
		distributeMarginsEvenly('div.main-menu ul li', 'div.title-bar');
	})
	
	
	
	$(window).resize(function(){
	
		adaptToScreenSize();
		
	})
	
	putAdminButtonsOnFront()
	
	fixBrokenImages();
})
var dimensions = new RegExp('cell=[0-9]*,[0-9]*'),

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

function fixBrokenImages(){
	function randomFromTo(from, to){
		return Math.floor(Math.random() * (to - from + 1) + from);
	}

	


	$(window).bind('load', function() {
		$('img').each(function() {
			if((typeof this.naturalWidth != "undefined" &&
				this.naturalWidth == 0 ) 
				|| this.readyState == 'uninitialized' ) {
				$(this).attr('src', $(this).attr('src').replace(quality,'qlt=' + randomFromTo(70,100)));
			}
		}); 
	})
}
function putAdminButtonsOnFront() {
	
	if ($('a.buttons').length > 0) {
		
		$('a.buttons').each(function (index, domEle) {
			$(domEle).closest('table').css({'z-index': 20, 'position' : 'relative'});
		})

		
	}
	
}

function adaptToScreenSize(){
	distributeMarginsEvenly('div.main-menu ul li', 'div.title-bar');
	
	// If front-page, handle slideshow size
	if (getUrlVarsFrom(document.location.href, true)['tabid'] == 1 || getUrlVarsFrom(document.location.href, true)['tabid'] == undefined) {

		$('div.slideshow div.slide img').css({
			
			'width' : $('table.mainTable').width(),
			'height' : 'auto'
			
		})
		
		$('div.slideshow').css({
			
			'height' : $('div.slideshow div.slide img').height()
			
		})
		
	}
	
}

// actions specific to the inventory page
function inventory(){
	
	/*$(window).load(function(){
		distributeMarginsEvenly('div.content-wrapper ul.submenu li', 'div.title-bar');
	})*/
	
}

// Distribute margins evenly
function distributeMarginsEvenly(el, parent) {
	if ($(parent).length > 0 && $(el).length > 0) { 
		totalWidth = 0;
	
		$(el).each(function (index, domEle) {
	
			totalWidth += $(domEle).width();
	
		})
	
		margins = ($(parent).width() - totalWidth) / ($(el).length - 1);
	
		$(el).css('margin-right', Math.floor(margins));
		$(el).last().css('margin-right', '0');
	}
}

// Set top style to top title
function exhibitionList() {
	$('.title-bar').first().addClass('top');
}

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


}


// Biography button (Artist List)
function activateToggle() {

		$('.toggle-slide').each(function(index,domEle){
			$(domEle).click(function() { 
				$(domEle).parent('.toggle-section').children('.content-to-toggle').slideToggle();
				$(domEle).toggleClass('active');
				return false;
			
			})
			
		})
		
		
		
		
		if ($('.content-to-toggle').text().replace(/ /g, '').replace(/\t/g, '').replace(/\n/g, '') == '') {
			
			$('.toggle-slide').hide();
		}
	

}

// Object detail 

function objectDetail() {
	$('.content a[title]').qtip({
      position: {
      my: 'left center'
   }
   });
	
}

//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;
}



// Home Page

function slideSwitch() {
    var $active = $('.slideshow div.slide.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 div.slide:first');



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

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 2000, function() {
            $active.removeClass('active last-active');
			clearTimeout(timer);
			timer = setTimeout( "slideSwitch()", 6000 );
        });
		
		
	
}



function initHome() {
	
	$('td#ContentPane > div > img').each(function(index, domEle){
	
		$(domEle).wrap('<div class="slide" />');	
		
	})
	
	$('td#ContentPane > div > a').each(function(index, domEle){
	
		$(domEle).wrap('<div class="slide" />');	
		
	})
	
	$('td#ContentPane').prepend('<div class="slideshow" />');
	
	$('div.slide').each(function(index, domEle){
	
		$(domEle).appendTo('div.slideshow');
		
	})
	
	$('td#ContentPane > div').each(function(index, domEle){

		if ($('img', domEle).length == 0)	$(domEle).remove();
		
	})
	
	$('div.slideshow').wrap('<div class="content front-page" />');
	
	$('div.slide').eq(0).addClass('active');
	
	timer = setTimeout( "slideSwitch()", 6000 );
	
	
	
}

// Get variables from the url

function getUrlVarsFrom(url, preventUnwantedVars) {
	var vars = [],
		hash;
	var hashes = url.split('#')[0].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;
}
