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;
}



function handleSearchBox() {
    if ($('div#searchBox input').val() != '') {
        $('div#searchBox label').css('display', 'none');
    }
    $('div#searchBox input').focus(function () {
        if ($(this).val() == '') {
            $('div#searchBox label').animate({
                opacity: 0.25
            }, 250);
        }
    });

    $('div#searchBox input').blur(function () {
        if ($(this).val() == '') {
            $('div#searchBox label').css('display', 'block');
            $('div#searchBox label').animate({
                opacity: 1
            }, 250);

        }
    });
    $('div#searchBox input').keydown(function () {

        $('div#searchBox label').css('display', 'none');

    });

    $('div#searchBox input').change(function () {
        if ($(this).val() == '') {
            $('div#searchBox label').css('opacity', 1);

        }
    });

}


function slideSwitch() {
    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 () {
    if ($('#slideshow').length > 0) {
        setInterval("slideSwitch()", 5500);
    }
});

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) $(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);

                }
            });


        });
}
function handleSelects() {
        //handle select
        $('select.selectBox').parent().prepend('<div class="selectBoxMask" />').prepend('<label />');
        $('select.selectBox').parent().children('label').attr('for', $('select.selectBox').attr('id')).addClass('label').attr('style', '');
        $('select.selectBox').css('opacity', 0);
        $('select.selectBox').change(function () {
            var val = $(this).find('option:selected').text();
            $('select.selectBox').parent().children('label').html(val);
        });


        // anulate hidden status from comment label
        $('inputBox.comments label').attr('style', '');

}
function handleContactPage() {
        // hide confirmation span if it has no content
        if ($('span.confirmation').is(":empty")) $('span.confirmation').css('display', 'none');
        $('span.req').each(function (index, domEle) {
            if ($(domEle).css('visibility') == 'hidden') $(domEle).css('display', 'none');

        })


        $('.inputBox.select label').html($('.inputBox.select select option:first').html());

    
}

/* Search Functions */

function submitQuickSearch() {
    var keyWords = document.getElementById('inpQuickSearch').value;
    document.location.href = document.location.href.split('?')[0] + '?tabid=5&keyword=' + keyWords;
}

function submitCategory() {
    var url = document.getElementById('selCategory').value;
    document.location.href = document.location.href.substr(0, document.location.href.indexOf('DesktopDefault.aspx')) + url;
}

function entsub(e) {
    var evt = window.event ? e.keyCode : e.which;
    var keyPressed = evt;

    if (keyPressed == 13) {
        submitQuickSearch();
        return false;
    } else {
        return true;
    }
}


//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');
        }
    })

	if (getUrlVarsFrom(window.location.href, true)['tabid'] == 5) {
		$("h4.categoryMenu > a").each(function (index, domEle) {
			if (getUrlVarsFrom(window.location.href, 0)['categoryid'] == getUrlVarsFrom($(domEle).attr('href'), 0)['categoryid']) {
				$(domEle).addClass('active');
			}
		})
	}
}

function fixCatalogueTitles() {
   
        $("h1").each(function (index, domEle) {
			if ($('span', domEle).text().indexOf('(') != -1) {
				var title = $('span', domEle).text().split('(');
				var date = '<h6>' + title[1].replace(')', '') + '</h6>';
				$(domEle).html(title[0]);
				$(domEle).after(date);
			}
			
        })
    
}

function fixArtistList(){
	
	$('div.col2 a').each(function (index, domEle) {
		
		if ($(domEle).attr('href') === undefined) {
			$(domEle).replaceWith($(domEle).html());
		}
	})
	
}

function loadArtistList() {

		var address = 'DesktopDefault.aspx?tabid=44';
		$('div.col2').addClass('loading');
		$("<div>").load(address + ' div#artistList', function () {
			$('div.col2').append($(this).find('div#artistList').html());
			$('div.col2').removeClass('loading');
			fixArtistList();
		});
	

}

