$(document).ready(function() {
    resizeBackgroundImages();

	/// SCROLL TOP
    scrollTopFunctionalities();

    addParameterToAvoidCache();

    fancyBoxFunctionalities();

});
$(window).load(function() {
    ///CONTENT SHADOW
    rescaleContentBackgroundContainer();
});
$(window).resize(function() {
    resizeBackgroundImages();
});

var backgroundImageWidth = 1109;
var backgroundImageHeight = 578;
function setBackgroundImagesWidthHeight(w,h){
    backgroundImageWidth = w;
    backgroundImageHeight = h;
}

function resizeBackgroundImages(){
    var b1 = $("#bgimage");
    var bw = $("#no_overflow");

    var w = $(window).width();
    var h = $(window).height();
    bw.css("width",w+"px");
    bw.css("height",h+"px");

    var ratio = backgroundImageHeight/backgroundImageWidth;

    if ((h/w) > ratio){
        var nw = h / ratio;
        b1.height(h);
        b1.width(nw);
        var l = 0;
        if(nw>w){
            l = (nw-w)/2;
        }
        b1.css("left","-"+l+"px");
    } else {
        b1.width(w);
        b1.height(w * ratio);
        b1.css("left","0");
    }
}





var customGalleryDetailContainer = "";
function customGalleryInteraction(){
    $(document).click(function(){
        if(customGalleryDetailContainer!=""){
            customGalleryDetailContainer.html("");
            customGalleryDetailContainer.css("top","-9000px");
            customGalleryDetailContainer.css("left","-9000px");
        }
    });
	$(".inlinegallery img").click(function(){
		if(customGalleryDetailContainer==""){
			$("<div id='customGalleryDetailContainer'></div>").appendTo('#mainWrapper');
			customGalleryDetailContainer=$("#customGalleryDetailContainer");
		}
		var i = $(this);
		var bh = i.attr("rel");
		var p = i.offset();
        var mwp = $("#mainWrapper").position();
        var tw = this.width;


        $('<img />').attr('src', bh).load(function(){

            customGalleryDetailContainer.html("<img src='"+bh+"' class='shadow' alt='detail view'/>");
            customGalleryDetailContainer.css("top", (p.top-mwp.top-12)+"px");
            customGalleryDetailContainer.css("left", (p.left-mwp.left-this.width+tw)+"px");

        });

	});

}

function scaleLogoWrapper(){
//    $("#navigationCanvas").css("height", ($(document).height())+"px");
    $("#logoWrapper").css("height", ($(document).height()-63)+"px");
}

var activityWidths = new Array();
var activityInAnimation = false;
function initActivityInteraction(){
    $(".activity>h2").click(function(){
        var t = $(this).parent();
        var a = t.find(".activity_entry");
        var i = t.attr("id");
        if(!a.hasClass("visible")){
            var h = t.find("h2");
            var c = t.find(".activity_closer");
            var w = a.css("width");
            var v = a.is(":visible");
            c.click(function(){if(t.hasClass("open")){
                closeActivityDisplay(c,t,a,h,i);
            }});
            if(!v){
                if(!activityInAnimation){
                    activityInAnimation = true;
                    activityWidths[i]=h.width();
                    h.animate({width: w},200,function(){t.addClass("open");c.fadeIn();a.slideDown(800,function(){activityInAnimation=false;});});
                }
            }else{
                closeActivityDisplay(c,t,a,h,i);
            }
        }
    });
}
function closeActivityDisplay(c,t,a,h,i){
    if(!activityInAnimation){
        activityInAnimation = true;
        c.fadeOut();
        t.removeClass("open");
        a.slideUp(500,function(){h.animate({width: activityWidths[i]+'px'},200,function(){activityInAnimation=false;});});
    }
}

var logoWrapperCanvas = null;
function initActivityLines(){
    logoWrapperCanvas = Raphael("logoWrapper"), pos = [0, 0];
}
function drawActivityLines(){
    logoWrapperCanvas.clear();
    var topOffset = 17;
    var leftOffset = 9;
    var logoPos = $("#logo").position();
    var logoLeft = logoPos.left;
    var logoTop = logoPos.top;
    $(".activity>h2").each(function(){
        var p = $(this).parent().position();
        var l = (p.left)+leftOffset;
        var t = (p.top)+topOffset;
        var conn = $(this).attr("id").substring(4);
        var mt = ((conn.substring(0,conn.indexOf("_")))*1)+logoTop;
        var ml = ((conn.substring(conn.indexOf("_")+1))*1)+logoLeft;
        var lc = "M"+l+" "+t+" L"+ml+" "+mt;
        logoWrapperCanvas.path(lc).attr({stroke: "#b6b5b5", "stroke-width": 1});
//        console.log("lc: "+lc);
    });
}

var navigationCanvas = null;
function initNavigationLines(){
    $("#l2NavBG").css("height",$("#l2Nav").height()+"px");
    if($("#navigationCanvas").length>0){
        navigationCanvas = Raphael("navigationCanvas"), pos = [0, 0];
    }
}
function rescaleContentBackgroundContainer(){
    $("#contentWrapperBG").css("height",$("#contentWrapper").height()+"px");
}


