// ###################################
// ############ UA CHECK #############
// ###################################

/* user agent sniffing shortcuts */

var ua = {};
with (ua) {
	ua.toString = function() { return navigator.userAgent; };
	ua.test = function(s) {
		return toString().toLowerCase().indexOf(s.toLowerCase()) > -1;
	};
	ua.gecko = test("gecko") && !test("webkit");
	ua.webkit = test("webkit");
	ua.opera = test("opera");
	ua.ie = test("msie");
	ua.ie6 = test("msie 6") && !test("msie 8");
	ua.mac = test("mac");
	ua.win = test("windows");
}


// ###################################
// ############# SCALING #############
// ###################################

/**
 * Scaling framework to handle viewport width/text size ratio
 */
var Scaling = {
  timerId: 0, // identifier for scaling loop
  bodySize: '',
  runRules: function() { // scaling loop, checking conditions for each rule
    
	var r = Scaling.getRatio();

    if (r != Scaling.lastRatio) {
      var size = '';
      switch (true) {
        case r < 300/12:
          size = '';
          break;
        case r > 300/12 && r <= 610/12:
          size = 'size_s';
          break;
        case r > 610/12 && r <= 760/12:
          size = 'size_s size_m';
          break;
        case r > 760/12 && r <= 900/12:
          size = 'size_s size_m size_l';
          break;
        case r > 900/12 && r <= 1100/12:
          size = 'size_s size_m size_l size_xl';
          break;
        case r > 1100/12:
          size = 'size_s size_m size_l size_xl size_xxl';
          break;
      };



      var tmp = Scaling.bodyClass;
      var classes = ["size_s", "size_m", "size_l", "size_xl", "size_xxl"];
      for (var index in classes) {
        tmp = tmp.replace(" " + classes[index], "");
      }
      document.body.className = tmp + ' javascript-enabled ' + size;
      Scaling.bodySize = size;
      
      setCookie('ui_scaling',Scaling.bodySize, 365);
      
      Scaling.lastRatio = r;
      if (typeof Scaling.onRatioChange == "function") // custom event trigger
        Scaling.onRatioChange();
    }
  },
  ratioElement: null,
  createRatioElement: function() { // create element to calculate runtime ratio
    var n = document.createElement("div");
    n.style.position = "absolute";
    n.style.top = "0";
    n.style.left = "-1234em";
    n.style.width = n.style.height = "1em";
    n.style.overflow = "hidden";
    n.style.fontSize = "100%";
    document.body.appendChild(n);
    Scaling.ratioElement = n;
  },
  lastRatio: null, // previous ratio
  getRatio: function() { // divide viewport width by font size
    var w = 0;
    if (document.documentElement && document.documentElement.clientWidth)
      w = document.documentElement.clientWidth;
    else if (document.body && document.body.clientWidth)
      w = document.body.clientWidth;
    else if (window.innerWidth)
      w = window.innerWidth - 18;
    return w / Scaling.ratioElement.offsetHeight; // height is 1em in pixels
  },
  bodyClass: '',
  setup: function() { // use setup function on DOM content loaded event
	if (Scaling.timerId == 0) { // only one instance of scaling loop allowed
		Scaling.timerId = 1;
    	Scaling.bodyClass = document.body.className;
		if (!$('body').hasClass('size_noresize')) {
		  Scaling.createRatioElement();
		  Scaling.runRules();
		  $(window).resize(function(){
			  Scaling.runRules();
	    	});
		}
	}
  }
};



// ###################################
// ############ CSS RULES ############
// ###################################


function createJSStyleSheet(){
  var elHead = document.getElementsByTagName('head')[0];
  var elLink = document.createElement('link');
  elLink.setAttribute('rel','stylesheet');
  elLink.setAttribute('href','/_ui/screen_js.css');
  elLink.setAttribute('type','text/css');
  elLink.setAttribute('media','screen');
  elHead.appendChild(elLink);
}

createJSStyleSheet();

// ###################################
// ############# CORNERS #############
// ###################################

