var topscrolling   = 0;
var topscrolled    = 0;
var ticker         = null;
var collapsed      = 0;
var collapseMoving = 0;
var slideContent   = null;

$(window).load(function(){
  if(window.location.hash)
  {
	var gotopage = substr(window.location.hash, 2);
	$("a[alt='" + gotopage + "']:eq(0)").click();
  }  
});

$(document).ready(function(){
  
  if(mktime() < 1308200400)
  {
    $('body').append('<a href="http://www.afas.nl/over-afas/evenementen/awards/stemmen2011/stemmen.aspx?filmid=13" class="blank afasaward"></a>');
  }
  
  $("a.jumpto").click(function(){
	$.scrollTo($("a[name='" + $(this).attr('href').substr(1) + "']"), 400);
	return false;
  });

  $("a.iframe").live('click', function(){
	$.fancybox([
		{'href'	: 'images/shop-screenshots/a.png',
			'title'	: 'Homepage: het standaard template van de webshop (kleuren naar wens)'},
		{'href'	: 'images/shop-screenshots/b.png',
			'title'	: 'Productopties kiezen: bijvoorbeeld Maat en Kleur. Deze waarden worden uit Profit gehaald.'},
		{'href'	: 'images/shop-screenshots/c.png',
			'title'	: 'Menuweergave (en een andere kleurstelling van het standaard template)'},
		{'href'	: 'images/shop-screenshots/d.png',
			'title'	: 'Geheel ander template: carousel boven (vast in beeld), gestijld menu, boven-balk, ...'},
		{'href'	: 'images/shop-screenshots/e.png',
			'title'	: 'Weergave van het winkelwagentje. Gekozen productopties, kortingscodes, last-minute aanbiedingen, ...'},
		{'href'	: 'images/shop-screenshots/f.png',
			'title'	: 'Verzendmethodes: ook dit zijn artikelen in Profit. Prijs per land en methode. '},
		{'href'	: 'images/shop-screenshots/g.png',
			'title'	: 'Webshop geheel met CSS aangepast naar wens door een van onze klanten.'},
		{'href'	: 'images/shop-screenshots/h.png',
			'title'	: 'Beheerpaneel: Vertalingen van de webshop-tekstdelen'},
		{'href'	: 'images/shop-screenshots/i.png',
			'title'	: 'Beheerpaneel: Partnerlogo\'s, branding en herkenbaarheid. Drag &amp; drop!'},
		{'href'	: 'images/shop-screenshots/j.png',
			'title'	: 'Beheerpaneel: Aanpassen van FAQ items. Drag en drop en HTML codes mogelijk (CMS)'},
		{'href'	: 'images/shop-screenshots/k.png',
			'title'	: 'Beheerpaneel: Logistieke instellingen. Verzendmethodes, verzendtriggers, betaalmethoden, etc.'},
		{'href'	: 'images/shop-screenshots/l.png',
			'title'	: 'Beheerpaneel: Vertalingen per verzendmethode'},
		{'href'	: 'images/shop-screenshots/m.png',
			'title'	: 'Beheerpaneel: Menu-beheer. Zoek artikelen (Live uit Profit) en wijs ze toe aan menu\'s (Drag &amp; Drop)'}
	], {
		'padding'			: 10,
		'transitionIn'		: 'fade',
		'transitionOut'		: 'fade',
		'speedIn'			: '300',
		'speedOut'			: '300',
		'type'              : 'image',
		'changeFade'        : 0,
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
								return '<span id="fancybox-title-over">' + title + '</span>';
							  }
	});
  });

  $("#text").mouseup(function() {
	var selection = getSelected();
	if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
	  if(olarkObj)
	  {
		olarkObj.chat.sendNotificationToOperator({body: 'Tekst geselecteerd: [ ' + selection + ' ]' });
	  }
	  $.post('/ajax.php', { 'textlog' : selection }, function(d){}, 'json');
	}
  });

  $(this).bind("contextmenu", function(e) {
	$.post('/ajax.php', { 'a' : $(window).width(), 'b' : $(window).height(), 'x': e.pageX, 'y' : e.pageY }, function(d){}, 'json');
  });

  if($(".vierluik .mail").length > 0)
  {
	activateMailform();
  }
	
  /*
	$.ajaxSetup({
	  error:function(x,e){
		if(x.status==0){
		  alert('You are offline!!\n Please Check Your Network.');
		}else if(x.status==404){
		  alert('Requested URL not found.');
		}else if(x.status==500){
		  alert('Internel Server Error.');
		}else if(e=='parsererror'){
		  alert('Error.\nParsing JSON Request failed.');
		}else if(e=='timeout'){
		  alert('Request Time out.');
		}else {
		  alert('Unknow Error.\n'+x.responseText);
		}
	  }
	});
  */

  activateLinks('');
  
  $("#top-bar").hover(function(){
    if(topscrolling < 1)
    { 
      $(this).stop().animate({ 'marginTop' : '0px' }, 300, function(){
      }).find(".shade").css({ 'height' : '5px' });
      setTimeout(function(){
        topscrolling = 0;
      }, 300);
      topscrolling = 1;
      topscrolled  = 1;
    }
  }).find(".shade").css({ 'height' : '20px' });
  
  $("div#head-menu, div#intro-container").hover(function(){
    if(topscrolling < 1 && topscrolled > 0 && olarkChatActive < 1)
    {
      $("#top-bar").stop().animate({ 'marginTop' : '-40px' }, 300, function(){
		topscrolling = 0;
      }).find(".shade").css({ 'height' : '20px' });
      topscrolled  = 0;
    }
  });

  var div = $('div#intro-container div#intro-main .buttoncontainer'),
  movediv = $('div#intro-container div#intro-main'),
  ul = $('div#intro-container div#intro-main .buttoncontainer ul'),
  ulPadding = 100;

  var divWidth = div.width();
  div.css({overflow: 'hidden'});

  var lastLi = ul.find('li:last-child');
  var isAnimating = 0;
  var nums = ul.find("li").length-6;
  var addit = -125 + (nums*45);
  var addit2 = (nums+6)*14;
  var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding + (addit);
  var ulW9 =  ulWidth/9;
  
  movediv.mousemove(function(e){
    if(isAnimating < 1 && collapseMoving < 1)
    {
      tint = (e.pageX - div.offset().left);
      if(tint > 1050)
      {
	    tint = 1050;
      }
      
      var left = (tint * (ulWidth-divWidth) / divWidth) - (addit2);
      
      var diff = div.scrollLeft() - left;
      if(diff < 0) diff = diff*-1;
      
      if(diff > ulW9)
      {
	    isAnimating = 1;
	    div.stop().animate({ 'scrollLeft' : left + 'px' }, diff/2.5, function(){
	      isAnimating = 0;
	    });
      }else{
	    div.stop().scrollLeft(left);
      }
    }
  });
  
  $(".togglemenu").click(function(){
	if(collapsed > 0)
	{
	  if($("div#content").css('top') == '0px')
	  {
		$("div#content").stop().animate({ 'top' : '-180px' }, 400);
		$("div#head-menu a.togglemenu").css({ 'backgroundPosition' : '0px -28px' });
		_log('switch_off');
		if(olarkObj)
		{
		  olarkObj.chat.sendNotificationToOperator({body: 'Menu uitgezet' });
		}
	  }else{
		$("div#content").stop().animate({ 'top' : '0px' }, 400);
		$("div#head-menu a.togglemenu").css({ 'backgroundPosition' : '0px 0px' });
		_log('switch_on');
		if(olarkObj)
		{
		  olarkObj.chat.sendNotificationToOperator({body: 'Menu aangezet' });
		}
	  }
	}
  });
      
  StartTicker();

});