var eventListBackLinkText = "";
function setEventListBackLinkText(v){
    eventListBackLinkText = v;
}
function focusDetailFunctionalities(){
    if($.getUrlVar("focusId")!=undefined){
        var $d = $("#"+$.getUrlVar("focusId"));
        if(eventListBackLinkText.length>2){$d.append("<br/><br/><a href='javascript:history.back()'>"+eventListBackLinkText+"</a>");}
        $d.addClass("focusedEvent");
        var t = $d.offset().top;
        $.scrollTo(t-22, 100);
    }
}
function scrollTopFunctionalities(){
    $(window).scroll(function() {
		if($(this).scrollTop() != 0) {
			$('#toTop').fadeIn();
		} else {
			$('#toTop').fadeOut();
		}
	});

	$('#toTop').click(function() {
		$('body,html').animate({scrollTop:0},800);
	});
}
function imageBoxFunctionalities(){
    $("#imgwrapper").mouseenter(function(){
        $(this).css("z-index",50);
    }).mouseleave(function(){
        $(this).css("z-index",20);
    });
}
function mainNavigationFunctionalities(){
    $("#l1Nav ul.sf-menu").superfish();
    $("#l1Nav ul ul li").each(function(){
        var t = $(this);
        if($("ul", t).size()>0){
            $("<span class='sn'>&gt;</span>").appendTo(t);
        }
    });
}


var basePath = "/";
var sitePath = "/";

function setBasePath(bp){
    basePath = bp;
}
function setSitePath(sp){
    sitePath = sp;
    var h = filterHandlingScriptPath+"?ck="+new Date().getTime();
    $.get(h,{'siteHandle': sp});
}


var imgBoxSlideStepTime = 2000;
var imgBoxSlideFadeTime = 800;
function setImgBoxSlideStepTime(t){imgBoxSlideStepTime=t;}
function setImgBoxSlideFadeTime(t){imgBoxSlideFadeTime=t;}
var imgBoxCurrentImage = 0;
var imgBoxHandles = new Array();
var imgBoxTitles = new Array();

function initImgBoxSlideShow(){
    var imgbox = $("#imgwrapper");
    if(imgBoxHandles.length>1){
        $("<img id='box_nextimg' src='"+imgBoxHandles[1]+"' alt='"+imgBoxTitles[1]+"' title='"+imgBoxTitles[1]+"' />").appendTo(imgbox);
        window.setTimeout('showNextImgBoxImage()', imgBoxSlideStepTime);
    }
}
function showNextImgBoxImage(){
    imgBoxCurrentImage++;
    if(imgBoxCurrentImage>=imgBoxHandles.length){imgBoxCurrentImage=0;}
    var ci = $("#box_currentimg");
    var ni = $("#box_nextimg");
    ni.fadeIn(imgBoxSlideFadeTime,function(){
        ni.attr("id","box_currentimg");
        ci.attr("id","box_nextimg").fadeOut(0).attr("src",imgBoxHandles[imgBoxCurrentImage]).attr("alt",imgBoxTitles[imgBoxCurrentImage]).attr("title",imgBoxTitles[imgBoxCurrentImage]);
        window.setTimeout('showNextImgBoxImage()', imgBoxSlideStepTime);
    });
}



/* helper methods */


function eventGalleryFunctionalities(){
    $(".eventGallery a").fancybox({
        'overlayColor'		: '#fff',
        'margin'       : 0,
        'padding'       : 0,
        'width'         : 600,
        'height'        : 400,
        'autoScale'        : false,
        'hideOnContentClick' : true,
        'showCloseButton'    : false,
        'autoDimensions'     : false,
        'titleFormat': formatInlineGalleryTitle,
        'overlayOpacity'	: 0.5
    });
}
function formatInlineGalleryTitle(title, currentArray, currentIndex, currentOpts) {
//    document.title = "";
    $("#collection_thumbnav img").each(function(){
        var t = $(this);
        var n = t.attr("id").substring(2);
        if(n==currentIndex){$(this).addClass("active");}else{$(this).removeClass("active");}
//        document.title += n +"/"+currentIndex+" ... ";

    });
    return (title && title.length ?  '<div id="currentImageTitle">' + title + '</div>' : '' );
}

function fancyBoxFunctionalities(){
    $(".gallery a, a.fancyBox").fancybox({
        'overlayColor'		: '#7b7c7e',
        'overlayOpacity'	: 0.75,
        'titlePosition' 	: 'over'
    });
}

function addParameterToAvoidCache(){
/* append url parameter to avoid mgnl cache */
    $(".kclink").each(function(){
        var $l = $(this).attr("href");
        if($l.indexOf("?")==-1){
            $l+="?";
        }else{
            $l+="&";
        }
        $l+="kc"+new Date().getTime();
        $(this).attr("href", $l)
    });
}

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});
/* decryp addresses*/
function dcmadr(nnnn){
    var a = "";
    for(i=0,m=nnnn.length;i < m;i++){
        if(i%3==0){
            a += String.fromCharCode(nnnn.substr(i, 3));
        }
    }
    location.href=(a);
}