/* CorneredBox function to add corners to any element */
function CorneredBox(n) {
	
	$(n).append('<div class="corner corner_tl"></div><div class="corner corner_tr"></div><div class="corner corner_bl"></div><div class="corner corner_br"></div>').css({position: $(n).css('position') != 'absolute' ? 'relative' : ''});

  	
  this.compensateIE = function() { // to compensate rounding error in IE 6
    if (ua.ie6) {
      $('.corner_tr, .corner_br', n).css({right: ($(n).width() % 2 == 1) ? "-1px" : "0"});
      $('.corner_bl, .corner_br', n).css({bottom: ($(n).height() % 2 == 1) ? "-1px" : "0"});
    }
  }
   this.compensateIE();
   CorneredBox.instances.push(this);
	
}
CorneredBox.compensateIEAll = function() {
  
	for (var k in CorneredBox.instances) {
		
		CorneredBox.instances[k].compensateIE();
	}
};
CorneredBox.instances = [];
CorneredBox.setup = function(nl) {
  //return;

if (!nl.length) return;
  var i=nl.length; while(i--)
    if(nl[i])
      new CorneredBox(nl[i]);
};



/* CorneredBox end */

// ###################################
// ############### DOTS ##############
// ###################################

/* DottedBox function to add dotted borders in IE6 */
/* Writes 4 divs in parentbox. Styling and background-image for dots in CSS */
function DottedBox(n) {
  if (!ua.ie6) return; // Only for IE6
  if (!$(n).size()) return;
  var that = n;
  $(n).addClass("border_box_ie6");
  var width = $(n)[0].clientWidth;
  var height = $(n)[0].clientHeight;
  that.t = document.createElement("div");
  that.t.className = "border_ie6 border_t";
  that.t.style.width = width+"px";
  $(n).append(that.t);
  that.r = document.createElement("div");
  that.r.className = "border_ie6 border_r";
  that.r.style.height = height+"px";
  $(n).append(that.r);
  that.b = document.createElement("div");
  that.b.className = "border_ie6 border_b";
  that.b.style.width = width+"px";
  $(n).append(that.b);
  that.l = document.createElement("div");
  that.l.className = "border_ie6 border_l";
  that.l.style.height = height+"px";
  $(n).append(that.l);
  if ($(n).css('position') != "relative" && $(n).css('position') != "absolute")
    $(n).css('position','relative');
  this.compensateIE = function() { // to compensate rounding error in IE 6
	if (ua.ie6) {
      $('.border_r',n).css({right: (width % 2 == 1) ? "-1px" : "0"});
      $('.border_b',n).css({bottom: (height % 2 == 1) ? "-1px" : "0"});
      that.t.style.width = that.b.style.width = n.clientWidth+"px";
      that.l.style.height = that.r.style.height = n.clientHeight+"px";
    }
    
  }
  this.compensateIE();
  DottedBox.instances.push(this);
}
DottedBox.compensateIEAll = function() {
	for (var k in DottedBox.instances) {
		DottedBox.instances[k].compensateIE();
	}
};
DottedBox.instances = [];
DottedBox.setup = function(nl) {
	$(nl).each(function(i,n){new DottedBox(n);})  
};
/* DottedBox end */


// ###################################
// ############### ???? ##############
// ###################################

/* CorneredBox & DottedBox: compensate for IE rounding error after scaling
 * Also includes resize handler for IE6/7 for foldable items on 'Nieuw bij AH'
 */
Scaling.onRatioChange = function() {
  if (ua.ie) CorneredBox.compensateIEAll();
  if (ua.ie && $('#nieuwbijah').size() && typeof resetFold != 'undefined') resetFold();
  if (ua.ie6) DottedBox.compensateIEAll();
};

// ###################################
// ############## LINKS ##############
// ###################################

function setupExternalLinks() {
	$("a.external").attr('target','_blank');
}

// ###################################
// ############# COOKIES #############
// ###################################

function setCookie(name, value, days){
  var cookieString = name + "=" + escape(value);
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    cookieString += "; expires="+date.toGMTString();
  }
  document.cookie = cookieString;
}

function getCookie(name) {
  var results = document.cookie.match (name + "=(.*?)(;|$)");

  if (results)
    return (unescape(results[1]));
  else
    return null;
}

function removeCookie(name) {
  var cookieDate = new Date ();  // current date & time
  cookieDate.setTime(cookieDate.getTime()-1);
  document.cookie = name += "=; expires=" + cookieDate.toGMTString();
}