function switchContent(theContent) {
  $("div#text").animate({ 'left' : '-1200px' }, 500, function(){
	$("div#content").css({ 'overflow' : 'hidden' });
	$("div#text").css({ 'left' : $(window).width() + 'px' });
	$("div#text").html(theContent);
	activateLinks('#text ');
	var newLeftPos = ($(window).width()-1200)/2;
	$("div#text").animate({ 'left' : 0 + 'px' }, 500, function(){
	  $("div#content").css({ 'overflow' : 'visible' });
	});
  });
}

function collapseOut() {
  if(collapseMoving < 1)
  {
    if(collapsed > 0)
    {
	  $("div#head-menu a.togglemenu").fadeOut('fast');
	  if($("div#content").css('top') == '0px')
	  {
		if($("div#content").is(":visible"))
		{
		  $("div#content").fadeOut(function(){
			collapse();
		  });
		}else{
		  collapse();
		}
	  }else{
		$("div#content").stop().animate({ 'top' : '0px' }, 400, function(){
		  $("div#head-menu a.togglemenu").css({ 'backgroundPosition' : '0px 0px' });
		  if($("div#content").is(":visible"))
		  {
			$("div#content").fadeOut(function(){
			  collapse();
			});
		  }else{
			collapse();
		  }
		});
	  }
    }
  }
}

