var $j = jQuery.noConflict();

// Use jQuery via $j(...)
$j(document).ready(function () {
	handleLanguageMenu();
	initHeader();
	initHome();
	
	switch (getUrlVarsFrom(document.location.href, true)['tabid']) {
	case undefined:
		initSmallSlideshow();
		break;
	case '1':
		initSmallSlideshow();
		break;
	case '41':
		activateAccordion();
		break;
	case '123':
		handleGallery();
		showCurrentSubMenu();
		break;

	}
	
	// Fix ie7 z-index bug
	if (navigator.appVersion.indexOf("MSIE 7.")>-1) {
	
		$j('div#Header').css('z-index', 1000);
		$j('div#MainMenu').css('z-index', 1000);
		$j('div#MainMenu *').css('z-index', 1000);
		
		
	}
	
	
});

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;
}

var gallery;

function showCurrentSubMenu() {
    //check for matches on menualert('ok');
	
	var found = "0";
    $j("ul#photomenu > li > a").each(function (index, domEle) {
        if (compareAssociativeArrays(getUrlVarsFrom(window.location.href, 1), getUrlVarsFrom($j(domEle).attr('href'), 1))) {
            $j(domEle).parent().children('ul').css('display','block');
			$j(domEle).addClass('active');
			found = 1;
        }
    })
	
	//check for matches on submenu
	
    $j("ul#photomenu ul a").each(function (index, domEle) {
        if (compareAssociativeArrays(getUrlVarsFrom(window.location.href, 1), getUrlVarsFrom($j(domEle).attr('href'), 1))) {
            $j(domEle).parent().parent().css('display','block');
			$j(domEle).addClass('active');
			$j(domEle).parent().parent().parent().children('a').addClass('active');
			found = 1;
        }
    })
if (found=0) {
	alert (gallery);
}

}

function handleGallery(){
	var file = getUrlVarsFrom(window.location.href, true)['mode']!=undefined ? getUrlVarsFrom(window.location.href, true)['mode'] : '';
	var flashvars = {};
	gallery = getUrlVarsFrom(window.location.href, true)['gallery'];
                         flashvars.galleryURL = "media/brafa2011media/photogallery/flickr_"+ gallery +".xml";
                         var params = {}; 
                         params.allowfullscreen = false;
                         params.allowscriptaccess = "always";
                         params.bgcolor = "FFFFFF";
                         swfobject.embedSWF("media/brafa2011media/photogallery/simpleviewer"+ file +".swf", "flashContent", "800px", "600px", "9.0.124", false, flashvars, params);
}