// ###################################
// ########### INITIALIZE ############
// ###################################

/* initialize when DOM is loaded */



// ###################################
// ############# PROFILER ############
// ###################################

var Profiler = function(){};
Profiler.prototype = {
  time: 0,
  marks: [],
  initialize: function(){
    this.reset();
  },
  reset: function(){
    this.time = new Date().getTime();
  },
  mark: function(label){
    var time = new Date().getTime() - this.time;
    this.marks.push({
        "label": label,
        "time": time});
    this.reset();
    return time;
  },
  show: function(){
    if(PROFILER) {
      var str = '';
      var total = 0;
      for (var i = 0; i < this.marks.length;i++){
        str += this.marks[i].label + ': ' + this.marks[i].time + '\n';
        total += this.marks[i].time;
      }
      str += '\nTotal: ' + total;
      var el = document.createElement('textarea');
      el.value = str;
      el.style.position = 'absolute';
      el.style.color = '#000';
      el.style.fontSize = '12px';
      el.style.top = '0px';
      el.style.zIndex = '2000';
      el.setAttribute('cols',40);
      el.setAttribute('rows',50);
      el.style.height = '500px';
      document.body.appendChild(el);
    }
  }
}

var PROFILER = 0;

var Loader = function(){};
Loader.priority = {
  HIGH: 0,
  NORMAL: 1,
  LOW : 2}
Loader.prototype = {
  actions: [],
  done: false,
  index: 0,
  initialize: function() {
  },
  load: function(){
    var profiler;
    var time;

    if (this.done)
      return;

    this.done = true;
    this.profiler = new Profiler();
    this.next();
  },
  next: function(label, method){
    var loader = this;
    var action = this.actions[this.index++];
    if(!action){
      this.profiler.show();
      return;
    }
    setTimeout(function(){
      var time;
      
      if (action.method != undefined) action.method();
      
      time = loader.profiler.mark(action.label);
      /*
      if (typeof console != 'undefined')
        console.log(action.label + '(' + time + ')');
      */
      loader.next();
    }, 1);
  },
  schedule: function(label, method, priority){
    var index;
    priority = (priority != undefined) ? priority : Loader.priority.LOW;

    for (index = 0; index < this.actions.length; index++){
      if (this.actions[index].priority > priority)
        break;
    }

    this.actions.splice(index, 0, {
        "label": label,
        "method": method,
        "priority": priority});
  }
}
var loader = new Loader();
loader.schedule("Scaling setup", Scaling.setup, Loader.priority.HIGH);
loader.schedule("fix ie6 background flicker", function() {
  try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {};
});
loader.schedule("rendering", function(){
  document.body.style.visibility = "visible";
});
loader.schedule("external links", setupExternalLinks);
loader.schedule("corners", function() {
  CorneredBox.setup([$("#to_food"), $("#to_household"),$("#to_affordable"),
    $("#to_offerings"), $("#to_campaigns"), $("#to_shopping"), $("#to_appie"), $("#to_assortment"),
    $("#to_main_site"), $("#to_about"), $("#to_service"), $("#to_stores"),
    $("#to_work"), $("#to_customerservice"), $("#to_delivery"),
    $("#user"), $("#cookbook_sidebar"),
    $("#cookbook_sidebar_me"), $("#recipe_info"), $("#recipe_shop_online"),
    $("#report_it")]);

  CorneredBox.setup($('.fillet'));
  CorneredBox.setup($('.block'));
  CorneredBox.setup($('.button'));
});
loader.schedule("dots (IE6)", function() {
  if (ua.ie6) {
    DottedBox.setup($("#temp_drop, #temp_drop_disabled, #section_press"));

    DottedBox.setup($(".ie6_border"));
    DottedBox.setup($(".verhaal"));
  }
});
loader.schedule("action banner", setupActionBanner);


function startLoader() {
		
}

/**
 * (IE Bugfix) Adds flashmovies to a queue for displaying at pageload.  For
 * displaying SWFObjects: showSWFObject(swfObject, "swfContainer") should be
 * used instead of the usual fo.write("swfContainer")
 */