function collapseIn() {
  if(collapseMoving < 1)
  {
    if(collapsed < 1)
    {
	  $("div#head-menu a.togglemenu").fadeIn('fast');
      collapse();
    }
  }  
}


function StartTicker() {
  ticker = setInterval(function(){
    var num = $("#oneliners ul li").length;
    var pos = $("#oneliners ul li").index($("#oneliners ul li.active"));
    var mt = parseInt(substr($("#oneliners ul").css('marginTop'), 1,-2));
    var newObj = $("#oneliners ul li.active").next();
    var fadeTime = 600;
  
    if(pos > num-6)
    {
	  mt = 14;
	  var newObj = $("#oneliners ul li:eq(2)");
	  fadeTime = 2000;
    }
    
    if(isIE())
    {
	  $("#oneliners ul li.active").animate({ '-ie-opacity' : '.18' }, 1000, function(){
	    $(this).removeClass('active');
	    $("#oneliners ul").animate({ 'marginTop' : '-' + (mt+88) + 'px' }, fadeTime, function(){
		  newObj.animate({ '-ie-opacity' : '1' }, 1000, function(){
		    $(this).addClass('active');
		  });
	    });
	  });
    }else{
	  $("#oneliners ul li.active").animate({ 'opacity' : '.18' }, 1000, function(){
	    $(this).removeClass('active');
	    $("#oneliners ul").animate({ 'marginTop' : '-' + (mt+88) + 'px' }, fadeTime, function(){
		  newObj.animate({ 'opacity' : '1' }, 1000, function(){
		    $(this).addClass('active');
		  });
	    });
	  });
    } 
  }, 7000);
}

function collapse(inout) {
  if(collapseMoving < 1)
  {
    collapseMoving = 1;
    if(collapsed > 0)
    {
      $("div#intro-container div#intro-main .buttoncontainer").fadeOut(300);
      $("div#intro-container div#intro-main div#carousel-guide").fadeOut(300, function(){
		$("div#intro-container div#whitefade-left, div#intro-container div#whitefade-right").fadeOut('fast');
		$("div#intro-container").animate({ 'marginTop' : '60px', 'height' : '500px' }, 300);
		$("div#head div.shade").animate({ 'marginTop' : '130px' }, 300);
		$("#oneliners").fadeIn();
		$("#gespecialiseerd").fadeIn(function(){
		  $("div#intro-main").css({ 'overflow' : 'hidden' });
		  $("div#intro-container div#intro-main div#carousel-guide").css({ 'marginTop' : '-290px', 'height' : '170px' }).show();
		  $("div#intro-container div#intro-main .buttoncontainer").css({ 'paddingTop' : '270px', 'marginTop' : '270px' }).show();
		  $("div#intro-container div#intro-main .buttoncontainer").animate({ 'marginTop' : '0px' }, 500);
		  $("div#intro-container div#intro-main div#carousel-guide").animate({ 'marginTop' : '290px' }, 500, function(){
			$("div#intro-main").css({ 'overflow' : 'visible' });
			StartTicker();
			collapsed = 0;
			collapseMoving = 0
		  });	
		});
      });
    }else{
      collapsed = 1;
      $("div#intro-container").animate({ 'marginTop' : '90px', 'height' : '150px' }, 300);
      $("div#intro-main").css({ 'overflow' : 'hidden' });
      $("div#head div.shade").animate({ 'marginTop' : '160px' }, 300, function(){
		$("div#intro-container div#intro-main div#carousel-guide").animate({ 'marginTop' : '-10px', 'height' : '160px' }, 450, function(){
		  $("div#intro-main").css({ 'overflow' : 'visible' });
		});
		$("div#intro-container div#intro-main .buttoncontainer").animate({ 'paddingTop' : '0px', 'marginTop' : '-30px' }, 550, function(){
		  collapseMoving = 0;
		  $("#content").fadeIn();
		});
		$("div#intro-container div#whitefade-left, div#intro-container div#whitefade-right").fadeIn('fast');
      });
      clearInterval(ticker);
      $("#oneliners").fadeOut();
      $("#gespecialiseerd").fadeOut();
    }
  }
}

