// ------------------------------------------ //
// LINK FUNCTIONS							  //
// ------------------------------------------ //
function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
}

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

function gotoLink (htmlElement, gakey) {
	
	if(typeof gakey == "string") {
		var path =  "/" + language + "/teaser/" + gakey;
		_gaq.push(['_trackPageview', path]);
	}
	
	var destinationURL = "";
	var target = "";
	
	if(htmlElement.href) {
		destinationURL = htmlElement.href;
		target = htmlElement.getAttribute("target");
	} else {
		if(htmlElement.childNodes) {
			if(htmlElement.getElementsByTagName("a")) {
				destinationURL = htmlElement.getElementsByTagName("a")[0].href;
				target = htmlElement.getElementsByTagName("a")[0].getAttribute("target");
			}
		}
	}
	if(destinationURL != "") {
		if(target == "_blank") {
			window.open(destinationURL);
		} else {
			location.href = destinationURL;
		}
	}
	return false;
}

function getLink(vari, target) {
	if(target == "_blank") {
		window.open(vari);
	} else {
		window.location.href = vari;
	}
}

function externalLinkClick () {
	var trackKey = this.getAttribute("trackKey");
	_gaq.push(['_trackPageview','/external/' + trackKey]);
	clickTracker('/external/' + trackKey); // e-Tracker
}


function getUniqueId (size) {
	var chars = "abcdefghijklmnopqurstuvwxyz";
	var str = "";
	for(var i = 0; i < size; i++) {
		str += chars.substr( Math.floor(Math.random() * 26), 1 );
	}
	return str;
}

function popitup(url, width, height) {
	newwindow=window.open(url,'name','height=' + height + ',width=' + width);
	if (window.focus) {newwindow.focus()}
}

function openLightbox(id) {
	if(affiliate) {
		$.colorbox({inline: true, href: id, opacity: 0.2, open: true, maxHeight: "80%"});
	} else {
		$.colorbox({inline: true, href: id, opacity: 0.2, open: true, maxHeight: "80%"});
	}
}

function openLightboxAjax(type, id) {
	$.colorbox({href: "/" + language + "/?controller=panorama&action=lightboxinfo&type=" + type + "&id=" + id, opacity: 0.5, open: true, maxHeight: "80%"});
	
	/*$.ajax({
		data: {type: type, id: id},
		cache: true,
		dataType: 'html',
		url: "/" + language + "/?controller=panorama&action=lightboxinfo",
		timeout: 3000,
		success: function(lightboxcontent){
			console.log(lightboxcontent);
		}
	});*/
	
}

function getDefaultLanguage() {
    var cookie = getCookie('languageoverlay');
    if (cookie != 'true') {
        setCookie('languageoverlay', 'true');
        var browserLanguage = navigator.language.slice(0,2);
        var availableLanguages = ["de","en","nl","pl","cs","hu","ru","da","sl","hr","ro","sk"];
        var websiteLanguage = window.location.pathname.split('/').slice(1,2);
        if (availableLanguages.indexOf(browserLanguage) > -1 && browserLanguage != websiteLanguage) {
            $.ajax({
                url: "/" + browserLanguage + "/shared/includes/languageoverlay",
                cache: false,
                success: function(data) {
                    $('#site').append(data);
                    console.log(data);
                }
            });
        }
    }
}

function setCookie(name,value) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + 365);
    var value= escape(value) + "; expires="+exdate.toUTCString() + "; path=/";
    document.cookie=name + "=" + value;
}

function getCookie(name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==name){
            return unescape(y);
        }
  }
}