// map functions (contact page)
    function load() {
  if (GBrowserIsCompatible()) {
    var map1 = new GMap2(document.getElementById("map1"));
	var point = new GLatLng(40.421207,-3.68763);
    map1.setCenter(point, 17);
	var marker = new GMarker(point);
    map1.addOverlay(marker);
	map1.addControl(new GSmallMapControl());
	
    /*var map2 = new GMap2(document.getElementById("map2"));
	var point = new GLatLng(50.841164,4.353547);
    map2.setCenter(point, 17);
    var marker = new GMarker(point);
    map2.addOverlay(marker);
	map2.addControl(new GSmallMapControl());*/
	
    
  }
}
// home page functions
function fixHighlightArtistName() {

			if ($("div.col2 h1 span").text().indexOf('(') != -1) {
				var title = $("div.col2 h1 span").text().split('(');
				var date = '<p>' + title[1].replace(')', '') + '</p>';
				$("div.col2 h1").html(title[0]);
				$("div.col2 h1").after(date);
			}
       
}
function resizeHomeExpoImage(domEle) {
	var target = 'div.col2 a img';
	if($(domEle).find('div.contentWrapper div.itemCol2 a img').length > 0){
		$(domEle).find('div.contentWrapper div.itemCol2 a img').attr('src', 
			$(domEle).find('div.contentWrapper div.itemCol2 a img').attr('src').replace(getUrlVarsFrom($(domEle).find('div.contentWrapper div.itemCol2 a img').attr('src'))['cell'], getUrlVarsFrom($('div.col2 a img').attr('src'))['cell']))
			
			
	}
}


function fixExhibitionDate() {
	var target = 'div.col1 h3';
  var date = $(target).text();
  var replace = new Array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "Lundi", "mardi", "mercredi", "jeudi", "Vendredi", "Samedi", "dimanche");
  for (var i=0; i<replace.length; i++) {
	  var regex = new RegExp( '(' + replace[i] + ',' + ')', 'gi' );

     date = date.replace(regex, '');
  }

$(target).html(date);
	
}

//Load first exhibition on home
function loadFirstExhibition() {
	
	var address = 'Linares-Gallery-Events-Linares-Exhibition-List-DesktopDefault.aspx?tabid=46';
    $("<div>").load(address + ' div.contentWrapper', function () {
		
        $('div.col1 h2').html($(this).find('div.contentWrapper h3:first-child').html());
		$('div.col1 h1').html($(this).find('div.contentWrapper h1:first-child').html());
		$('div.col1 h3').html($(this).find('div.contentWrapper span.dates').html());
		fixExhibitionDate();
		$('div.col1 h4.openings').html($(this).find('div.contentWrapper span.info.openings').html());
		fixHighlightArtistName();
		resizeHomeExpoImage(this);
		$('div.col1 div.highlightImage').html($(this).find('div.contentWrapper div.itemCol2').html());
		
	    //$('a#readMore').attr('href', $(this).find('div.title:first-child a').attr('href'));
    });	
    	
	
	
}



/*
 * jQuery Tooltip
 */