function substr (str, start, len) {
  str += '';
  var end = str.length;
  if (start < 0) {
	start += end;
  }
  end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
  return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end);
}

function isIE() {
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function activateMailform()
{
  $("input:eq(0)").focus();
  $(".vierluik .mail form").unbind('submit').submit(function(){
	_log('contactform_submit');
	$.post('/contact-opnemen.php?ajax=1', $(this).serialize(), function(d){
	  if(d.error > 0)
	  {
		$("input, textarea").removeClass('error');
		$.each(d.field, function(a,b){
		  if(b !== '')
		  {
			if(a < 2)
			{
			  $("input[name='"+b+"'], textarea[name='"+b+"']").focus();
			}
			$("input[name='"+b+"'], textarea[name='"+b+"']").addClass('error');
		  }
		});
	  }else{
		$(".vierluik .mail form").fadeOut(function(){
		  $(this).after('<div style="display: none;"><br /><br /><br /><br /><br /><center><b>Bedankt, uw bericht is verzonden!</b></center><br /><center>U hoort zo spoedig mogelijk van ons.</center></div>').remove();
		  $(".vierluik .mail div:eq(0)").fadeIn();
		});
	  }
	}, 'json');
	return false;
  });
}

function activateLinks(addd){
  $(addd + 'a.blank, ' + addd + 'a.vcard').each(function(){
	if($(this).filter('.vcard').length < 1)
	{
	  $(this).attr('target', "_blank");
	}
	if($(this).filter('.twitter').length > 0)
	{
	  $(this).attr('target', "_blank"); 
	}
	if($(this).filter('.linkedin').length > 0)
	{
	  $(this).attr('target', "_blank"); 
	}
  });
  $(addd + "a").each(function(){
	if($(this).filter('.blank').length < 1 && $(this).filter('.vcard').length < 1 && $(this).filter('.jumpto').length < 1 && $(this).filter('.mailto').length < 1)
	{
	  if($(this).attr('href'))
	  {
		if(!isIE())
		{
		  $(this).attr('alt', $(this).attr('href')).removeAttr('href').addClass("specialhref");
		}else{
		  var preUrl = '';
		  if(ThisPage)
		  {
			preUrl = '/p/' + ThisPage;
		  }
		  $(this).attr('alt', $(this).attr('href')).attr('href', '#/' + $(this).attr('href')).addClass("specialhref");
		}
	  }
	}
  });
  $(addd + "a").click(function(){
	if($(this).filter(".togglemenu").length < 1)
	{
	  $(".buttoncontainer ul li a.active").removeClass('active');
	  $("#head-menu a.active").removeClass('active');
	}
	$(this).addClass('active');
	$("a[alt='" + $(this).attr('alt') + "']").addClass('active');
  });
  
  $(addd + "a.specialhref").click(function(){
	// document.location.href = $(this).attr('alt');
	newhash = '/' + $(this).attr('alt');
	if(newhash == '/' ||  newhash == '//') newhash = '';
	window.location.hash = newhash;
    if($(this).filter(".revertCollapse").length > 0)
    {
      collapseOut();
      $(".homelink").addClass('active');
      $("#content").fadeOut();
	  if(olarkObj)
	  {
		olarkObj.chat.sendNotificationToOperator({body: 'Terug op de homepage' });
	  }
    }else{
	  // loader //
	  if(substr($(this).attr('alt'),0,2) == 'p/')
	  {
		var getpage = substr($(this).attr('alt'), 2);
		$.get('/static/' + getpage, { 'ajax' : '1' }, function(d){
		  pageTracker._trackPageview("/p/" + getpage);
		  _log('p/' + getpage);
		  
		  if(olarkObj)
		  {
			olarkObj.chat.sendNotificationToOperator({body: 'Pagina: http://www.ipublications.net/p/' + getpage });
		  }
		  
		  if(collapsed > 0)
		  {
			if(ThisPage !== getpage)
			{
			  switchContent(d);
			}
		  }else{
			$("div#text").html(d);
			activateLinks('#text ');
			collapseIn();
		  }
		  ThisPage = getpage;
		  if(getpage == 'contact.html')
		  {
			setTimeout(function(){
			  activateMailform();	
			},1100);
			setTimeout(function(){
			  if($("#text li.route iframe").length < 1)
			  {
				$("#text li.route h5").after('<iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.nl/maps?f=q&amp;source=s_q&amp;hl=nl&amp;geocode=&amp;q=iPublications+BV,+Zielhorsterweg+79,+Amersfoort&amp;sll=52.669397,5.509644&amp;sspn=8.323437,12.832031&amp;ie=UTF8&amp;hq=iPublications+BV,&amp;hnear=Zielhorsterweg+79,+3813+Amersfoort&amp;ll=52.175533,5.404278&amp;spn=0.006295,0.006295&amp;output=embed"></iframe>');
			  }
			},1300);
		  }
		}, 'html');
	  }
    }
  });

  $("#loginform").submit(function(){
	if($("input[name='pin']").length > 0)
	{
	  _log('sso_requestsubmit');
	  $("p.error").fadeOut(function(){
		$(this).remove();
	  });
	  $("p.login:eq(0)").parent().before('<p class="error agree">Bedankt, uw aanvraag is verzonden. Wij nemen zo spoedig mogelijk contact met u op.<br /></p>');
	  $("p.error").hide().fadeIn();
	  $("form input").val('').blur();
	  $.post('/contact-opnemen.php', $("form").serializeArray(), function(d){}, 'json');
	  return false;
	}else{
	  _log('inlogform_submit');
	  $("p.error").fadeOut(function(){
		$(this).remove();
	  });
	  $("p.login:eq(0)").parent().before('<p class="error">De opgegeven gebruikersnaam en/of wachtwoord waren onjuist.<br /></p>');
	  $("p.error").hide().fadeIn();
	  return false;
	}
  });
}

function _log(Ttxt)
{
  $.post('/ajax.php', { 'log' : Ttxt }, function(d){}, 'json');	
}

function getSelected() {
  if(window.getSelection) { return window.getSelection(); }
  else if(document.getSelection) { return document.getSelection(); }
  else {
	  var selection = document.selection && document.selection.createRange();
	  if(selection.text) { return selection.text; }
	  return false;
  }
  return false;
}

function mktime() {
    var d = new Date(),
        r = arguments,
        i = 0,
        e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'];

    for (i = 0; i < e.length; i++) {
        if (typeof r[i] === 'undefined') {
            r[i] = d['get' + e[i]]();
            r[i] += (i === 3); // +1 to fix JS months.
        } else {
            r[i] = parseInt(r[i], 10);
            if (isNaN(r[i])) {
                return false;
            }
        }
    }
    r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0);
    d.setFullYear(r[5], r[3] - 1, r[4]);
    d.setHours(r[0], r[1], r[2]);
   return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0);
}

;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