function showSWFObject(swfObject, swfContainer) {
  loader.schedule("write swf objects", function() {
    swfObject.write(swfContainer);
  });
}
/**
 * Write the given swfObject in the given swf container.
 * When there is no swf player with the given required version available, the swfObject will
 * not be written. Instead, all html elements with class=swf_alternate are displayed and all
 * elements with class=swf_content are hidden.
 */
function writeSWFObject(swfObject, swfContainer, requiredPlayerVersion) {
	if (deconcept.SWFObjectUtil.getPlayerVersion().major >= requiredPlayerVersion) {
		loader.schedule("write swf objects", function() {
			swfObject.write(swfContainer);
		});
	} else {
		loader.schedule("swf alternate", function() {
			$('.swf_content').hide();
			$('.swf_alternate').show();
		});
	}
}

// ###################################
// ############## MENU ###############
// ###################################

var effects = new Array();
function setAnimatedHover(n, startcolor, endcolor) {
  if (!n) return;
  function hover() {
    $(n).stop(true,true).animate({backgroundColor:  endcolor},100);
    

  }
  function unhover(e) {
	  $(n).stop(true,true).animate({backgroundColor: startcolor},600,'linear',function(){
		  $(this).css({backgroundColor: ''});
	  });
  }
 

  $(n).hover(function(){hover();},function(){unhover();}).blur(function(){unhover();}).focus(function(){hover();});
}


loader.schedule("main menu", function() {
  var elBody = $(document.body);
  if (!elBody.hasClass("food")) {
    setAnimatedHover($("#to_food"), "#FFFFFF", "#f6f9ee");
  }
  if (!elBody.hasClass("household") && !elBody.hasClass("householdtips")) {
    setAnimatedHover($("#to_household"), "#FFFFFF", "#fdf9eb");
  }
  if (!elBody.hasClass("assortment")) {
    setAnimatedHover($("#to_assortment"), "#FFFFFF", "#f7ebf7");
  }
  if (!elBody.hasClass("offerings")) {
    setAnimatedHover($("#to_offerings"), "#FFFFFF", "#fcf5ed");
  }
  if (!elBody.hasClass("campaigns")) {
    setAnimatedHover($("#to_campaigns"), "#FFFFFF", "#e6f6fb");
  }
  if (!elBody.hasClass("affordable")) {
    setAnimatedHover($("#to_affordable"), "#FFFFFF", "#fcebec");
  }
  if (!elBody.hasClass("shopping")) {
    setAnimatedHover($("#to_shopping"), "#FFFFFF", "#e6f6fb");
  }
  if (!elBody.hasClass("appie")) {
    setAnimatedHover($("#to_appie"), "#FFFFFF", "#e6f6fb");
  }
  if (!elBody.hasClass("about")
      && !elBody.hasClass("overah")) {
    setAnimatedHover($("#to_about"), "#FFFFFF", "#CBEDFC");
  }
  if (!elBody.hasClass("service")
      && !elBody.hasClass("klantenservice")) {
    setAnimatedHover($("#to_service"), "#FFFFFF", "#CBEDFC");
  }
  if (!elBody.hasClass("stores")) {
    setAnimatedHover($("#to_stores"), "#FFFFFF", "#CBEDFC");
  }
  if (!elBody.hasClass("work")) {
    setAnimatedHover($("#to_work"), "#FFFFFF", "#CBEDFC");
  }
});

// This is not me / Dit ben ik niet : cookie remover

$("#to_user_switch").click(function(){
	removeCookie("ah_collected_recipe");
	return false;
});

  
  // ###################################
// ############ BANNERS #############
// ###################################

/**
Setup Actionbanner mouseover show hide
To be memorycleaned...
**/
function setupActionBanner() {


    $('#actie_banner_popup').hover(function(){$('#actie_banner_popup_mo').show();},function(){});
    $("#actie_banner_popup_mo").hover(function(){},function(){$(this).hide();}).hide();
    
}
/* lightbox handler - able to handle swf's, iframes, jpg's, gif's */

// function call to close lightbox and to remove flashcontainer
// AHLightBox.closeFlashContainer();

AHLightBox = new Object({openLightBox: false});

AHLightBox.createLightboxLinks = function() {

	// get all flash links in the primary container
	$('a.lightbox').click(function(){
		AHLightBox.createLighboxContentForLink(this);
		return false;
	});
}