$(document).ready(function() {

	// ISOTOPE
    //getDefaultLanguage();

	if ( $("#teasers").length ) {
		
		$("#teasers").isotope({
			duration: 0,
			easing: 'linear',
			queue: false,
			filter: currentactiveCat,
			visibleStyle: { display: 'block' },
			hiddenStyle: { display: 'none' },
			transformsEnabled: false,
			masonry: {
				columnWidth: 253
			},
			animationEngine: "best-available",
			sortBy: "original-order"
		});

		if ( $("ul#filters").length ) {

			var firstfilteritem = $("ul#filters li a.active");
			var firstfilteritemwidth = firstfilteritem.width() + 26;
			var firstfilteritemmarginfromleft = (firstfilteritemwidth/2) - 12;
			var firstfilteritemspan = $("span",firstfilteritem);
			$(firstfilteritemspan).css("left",firstfilteritemmarginfromleft);

			$("ul#filters li a").click(function() {
				var width = $(this).width() + 26;
				var marginfromleft = (width/2) - 12;
				var arrow = $("span",this);
				arrow.css("left",marginfromleft);
				$("ul#filters li a").removeClass("active");
				$(this).addClass("active");
				$(this).blur();
				return false;
			});
		}

		var cat;
		var portalbgimages = $('#background_container .bgimage');
		
		//setTimeout($('#background_container .bgimage:not(.active)').css({ "opacity": 0 }).show(), 250);
		$('#background_container .bgimage:not(.active)').css({ "opacity": 0 }).show();
	
		$("ul#filters li a").each(function(i) {
			$(this).bind({
				click:	function() {			
					$("#teasers .roundteaser").hide();
					$("#teasers").append("<div id='loading'><img src='/static/2011/img/loading.gif' alt='' /></div>");
					$("#teasers").addClass("loading");
					
					var cat = $(this).attr("data-filter");
					cat = cat.slice(1);
					var x = setTimeout(function() {doRequest("." + cat)}, 200);
					
					
					var currentnr = i;

					portalbgimages.eq(i).stop().fadeTo(250, 1, function() { });
					$("#background_container .bgimage.active").fadeOut(250, function() { });
					
					$("#background_container .bgimage.active").removeClass("active")
					portalbgimages.eq(i).addClass("active");

					
					
					// Background Fading
					/*if ( portalBackgroundImages ) {
						var currentnr = i;
						
						var currentimg = portalBackgroundImages[currentnr];
						$("#filter").append("<div class='stresslayer'></div>");
						$(".stresslayer","#filter").show();
						$("<img />").prependTo("#background_container").attr("src",currentimg);
						$('#background_container').onImagesLoad({
							selectorCallback: function() {
								$("<div class='bgimage'>").prependTo("#background_container").attr("style", "background-image: url(" + currentimg + ");");
								$("img","#background_container").remove();
								$("#background_container .bgimage:last").fadeOut(400, function() {
									$("#background_container .bgimage:last").remove();
									$(".stresslayer","#filter").hide();
								});
							}
						});
					}*/
					
				}
			});
		});

		function doRequest(cat) {
		
			$("#teasers").isotope("destroy");
			$("#loading").remove();
			
			var catclass = cat;
			
			$("#teasers").isotope({
				duration: 0,
				easing: 'linear',
				queue: false,
				filter: catclass,
			    visibleStyle: { display: 'block' },
				hiddenStyle: { display: 'none' },
				masonry: { columnWidth: 253 },
				animationEngine: "best-available",
				sortBy: "original-order"
			});
			$("css3").css("display","none");
			$("#teasers .roundteaser").not(".isotope-hidden").show();
		}

	}
	
	
	
	// SKI TICKETS FORMULAR
	
	
	if($(".skiticketform").length > 0 && $("select[name=tickettemp]").length > 0) {
		
		var skiticketforms = $(".skiticketform");
		skiticketforms.each(function(i){							 
			var skiticket_tickettemp_select = $("select[name=tickettemp]", this).eq(0);
			var skiticket_tickettemp1_select = $("select[name=tickettemp_dt]", this).eq(0);
			var skiticket_tickettemp2_select = $("select[name=tickettemp_mdt]", this).eq(0);
			var skiticket_tickettemp3_select = $("select[name=tickettemp_st]", this).eq(0);
			var skiticket_ticket_inputhidden = $("input[name=ticket]", this).eq(0);
			
			var skiticket_validfrom = $(".validfrom", this).eq(0)
			var skiticket_hiddenformline1 = $(".hidden_dt", this).eq(0);
			var skiticket_hiddenformline2 = $(".hidden_mdt", this).eq(0);
			var skiticket_hiddenformline3 = $(".hidden_st", this).eq(0);
			
			var skiticketsubmit = $(".submit", this).eq(0);
			
			if(skiticket_tickettemp_select.selectedIndex == 1) {
				skiticket_hiddenformline1.show();
			} else if(skiticket_tickettemp_select.selectedIndex == 2) {
				skiticket_hiddenformline2.show();
			}
			
			// show region-selectbox only if oneday-tickets are chosen:
			skiticket_tickettemp_select.bind({
				change: function() {
					if(this.selectedIndex == 1) {
						skiticket_ticket_inputhidden.val(skiticket_tickettemp1_select.val());
						skiticket_hiddenformline2.hide();
						skiticket_hiddenformline3.hide();
						skiticket_hiddenformline1.show();
						skiticket_validfrom.show();
					} else if(this.selectedIndex == 2) {
						skiticket_ticket_inputhidden.val(skiticket_tickettemp2_select.val());
						skiticket_hiddenformline1.hide();
						skiticket_hiddenformline3.hide();
						skiticket_hiddenformline2.show();
						skiticket_validfrom.show();
					} else if(this.selectedIndex == 3) {
						skiticket_ticket_inputhidden.val(skiticket_tickettemp3_select.val());
						skiticket_validfrom.hide();
						skiticket_hiddenformline1.hide();
						skiticket_hiddenformline2.hide();
						skiticket_hiddenformline3.show();
					} else {
						skiticket_hiddenformline1.hide();
						skiticket_hiddenformline2.hide();
						skiticket_hiddenformline3.hide();
						skiticket_validfrom.show();
					}
				}
			});
			
			skiticket_tickettemp1_select.bind({
				change: function() {
					skiticket_ticket_inputhidden.val($(this).val());
				}
			});
			
			skiticket_tickettemp2_select.bind({
				change: function() {
					skiticket_ticket_inputhidden.val($(this).val());
				}
			});
			
			skiticket_tickettemp3_select.bind({
				change: function() {
					skiticket_ticket_inputhidden.val($(this).val());
				}
			});
			
			skiticketsubmit.bind({
				click: function() {
					skiticketforms.eq(i).submit();
				}
			});
			
		});
		
	}
	
	
	
	// SET COOKIES
	var navigationtags = $("#metanav .dropdown.heart a.tag");
	if(navigationtags.length > 0) {
		navigationtags.each(function(i) {
			if($.cookie("ilovecategory[" + $(this).attr("rel").substring(4) + "]")) {
				$(this).addClass("clicked");
			}
		});
	}
	
	var sidebartags = $("#contentarea .rightcol .roundteaser.ilove a.tag");
	var sidebartagscounter = 0;
	if(sidebartags.length > 0) {
		sidebartags.each(function(i) {
			if(sidebartagscounter < 6 && $.cookie("ilovecategory[" + $(this).attr("rel").substring(4) + "]")) {
				$(this).addClass("clicked");
				sidebartagscounter++;
			}
		});
	}
	

	// SMALL FILTER

	if ($("ul#smallfilters").length) {
		
		var navigationtagscontainer = $("#metanav .dropdown.heart");
		var smallfilters = $("ul#smallfilters li a");
		var activefilters = new Array();
		
		smallfilters.each(function(i) {
			if($(this).hasClass("active")) {
				$.cookie("ilovecategory[" + $(this).attr("data-filter").substring(4) + "]", 'true', { expires: 365, path: '/' });
			}
		});
		
		$("ul#smallfilters li a").bind({
			click: function() {
				if($(this).hasClass("active")) {
					$(this).removeClass("active");
					$.cookie("ilovecategory[" + $(this).attr("data-filter").substring(4) + "]", null, { path: '/' });
					$("a.tag[rel='" + $(this).attr("data-filter") + "']", navigationtagscontainer).removeClass("clicked");
				} else {
					$(this).addClass("active");
					$.cookie("ilovecategory[" + $(this).attr("data-filter").substring(4) + "]", 'true', { expires: 365, path: '/' });
					$("a.tag[rel='" + $(this).attr("data-filter") + "']", navigationtagscontainer).addClass("clicked");
				}
				
				$(this).blur();
				
				activefilters = new Array();
				nofilter = true;
				
				smallfilters.each(function(i) {
					if($(this).hasClass("active")) {
						activefilters[i] = $(this).attr("data-filter");
						nofilter = false;
					}
				});
				
				if(nofilter) {
					var cat = ".cat0";
				} else {
					var cat = activefilters.join(", ");
				}
				var x = setTimeout(function() {doRequest(cat)}, 200);
			}
		});	
	}


	// METANAV

	if ( $("#metanav").length ) {
		$("#metanav > li").hover(function() {

			var thisposition = $(this).position().left;
			var thiswidth = $(this).width();
			var posfromleft = thisposition + ((thiswidth / 2) - 10);

			var child = $(".dropdown",$(this));
			var arrow = $(".arrow_down",$(this));
			arrow.css("left",posfromleft);

			if ( child.hasClass("dropdown") ) {
				var siteheight = $("html").height();
				$("#layer").height(siteheight).show();
				child.show();
				arrow.show();

				// ADJUST VERTICAL BORDERS IN MAINNAV

				if ( $(".bookinglinks",child) ) {
					
					var linkblock = $(".booking_links .linkblock",child);
					var lblength = linkblock.length;
					var maxheight = 0;

					for ( j=0; j<lblength; j++ ) {
						var currentlb = $(".linkblock:eq("+j+")",child);
						var clbheight = currentlb.height();
						if ( clbheight > maxheight ) {
							maxheight = clbheight;
						}
					}
					
					linkblock.height(maxheight);

				}

			}
			if ( child.hasClass("simple")) {
				child.css("left",thisposition+1);
			}
		},
		function() {
			var child = $(".dropdown",$(this));
			var arrow = $(".arrow_down",$(this));
			child.hide();
			arrow.hide();
			$("#layer").hide();
		});
	}
	
	
	// DATEPICKER
	
	if($(".datepicker").length > 0) {
		if(language == "de") {
			$(".datepicker").datepicker({
				buttonImage: '/static/img/new/calendar.png',
				buttonImageOnly: true,
				buttonText: '',
				showOn: 'both',
				minDate: 0,
				gotoCurrent: true,
				nextText: '',
				prevText: '',
				numberOfMonths: 1, regional: "de", dateFormat: 'dd.mm.yy', firstDay: 1,
				monthNames: ['Januar','Februar','M&auml;rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
				dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa']
			});
		} else {
			$(".datepicker").datepicker({
				buttonImage: '/static/img/new/calendar.png',
				buttonImageOnly: true,
				buttonText: '',
				showOn: 'both',
				minDate: 0,
				gotoCurrent: true,
				nextText: '',
				prevText: '',
				numberOfMonths: 1, dateFormat: 'dd.mm.yy', firstDay: 1
			});
		}
		
		/*if($("form.skitickets_vorverkauf").length > 0) {
			$("form.skitickets_vorverkauf").each(function(i) {
				if($("input[name=desireddate]", $(this)).length > 0 && $("input.desireddatemindate", $(this)).length > 0) {
					var minDateArr = $("input.desireddatemindate", $(this)).val().split("-");
					var desireddatepickerInput = $("input[name=desireddate]", $(this)).eq(0);
					desireddatepickerInput.datepicker({minDate: new Date(minDateArr[0], minDateArr[1]-1, minDateArr[2])});
				}
			});
		}*/
		
	}
	

	// LIFT TABLE

	if ( $("#popups").length ) {

		
		$("#popups .table").each(function(i) {
			$(".row:even", this).addClass("even");
			$(".row.header", this).addClass("even");
		});
		$("#popups table").each(function(i) {
			$(".row:even", this).addClass("even");
			$(".row.header", this).addClass("even");
		});
		

		$(".smallbox").click(function() {
			$(".mainbox").removeClass("clicked");
			$(".smallbox").removeClass("clicked");
			var thisclass = $(this).attr("class");
			var croppedclass = thisclass.slice(9);
			$(".popup","#popups").hide();
			$(".popup."+croppedclass,"#popups").show();
			$("#popups").show();
			$(this).addClass("clicked");
			return false;
		});

		$(".mainbox").click(function() {
			$(".mainbox").removeClass("clicked");
			$(".smallbox").removeClass("clicked");
			var thisclass = $(this).attr("class");
			var croppedclass = thisclass.slice(8);
			$(".popup","#popups").hide();
			$(".popup."+croppedclass,"#popups").show();
			$("#popups").show();
			$(this).addClass("clicked");
			return false;
		});

		$("a.close","#popups").click(function() {
			$(".mainbox").removeClass("clicked");
			$(".smallbox").removeClass("clicked");
			$(".popup","#popups").hide();
			$("#popups").hide();
			return false;
		});

		// MAKE TOOLTIP DISAPEAR WHEN LEAVING THE ROW

        if(!affiliate) {
            $(".scrollingtable .row").mouseenter(function() {
                $(this).addClass("hover");
                var offset = $(".tooltip",this).offset();
                var height = $(".tooltip",this).height();
                if((parseInt(offset.top) + parseInt(height)) > 1090) {
                    $(".tooltip",this).css("top", "auto");
                    $(".tooltip",this).css("bottom", "1px");
                }
                console.log(parseInt(offset.top) + parseInt(height));
            }).mouseleave(function() {
                $(this).removeClass("hover");
            });
        }

	}


	// LANGUAGE POPUP

	if ( $("a.close","#lang_popup").length ) {
		$("a.close","#lang_popup").click(function() {
			$("#lang_popup").fadeOut();	
		});
	}

		
	
	// SOCIAL LAYER

	if ( $("a#socialbutton").length ) {
	
		$("#socialbutton").click(function() {
			$("#social_layer").show();
			$("#social_layer .limiter").append("<div id='loading'><img src='/static/2011/img/loading.gif' alt='' /></div>");
			var y = setTimeout(function() {getSocialItems()},1000);
			
			return false;
		});
		
		if ( $("#social_layer").length ) {
			$("a.close","#social_layer").live("click",function() {
				$("#social_layer .limiter").empty();
				$("#social_layer").hide();
				return false;
			});
		}

		function getSocialItems() {
			$.ajax({
				url: "/" + language + "/?controller=content&action=socialmediaoverlay",
				cache: false,
				beforeSend: function() { },
				success: function(data) {
					$("#social_layer .limiter").html(data);
				}
			});
		}

	}

	// COLORBOX
	if ( $("a.lightbox").length ) {
        $("a.lightbox").colorbox({current: function(){
            var image = $('img', this); return image.attr('alt');
        }, opacity: 0.4, rel: "content"});
	}
	
	if ( $("a[rel='lightbox']").length ) {
        $("a[rel='lightbox']").colorbox({current: function(){
            var image = $('img', this); return image.attr('alt');
        }, opacity: 0.4, rel: "content"});
	}
	
	// VIDEO LIGHTBOX
    if($(".roundteaser.video").length > 0) {
		var videoteaser = $(".roundteaser.video");
		videoteaser.each(function(i) {
			$(this).bind({
				click: function() {
					$("a", $(this)).colorbox({current: function(){
						return $(this).attr('title');									
					}, iframe:true, innerWidth:640, innerHeight:390, transition:"none", overlay:false, opacity: 0.4, open:true, rel:'nofollow'});
				}
			});
		});
    }

	// GALLERY TEASER
	if($(".roundteaser.gallery").length > 0) {
		var galleryteaser = $(".roundteaser.gallery");
		galleryteaser.each(function(i) {
			$(this).bind({
				click: function() {
					$(".galleryimages a", $(this)).colorbox({current: function(){
						return "";									
					}, transition:"none", opacity: 0.4, open:true, rel: "gallery_" + i });
				}
			});
		});
    }

	// SEASON START OVERVIEW
	if($("#textarea .openinfo .infolink").length > 0) {
		var pisteninfoboxes = $("#textarea .openinfo .info_extra");
		
		$("#textarea .openinfo .infolink").each(function(i){
			$(this).bind({
				click: function() {
					pisteninfoboxes.eq(i).toggle();
				}
			});	
		});
	}


	if( $('#setYourLanguageToBrowserLanguage.isTest')[0] ){
		if( $.cookie('sa_cookie_lang') != 'closed' ){
			$.ajax({
				type: 'POST',
				url: '/?controller=snippets&action=shownewlng',
				data: '&lng=' + language,
				success: function( msg ){
					if( msg != '' ){
					$('#setYourLanguageToBrowserLanguage').append( msg ).fadeIn();

					$('#closeThisLanguageBadgeOverlay').bind({
						click: function(){
							$('#setYourLanguageToBrowserLanguage').fadeOut(function(){
								var cDate = new Date();
								$.cookie('sa_cookie_lang', 'closed', {expires: cDate.setDate(cDate.getDate() + 1)});
							});
						}
					});
					}
				}
			});
		}
	}

});

$(window).load(function() {

	// LANGUAGE DROPDOWN

	if ( $("#lang_dropdown").length ) {
		$("#lang_dropdown").hover(function() {
			$(this).addClass("active");
			$(".dropdown","#lang_dropdown").show();
		}, function() {
			$(this).removeClass("active");
			$(".dropdown","#lang_dropdown").hide();
		});
	}

	// BREADCRUMBS
	if ( $("ul#breadcrumbs").length ) {
		$("ul#breadcrumbs li").hover(function() {
			$(this).addClass("active");
		},
		function() {
			$(this).removeClass("active");
		});
	}
	
	// WINTER PANORAMA
	if(!affiliate && $("#winterpanorama").length > 0 ) {
		var headerheight = 60;
		$("#winterpanorama").height($(window).height() - headerheight);
		
		$(window).resize(function() {
			var windowheight = $(window).height();
			$("#winterpanorama").height(windowheight - headerheight);
		});
		
		$('a:last').hide();
	}

    // SET DESKLINE NEWSLETTER CHECKBOX TO ACTIVE
    if($("#savingrequestform").length > 0) {
        $("#savingrequestform input[name=newsletter]").attr("checked", "checked");
    }

	
	// ------------------------------------------ //
	// track external links with google analytics //
	// ------------------------------------------ //
	
	window.setTimeout(function () {
		var externalLinks = $("#subnavigation a, #textarea a, .roundteaser a, .teaser a");
	
		for(var i = 0; i < externalLinks.length; i++) {
			if (externalLinks[i].getAttribute("href")) {
				if(externalLinks[i].getAttribute("href").indexOf("http") >= 0) {
					if(externalLinks[i].getAttribute("href").indexOf("skiamade.com") < 0) {
						var hostname = parseUri(externalLinks[i].getAttribute("href")).host;
						externalLinks[i].setAttribute("trackKey",hostname);
						externalLinks[i].onclick = externalLinkClick;
					}
				}
			}
		}
	}, 800);
	
	
	// ------------------------------------------ //
	// AD-Server Integration                      //
	// ------------------------------------------ //
	
	var adcodes = [];
	$(".adserver[lang]").each(function (index, el) {
		var code = getUniqueId(5);
		el.setAttribute("id", code);
		
		var zoneId = el.getAttribute("lang");
		if(zoneId) {
			adcodes.push(code + "_" + zoneId);
		}
	});
	
	if(adcodes.length > 0) {
		$.ajax({
			cache: false,
			dataType: 'json',
			url: "/ads/code?zones=" + adcodes.join(","),
			timeout: 2500,
			success: function(codes){
				
				$(".adserver[lang]").each(function (index, el) {
					var id = $(el).attr("id");
					if(codes[id]) {
						$(el).append(codes[id]);
						$("div", el).show();						
					} else {
						$(el).remove();
						
						if($("#teasers") && $("#teasers").isotope) {
							$("#teasers").isotope( 'destroy' );
							
							$("#teasers").isotope({
								duration: 0,
								easing: 'linear',
								queue: false,
								filter: currentactiveCat,
								visibleStyle: { display: 'block' },
								hiddenStyle: { display: 'none' },
								masonry: {
									columnWidth: 253
								},
								animationEngine: "best-available",
								sortBy: "original-order"
							});
							
						}
					}
				});			
				
				
				$(".adserver_banner").each(function (index, el) {
					var el = $(this);
					
					var category = "AD-CAMPAIGN: " + el.attr("campaignName");
					var action = "AD-IMPRESSION";
					var label = "AD-BANNER: " + el.attr("bannerName");
					_gaq.push(['_trackEvent', category, action, label]);
				});
			}
		});
	}
	
	$(".adserver_banner").live("click", function () {
		var el = $(this);
		
		var category = "AD-CAMPAIGN: " + el.attr("campaignName");
		var action = "AD-CLICK";
		var label = "AD-BANNER: " + el.attr("bannerName");
		_gaq.push(['_trackEvent', category, action, label]);
		
		
		window.open($("a", this).attr("href"));
	});

});