function slideSwitch() {
    var $active = $j('#smallslideshow img.active');

    if ( $active.length == 0 ) $active = $j('#smallslideshow img:last');

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $j('#smallslideshow 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 initSmallSlideshow() {
    setInterval( "slideSwitch()", 5000 );
}


function initHeader() {

	$j('.cboxElement').colorbox({width:1100,height:820});	

	if ($j.browser.msie && $j.browser.version == "7.0") {
		//$j('div.menuSub_body').show();
	} else {
		$j('div.menuSub_body').hide();
		$j(".submenu ul li.sublink a").hover(function () {
			$j(this).next('div.menuSub_body').stop(true, true).slideDown(500);
			$j(this).next('div.menuSub_body').style.position = "relative";
			//clearTimeout ( timeoutID );
		}
/*
                                      , function() {
                                             var timeoutID = window.setTimeout( function(){$j('div.menuSub_body').stop(true, true).slideUp('slow')}, 5000);
                                      }
                                      */
		);
	}

}

function activateAccordion() {

	$j('div.subcontent').hide();

	$j('h3.accordionLink').each(function (index, domEle) {

		$j(domEle).click(function () {

			$j(domEle).next('div.subcontent').slideToggle();
			return false;

		})

	})

}


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() {

	$j("div#langs a").each(function (index, domEle) {
		if (!$j(domEle).hasClass('notLang')) {
			var currentLg = getUrlVarsFrom(window.location.href, false)['lg'],
				newLg = getUrlVarsFrom($j(domEle).attr('href'), false)['lg'];
			if (currentLg != newLg) {

				if (currentLg === undefined) {
					if (getUrlVarsFrom(window.location.href, false).length > 1) {
						$j(domEle).attr('href', window.location.href + '&lg=' + newLg);
					}



				} else {
					$j(domEle).bind('click', function () {
						window.location = window.location.href.replace('lg=' + currentLg, 'lg=' + newLg);
						return false;
					})
				}

			} else {
				$j(domEle).bind('click', function () {
					window.location = window.location.href;
					return false;
				})

			}
		}
	})


}



	var timeout = 500;
	var closetimer = 0;
	var ddmenuitem = 0;
	// open hidden layer


	function mopen(id) {
		// cancel close timer
		mcancelclosetime();
		// close old layer
		if (ddmenuitem) ddmenuitem.style.visibility = 'hidden';
		// get new layer and show it
		ddmenuitem = document.getElementById(id);
		ddmenuitem.style.visibility = 'visible';
	}
	// close showed layer


	function mclose() {
		if (ddmenuitem) ddmenuitem.style.visibility = 'hidden'; /*$("div.menuSub_body").slideUp("slow");*/
	}
	// go close timer


	function mclosetime() {
		closetimer = window.setTimeout(mclose, timeout);
	}
	// cancel close timer


	function mcancelclosetime() {
		if (closetimer) {
			window.clearTimeout(closetimer);
			closetimer = null;
		}
	}
	// close layer when click-out
	document.onclick = mclose;

var currentImage;
var currentIndex = -1;
var myTimer;
var images = [];

function showImage(index, speed) {
    currentIndex = index;


    $j('div.navigation img').removeClass('active');
    $j('div.navigation img').eq(index).addClass('active');

	
	$j('div#slideshow-home > div.item').stop();
	//$j('h1').html(index);
	$j('div#slideshow-home > div.item').eq(index)
	.css({'opacity': '0', 'z-index': '9'}).fadeTo(speed, 1, function(){ 
		$j('div#slideshow-home > div.item').css({'z-index':7});
		$j('div#slideshow-home > div.item').eq(index).css({'z-index':8, 'filter': ''});
	});





    clearTimeout(myTimer);
    myTimer = setTimeout("showNext()", 7000);


}

function showNext() {

    var len = $j('div.navigation img').length;
    var next = currentIndex < (len - 1) ? currentIndex + 1 : 0;

    showImage(next, 1500);

}


function initHome() {
	
	
	showNext(); //loads first image
        $j('div.navigation img').each(function (index, domEle) {

            $j(domEle).bind('click', function () {
                $j('div.navigation img').removeClass('active');
                $j(domEle).addClass('active');

                showImage($j(domEle).index(), 1500);

            })
        })

	
	$j('div.tools a.back').click(function() {
		var len = $j('div.navigation img').length;
		var next = currentIndex > 0 ? currentIndex - 1 : len - 1;
		showImage(next, 300);
		return false;
	});
	$j('div.tools a.next').click(function() { 
		var len = $j('div.navigation img').length;
    	var next = currentIndex < (len - 1) ? currentIndex + 1 : 0;

    	showImage(next, 300);
		return false;
	});
	
	
	$j('div#slideshow-home div.controls-area').mouseenter(function() { 
		
		$j('div#slideshow-home div.navigation').stop().animate({
			'top':'4px',
			'width':'772px'
			
			}, 300);
		
		$j('div#slideshow-home div.controls-area div.background').stop().animate({
			'top':'0px',
			'width':'772px'
			
			}, 300);
		
	}).mouseleave(function() {
		
		$j('div#slideshow-home div.navigation').stop().animate({
			'top':'65px',
			'width':'0px'
			
			}, 300);
			
		$j('div#slideshow-home div.controls-area div.background').stop().animate({
			'top':'60px',
			'width':'0px'
			
			}, 300);
		
	});

}