AHLightBox.readLightboxParametersFromHref = function(href) {
	var parameters = new Array();
	var params = href.substr(href.lastIndexOf('#') + 1);

	var paramsArr = params.split(',');
	for (k=0; k<paramsArr.length; k++) {
		var paramArr = paramsArr[k].split('=');
		parameters[paramArr[0]] = paramArr[1];
	}

	return parameters;
}

AHLightBox.createLighboxContentForLink = function(link) {
	var url = link.href.substring(0,link.href.lastIndexOf('#'));
	var parameters = AHLightBox.readLightboxParametersFromHref(link.href);
	var hash = (parameters['id']?parameters['id']:(Math.round(Math.random()*1000)));
	var id = 'lightbox_' + hash;

	AHLightBox.createLighboxContent(id, url, parameters);
	document.location.hash = hash;
}

AHLightBox.createLighboxContent = function(foid, url, parameters) {
	

	var type = url ? url.substr(url.lastIndexOf('.') + 1).toLowerCase() : 'empty';
	type = (typeof(parameters['type'])!='undefined')?parameters['type']:type;
	
	// create lightbox
	var grayDiv = document.createElement('div');
	grayDiv.id = 'graysite';
	// set backgroundcolor
	if (parameters['fadecolor']) grayDiv.style.backgroundColor = '#' + parameters['fadecolor'];

		// remove scrollbar
	// document.body.style.overflow = 'hidden';

	document.body.appendChild(grayDiv);

	// create an close event on lightbox
	$(grayDiv).bind('click', function(){
		AHLightBox.closeLightboxContainer();
		document.location.hash = '';
		return false;
	});

	// fade in
	var opacity = (typeof(parameters['fadeopacity'])!='undefined')?parseFloat(parameters['fadeopacity']):0.8;
	
	$('body').addClass('light-boxed');
	$(grayDiv).fadeTo(500, opacity, function(){

		// if fading done, create container

    		// create flash Container
    		var fo_container = document.createElement('div');
    		fo_container.id = 'fo_' + foid;
    		fo_container.className = 'lightboxobj_container';


			// check if there is a height specified
			var winHeight = 500;
			if (parameters['height']) {
				winHeight = parameters['height'];
			} else if (parameters['voffset']) {
				winHeight = $(window).height() - (2 * parseInt(parameters['voffset']));
			}

			// check if there is a width specified
			var winWidth = 500;
			if (parameters['width']) {
				winWidth = parameters['width'];
			} else if (parameters['hoffset']) {
				winWidth = $(window).width() - (2 * parseInt(parameters['hoffset']));
			}
			var top,left;
			if (parameters['top']) {
				top = parseInt(parameters['top']) + $(window).scrollTop();
			}
			else {
				top = ($(window).height() - winHeight)/2 + $(window).scrollTop();
			}
			if (parameters['left']) {
				left = parseInt(parameters['left']) + $(window).scrollLeft();
			}
			else {
				left = ($(window).width() - winWidth)/2 + $(window).scrollLeft();
			}
    		
    		if (top < ($(window).scrollTop()+25) && !parameters['voffset']) top = ($(window).scrollTop()+25);
			if (left < ($(window).scrollLeft()+25) && !parameters['hoffset']) left = ($(window).scrollLeft()+25);

			fo_container.style.left = left + 'px';
    		fo_container.style.top = top + 'px';

    		
    		document.body.appendChild(fo_container);
    		
    		if (parameters['callback']) {
    			eval(parameters['callback'])();
    		}
    		
    		if (parameters['css']) {
    			$(fo_container).css(eval(parameters['css']));
    		}

    		AHLightBox.openLightboxContainer = fo_container.id;

			// write flash object

			switch(type) {
				case 'swf':
					if (deconcept.SWFObjectUtil.getPlayerVersion().major >= 8) {
			    	    var fo = new SWFObject(url,parameters['id'], winWidth + "px", winHeight + "px", "8");
				        fo.addParam("quality", "high");
				        fo.addParam("menu", "false");
				        fo.addParam("allowFullScreen", "false");
				        fo.addParam("allowScriptAccess","always");
				        fo.addParam("pluginspage", "http://www.macromedia.com/go/getflashplayer");
				        fo.addParam("play", "true");
				        fo.addParam("loop", "true");
				        fo.addParam("wmode", "transparent");
				        fo.addParam("devicefont", "false");
				        fo.write(fo_container.id);
					}
					break;

				case ('jpg' || 'gif'):
					var img = new Image();
					img.src = url;
					img.style.width = winWidth + 'px';
					img.style.height = winHeight + 'px';
					fo_container.appendChild(img);
					break;
					
				case ('empty'):
					break;
				
				case ('popin'):
					$.ajax({
						url: url,
						success: function(data){
							$('<div class="popin"/>').css({width: winWidth, height: winHeight}).html(data).appendTo('#primary');
						}
					});
					break;
				

				default:

					var iframe = document.createElement('iframe');
					iframe.src = url;
					iframe.style.width = winWidth + 'px';
					iframe.style.height = winHeight + 'px';
					iframe.setAttribute('frameBorder','0');
					if (parameters['iframecss']) {
						var css = eval(parameters['iframecss']);
						$(iframe).css(css);
						if (css.overflow && css.overflow == 'hidden') {
							iframe.setAttribute('scrolling','no');
						}
					}
					
					fo_container.appendChild(iframe);
					break;

			}

		if ('none' != parameters['close']) {
				$('<a class="close" href="#_close">sluiten</a>').click(function(){
					AHLightBox.closeLightboxContainer();
					document.location.hash = '';
					return false;
				}).appendTo(fo_container);
    		}

    		// ie6 fix
			grayDiv.style.height = ($('body').height() > $(window).height() ?  $('body').height() :  $(window).height()) + 40 + 'px';

	});
}