(function(f){function p(a,b,c){var h=c.relative?a.position().top:a.offset().top,d=c.relative?a.position().left:a.offset().left,i=c.position[0];h-=b.outerHeight()-c.offset[0];d+=a.outerWidth()+c.offset[1];if(/iPad/i.test(navigator.userAgent))h-=f(window).scrollTop();var j=b.outerHeight()+a.outerHeight();if(i=="center")h+=j/2;if(i=="bottom")h+=j;i=c.position[1];a=b.outerWidth()+a.outerWidth();if(i=="center")d-=a/2;if(i=="left")d-=a;return{top:h,left:d}}function u(a,b){var c=this,h=a.add(c),d,i=0,j=
0,m=a.attr("title"),q=a.attr("data-tooltip"),r=o[b.effect],l,s=a.is(":input"),v=s&&a.is(":checkbox, :radio, select, :button, :submit"),t=a.attr("type"),k=b.events[t]||b.events[s?v?"widget":"input":"def"];if(!r)throw'Nonexistent effect "'+b.effect+'"';k=k.split(/,\s*/);if(k.length!=2)throw"Tooltip: bad events configuration for "+t;a.bind(k[0],function(e){clearTimeout(i);if(b.predelay)j=setTimeout(function(){c.show(e)},b.predelay);else c.show(e)}).bind(k[1],function(e){clearTimeout(j);if(b.delay)i=
setTimeout(function(){c.hide(e)},b.delay);else c.hide(e)});if(m&&b.cancelDefault){a.removeAttr("title");a.data("title",m)}f.extend(c,{show:function(e){if(!d){if(q)d=f(q);else if(b.tip)d=f(b.tip).eq(0);else if(m)d=f(b.layout).addClass(b.tipClass).appendTo(document.body).hide().append(m);else{d=a.next();d.length||(d=a.parent().next())}if(!d.length)throw"Cannot find tooltip for "+a;}if(c.isShown())return c;d.stop(true,true);var g=p(a,d,b);b.tip&&d.html(a.data("title"));e=e||f.Event();e.type="onBeforeShow";
h.trigger(e,[g]);if(e.isDefaultPrevented())return c;g=p(a,d,b);d.css({position:"absolute",top:g.top,left:g.left});l=true;r[0].call(c,function(){e.type="onShow";l="full";h.trigger(e)});g=b.events.tooltip.split(/,\s*/);if(!d.data("__set")){d.bind(g[0],function(){clearTimeout(i);clearTimeout(j)});g[1]&&!a.is("input:not(:checkbox, :radio), textarea")&&d.bind(g[1],function(n){n.relatedTarget!=a[0]&&a.trigger(k[1].split(" ")[0])});d.data("__set",true)}return c},hide:function(e){if(!d||!c.isShown())return c;
e=e||f.Event();e.type="onBeforeHide";h.trigger(e);if(!e.isDefaultPrevented()){l=false;o[b.effect][1].call(c,function(){e.type="onHide";h.trigger(e)});return c}},isShown:function(e){return e?l=="full":l},getConf:function(){return b},getTip:function(){return d},getTrigger:function(){return a}});f.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(e,g){f.isFunction(b[g])&&f(c).bind(g,b[g]);c[g]=function(n){n&&f(c).bind(g,n);return c}})}f.tools=f.tools||{version:"1.2.5"};f.tools.tooltip=
{conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,position:["top","center"],offset:[0,0],relative:false,cancelDefault:true,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,b,c){o[a]=[b,c]}};var o={toggle:[function(a){var b=this.getConf(),c=this.getTip();b=b.opacity;b<1&&c.css({opacity:b});c.show();a.call()},function(a){this.getTip().hide();
a.call()}],fade:[function(a){var b=this.getConf();this.getTip().fadeTo(b.fadeInSpeed,b.opacity,a)},function(a){this.getTip().fadeOut(this.getConf().fadeOutSpeed,a)}]};f.fn.tooltip=function(a){var b=this.data("tooltip");if(b)return b;a=f.extend(true,{},f.tools.tooltip.conf,a);if(typeof a.position=="string")a.position=a.position.split(/,?\s/);this.each(function(){b=new u(f(this),a);f(this).data("tooltip",b)});return a.api?b:this}})(jQuery);

function setIpad() {
	
	if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
		$('.fullScreen').attr('onclick', '').attr('onmouseout', '').attr('onmouseover', '').attr('href', '').click(function(){
			
			
			window.location = 'DesktopDefault.aspx?tabid=23&imgurl=' + $('.mainImage a img').attr('src').split('?')[0];
			return false;
			
			});
	} 
	
}

$(document).ready(function () {
	handleLanguageMenu();
    handleSearchBox();
    highlightCurrent();
	handleInputs();
	$("ul.tools li a").tooltip();
	switch(getUrlVarsFrom(window.location.href, true)['tabid']) {
		case '5':
			fixCatalogueTitles();
			loadArtistList();
			break;
		case '45':
			loadArtistList();
			break;
		case '50':
			handleSelects();
			handleContactPage();
			load();
			break;
		case '1':
			loadFirstExhibition();
			break;
		case undefined:
			loadFirstExhibition();
			break;
		case '6':
			setIpad();
			break;
		}
		
	
})