// function to close container and re-enable site
AHLightBox.closeLightboxContainer = function() {
	$('body').removeClass('light-boxed');
	$('#graysite, #'+AHLightBox.openLightboxContainer).fadeTo(300,0,function(){
		$(this).remove();
	});
}

AHLightBox.openLightBoxByHash = function() {

	var lightboxId = document.location.hash.substring(1);

	// get all lightbox links in the primary container
	$('a.lightbox').each(function(){
		var lightboxLink = $(this);
		var parameters = AHLightBox.readLightboxParametersFromHref(lightboxLink[0].href);
		var lightboxLinkId =  parameters['id'];
		if (lightboxLinkId == lightboxId) {
			AHLightBox.createLighboxContentForLink(lightboxLink[0]);
		}
	});
}

if (loader) {
	loader.schedule("createLightboxLinks", AHLightBox.createLightboxLinks);
	loader.schedule("check to open lightbox by hash", AHLightBox.openLightBoxByHash);
}
//// takeover scripts
function doTakeOver() {
	$('a.takeover').each(function(){
		var takeoverLink = $(this);
	
		var target = takeoverLink.attr('target');
		if (target && target!='') {
			var correctUserAgent = false;
			var targetUserAgents = target.split("|");
			for (var agentIdx = 0; agentIdx < targetUserAgents.length; ++agentIdx) {
				if (navigator.userAgent.toLowerCase().indexOf(targetUserAgents[agentIdx]) > -1) {
					correctUserAgent = true;
				}
			}
			if (!correctUserAgent) {
				return;
			}
		}
	
		var parameters = AHLightBox.readLightboxParametersFromHref(takeoverLink[0].href);
		var lightboxId = parameters['id'];
		var showTakeOver = true;
		if (typeof lightboxId != 'undefined') {
			setCookie('takeover_check',true,365);
			if (getCookie('takeover_check') && !getCookie('takeover_' + lightboxId)) {
				setCookie('takeover_' + lightboxId,true,365);
			} else {
				showTakeOver = false;
			}
		}
		if (showTakeOver) {
			if (parameters['force']=='true') {
				document.location.href = takeoverLink[0].href.substring(0,takeoverLink[0].href.lastIndexOf('#'));
			} else {
				AHLightBox.createLighboxContentForLink(takeoverLink[0]);
			}
		}
	});
}

loader.schedule("run takeover script", doTakeOver);

function shareThisPage() {
	$('.social-sharing-wrapper a').live('click',function(e){
		var href = $(this).attr('href');
		var shareLocation = parent ? parent.location : document.location;
		var shareUrl = escape(shareLocation.pathname + shareLocation.search + shareLocation.hash);
		shareUrl = href.replace('http://www.ah.nl/', 'http://www.ah.nl'+shareUrl);
		var w = 600;
		var h = 500;
		var left = (screen.width/2)-(w/2);
		var top = (screen.height/2)-(h/2);
		window.open(shareUrl, null,'menubar=0,resizable=1,width='+w+',height='+h
				+',left='+left+',top='+top+',screenX='+left+',screenY='+top+',status=1,toolbar=0,directories=0,scrollbars=1');

		return false;
	});	
	
}

loader.schedule("share This Page", shareThisPage);

function dataStats() {
	
	$('a[data-stats]').click(function(e){
		var a = $(this);
		sitestatTellerPage(a.attr('data-stats'));
	});
}
loader.schedule("sitestat teller based on data-stats attribute", dataStats);


function fixPngsInIE6() {
	if (!ua.ie6) {
		return;
	}
	var mayneedpngfix = $('.mayneedpngfix');
	for (var i = 0; i < mayneedpngfix.length; i++) {
		var obj = mayneedpngfix[i];
		if (obj.currentStyle.backgroundImage.match(/\.png/i) !== null) {
			var mode = 'scale';
			var bg	= obj.currentStyle.backgroundImage;
			var src = bg.substring(5,bg.length-2);
			if (obj.currentStyle.backgroundRepeat == 'no-repeat') {
				mode = 'crop';
			}
			obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')";
			obj.style.backgroundImage = 'url(/_ui/spacer.gif)';
		}
	}
}

if (ua.ie6) {
	loader.schedule("fix IE6 pngs", fixPngsInIE6);
}



function sitestatTellerPage(tellerName, asUrl){
	var referrer = document.referrer;
	if (referrer.length > 0) {
		if (referrer.lastIndexOf('/') == referrer.length - 1) {
			referrer = referrer.substring(referrer.length - 1, 0);
		}
		return sitestatWrite(tellerName, 'ns_referrer=' + escape(referrer), asUrl);
	} else {
		return sitestatWrite(tellerName, null, asUrl);
	}
}

function sitestatTellerFlash(tellerName){
	sitestatWrite(tellerName, 'ns_type=flash');
}

function sitestatWrite(tellerName, parameters, asUrl) {
	// Optional prefix
	var stats_prefix = getHtmlDataProperty('stats-prefix');
	// Optional section
	var site_section = getHtmlDataProperty('stats-site-section');
	
	if (stats_prefix && tellerName.indexOf(stats_prefix)!=0) {
		tellerName = stats_prefix + tellerName;
	}
	if (site_section && tellerName.indexOf("ah_site_section=")==-1) {
		tellerName = tellerName + "&amp;ah_site_section=" + site_section;
	}
	
	// if (tellerName.indexOf("ah_site_section=")==-1) {
	//	  myConsoleLog('*** ADD ah_site_section ***');
	// }
	
	var scheme = 'http:';
	if (typeof document.location.protocol != 'undefined') {
		scheme = document.location.protocol;
	}
	var sitestatUrl = scheme + '//nl.sitestat.com/ahold/ah/s?' + tellerName
			+ '&amp;ns__t='+(new Date()).getTime();
	if (parameters != null) {
		sitestatUrl += '&amp;' + parameters;
	}
	
	// myConsoleLog(tellerName);
	// myConsoleLog(sitestatUrl);
	
	if (asUrl) {	
		return sitestatUrl;
	}
	else {
		if (document.images){
			var sitestatImg = new Image();
			sitestatImg.src = sitestatUrl;
		} else {
	    	document.write('<img src="' + sitestatUrl + '" width="0" height="0" alt="" '
					+ 'style="position:absolute; left:-1000em; ">');
		}
	}
}

/**
 * Read data-xxx attribute from HTML tag.
 * @param property field (part after "data-") to read
 * @returns data or NULL if not found
 */
function getHtmlDataProperty(property) {
	try {
		// TODO: when new jquery in use, replace with return $('html').data(property);
		return $('html').attr('data-' + property);
	}
	catch( error ) {
		// igonre any errors
	}
	return null;
}

function myConsoleLog(message) {
	if (!(typeof console === "undefined") &&  !(typeof console.log === "undefined")) {
		console.log(message);
	}
}


