isActive = true;
overCurrentImage = false; 
textScrollable = true;

function getidofblogpost(element) {
  var id = element.attr('id');
  return parseInt(id.substring(8, id.length));
}

function nextblogpost() {
  element = $('.blogpostvisible');
  id = getidofblogpost(element);
  nextid = id+1;
  nextelement = $('#blogpost'+nextid);
  if (nextelement) {
    alert(element.children('entry:first'));
    element.children('entry:first').removeClass('flexcroll');
    element.removeClass('blogpostvisible').addClass('blogpostinvisible');
    nextelement.removeClass('blogpostinvisible').addClass('blogpostvisible');
    nextelement.children('entry:first').addClass('flexcroll');
    fleXenv.updateScrollBars();
  }
  return false;
}

function prevblogpost() {
  element = $('.blogpostvisible');
  id = getidofblogpost(element);
  nextid = id+1;
  prevelement = $('#blogpost'+previd);
  if (prevelement) {
    element.children('entry:first').removeClass('flexcroll');
    element.removeClass('blogpostvisible').addClass('blogpostinvisible');
    prevelement.removeClass('blogpostinvisible').addClass('blogpostvisible');
    prevelement.children('entry:first').addClass('flexcroll');
    fleXenv.updateScrollBars();
  }
  return false;
}

function gopromo() {
  var url = '/promotiecode/' + $('#promopopupcode').val();
  window.location = url;
  return false;
}

function checkcontactform() {
  naam = $('#contactnaam').val();
  email = $('#email').val();
  telefoon = $('#telefoon').val(); 

  if (naam=="") {
    alert("Vul wel een naam in graag.");
    $('#contactnaam').focus();
    return false;    
  }
  
  if (email=="") {
    alert("Vul wel een emailadres in graag.");
    $('#email').focus();
    return false;    
  }
  
  if(telefoon=="") {
    alert("Vul wel een telefoonnummer in graag.");
    $('#telefoon').focus();
    return false;    
  }
  
  var atpos  = email.indexOf("@");
  var dotpos = email.lastIndexOf(".");
  if ( (atpos < 1) || (dotpos < (atpos+2)) || ((dotpos+2) >= email.length) ) {
    alert("Het emailadres is niet geldig.");
    $('#email').focus();
    return false;
  }
  
  return true;
}

function gocontact() {
  if (checkcontactform())
    document.forms["contactform"].submit();
  return false;
}

function promocodeinput() {
  if (window.event && window.event.keyCode == 13)
    gopromo();
}

function IsNumeric(input){
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}

function submitPromo(returnvalue) {
  naam = $('#promoname').val();
  email = $('#promoemail').val();
  telefoon = $('#promotelephone').val();
  promocode = $('#promopromocode').val();

  if ((naam=="<jouw naam>")||(naam=="")) {
    alert("Vul wel een naam in graag.");
    $('#promoname').focus();
    return false;    
  }
  
  if ((email=="<jouw@email.adres>")||(email=="")) {
    alert("Vul wel een emailadres in graag.");
    $('#promoemail').focus();
    return false;    
  }
  
  if ( (telefoon=="<jouw telefoonnummer>")||(telefoon=="")) {
    alert("Vul wel een telefoonnummer in graag.");
    $('#promotelephone').focus();
    return false;    
  }
  
  var atpos  = email.indexOf("@");
  var dotpos = email.lastIndexOf(".");
  if ( (atpos < 1) || (dotpos < (atpos+2)) || ((dotpos+2) >= email.length) ) {
    alert("Het emailadres is niet geldig.");
    $('#promoemail').focus();
    return false;
  }

  if ( (telefoon.length!=10) || (!IsNumeric(telefoon))) {
    alert("Het telefoonnummer is niet geldig. Het dient uit 10 cijfers te bestaan zonder spaties of streepjes.");
    $('#promotelephone').focus();
    return false;
  }
  
  $.get('/promosubmit.php',{'name':naam, 'email': email, 'telephone': telefoon, 'promocode':promocode}, function(data) {
    if ($('#downloadp')) {
      $('#downloadp').removeClass('invalid').addClass('valid');
      alert('Bedankt voor het invullen. Je kunt nu de bestanden downloaden.');
    }
    if (returnvalue) window.location = 'http://sevendwarfs.nl/bedankt'; else window.location = 'http://www.sevendwarfs.nl/promodownload.php?code='+promocode;
  });
  
  return false;
}

function checkDownload() {
  returnvalue = $('#downloadp').hasClass('valid');
  if (!returnvalue) alert('Je dient eerst je naam, emailadres en telefoonnummer hieronder in te vullen!');
  return returnvalue;
}

function clearName() {
  naam = $('#promoname').val();
  if (naam=="<jouw naam>") $('#promoname').val("");
}

function clearEmail() {
  email = $('#promoemail').val();
  if (email=="<jouw@email.adres>") $('#promoemail').val("");
}
			
function clearTelephone() {
  email = $('#promotelephone').val();
  if (email=="<jouw telefoonnummer>") $('#promotelephone').val("");
}
			
function onBlur() {
	isActive = false; 
};
function onFocus(){
	isActive = true; 
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
	document.onfocusin = onFocus;
	document.onfocusout = onBlur;
} else {
	window.onfocus = onFocus;
	window.onblur = onBlur;
}

function loaded(el) {
	$(el).attr('data-loaded', 1);
}

function isiPad(){
    return navigator.userAgent.match(/iPad/i) != null;
}

// Ensures Images are always centered in the available space.
function resizeImages(forceLeft) {
	var width, height, newWidth, newHeight, ratio, targetWidth, targetHeight, newLeft, newTop;
	$('#rightBlock #photoBlock img').each(function() {
		// Target
		targetWidth = $('#photoBlock').width();
		targetHeight = $('#photoBlock').height()-20;

		// Image Width
		if (this.currentStyle && $(this).attr('width') == 0) {
			ieW = this.currentStyle.width;
			ieH = this.currentStyle.height
			width = ieW.substring(0, (ieW.length - 2));
			height = ieH.substring(0, (ieH.length - 2));
		} else {
			width = $(this).attr('width');
			height = $(this).attr('height');
		}

		newWidth = width;
		newHeight = height;

		// Check Width
		if (width > targetWidth) {
			ratio = targetWidth / width;
			newWidth = targetWidth;
			newHeight = Math.round(ratio * newHeight);
		}

		// Check Height
		if (newHeight > targetHeight) {
			ratio = targetHeight / newHeight;
			newHeight = targetHeight;
			newWidth = Math.round(ratio * newWidth);
		}

		// Calculate Left
		if ( ! forceLeft) {
			newLeft = ((targetWidth - newWidth) / 2) + 'px';
		}

		newTop = ((targetHeight - newHeight) / 2)+'px';
		// Apply
		$(this).css({
			'width' : newWidth+'px',
			'height' : newHeight+'px',
			'left': newLeft,
			'top': newTop
		});
	});
}

// Slideshow
function slideShow() {
	// Specify Next Image
	var totalImages = homeImages.length;
//	$('#debug').html(totalImages);
	var current = homeCurrent;

	if ( ! window.isActive) {
		clearTimeout(timeoutID);
		timeoutID = setTimeout("slideShow()", 1000);
		return;
	}

	if ( ! $(homeImages[current]).attr('data-loaded')) {
		clearTimeout(timeoutID);
		timeoutID = setTimeout("slideShow()", 200);
		return;
	} else {
		clearTimeout(timeoutID);
	}

	// If there is a caption - slide that out first.
	if ($('#caption').length) {
		clearTimeout(timeoutID);
		$('#caption').stop().animate({bottom:'-150px'}, 500, function() {
			$('div#caption').remove();
			return slideShow();
		});
		return;
	}

	// Switch Image
	if ($('#photoBlockInner img:visible').length) {
		$('#photoBlockInner img:visible').fadeOut(500, function() {
			$(homeImages[current]).fadeIn(500, function() {
				if ($(homeImages[current]).attr('alt') && !($(homeImages[current]).hasClass('noalttext'))) {
					$('div#photoBlockInner').append('<div id="caption"><span>'+$(homeImages[current]).attr('alt')+'</span></div>');
					$('div#caption').animate({bottom:0}, 500);
				}
			});
		});
	} else {
		$(homeImages[current]).fadeIn(500, function() {
            if ($(homeImages[current]).attr('alt') && !($(homeImages[current]).hasClass('noalttext'))) {
				$('div#photoBlockInner').append('<div id="caption"><span>'+$(homeImages[current]).attr('alt')+'</span></div>');
				$('div#caption').animate({bottom:0}, 500);
			}
		});
	}

	if (homeCurrent == (homeImages.length - 1)) {
		homeCurrent = 0;
	} else {
		homeCurrent++;
	}

	clearTimeout(timeoutID);
	if (totalImages > 1) {
		timeoutID = setTimeout("slideShow()", 5000);
	}
}
		
// Slideshow
function gallerySlideShow(photo, go) {
	// Specify Next Image
	var totalImages = homeImages.length;
	var current = (photo != undefined) ? photo : homeCurrent;

	if ( ! window.isActive) {
		clearTimeout(timeoutID);
		timeoutID = setTimeout("gallerySlideShow("+photo+")", 1000);
		return;
	}

	if ( ! $(homeImages[current]).attr('data-loaded')) {
		clearTimeout(timeoutID);
		timeoutID = setTimeout("gallerySlideShow("+photo+")", 200);
		return;
	} else {
		clearTimeout(timeoutID);
	}

	// If there is a caption - slide that out first.
	if ($('#caption').length) {
		$('#caption').animate({bottom:'-150px'}, 500, function() {
			$('#caption').remove();
			return gallerySlideShow(photo);
		});
		return;
	}

	// Switch Image
	if ($('#photoBlockInner img:visible').length) {
		$('#photoBlockInner img:visible').fadeOut(500, function() {
			$(homeImages[current]).fadeIn(500, function() {
                if (($(homeImages[current]).attr('alt').length > 0) && !($(homeImages[current]).hasClass('noalttext'))) {
					$('#photoBlockInner').append('<div id="caption"><span>'+$(homeImages[current]).attr('alt')+'</span></div>');
					$('#caption').animate({bottom:0}, 500);
				}
			});

			// Manipulate thumbs
			$("#photoSlider a, #photoSlider img").removeClass('current');

			id = $(homeImages[current]).attr('id');
			$('a[rel="'+id+'"]').addClass('current');
		});
	} else {
		$(homeImages[current]).fadeIn(500, function() {
            if (($(homeImages[current]).attr('alt').length > 0) && !($(homeImages[current]).hasClass('noalttext'))) {
				$('#photoBlockInner').append('<div id="caption"><span>'+$(homeImages[current]).attr('alt')+'<span></div>');
				$('#caption').animate({bottom:0}, 500);
			}
		});

		// Manipulate thumbs
		$("#photoSlider a, #photoSlider img").removeClass('current');

		id = $(homeImages[current]).attr('id');
		$('a[rel="'+id+'"]').addClass('current');
	}

	if ( photo == undefined ) {
		if (homeCurrent == (homeImages.length - 1)) {
			homeCurrent = 0;
		} else {
			homeCurrent++;
		}

		clearTimeout(timeoutID);
		if (totalImages > 1) {
			timeoutID = setTimeout("gallerySlideShow()", 4000);
		}
	} else {
		if (photo == (homeImages.length - 1)) {
			homeCurrent = 0;
		} else {
			homeCurrent = photo+1;
		}

		clearTimeout(timeoutID);
		timeoutID = 0;
		$('#startStop').html('start');
	}
}

function prevText() {
  if( parseInt($(".scrollabletextInner").css('top'))>=0 ) {
    return false;
  }
  $(".scrollabletextInner").animate({"top": "+=100px"});
  return false;
}

function nextText() {
  stInTop = parseInt($(".scrollabletextInner").css('top'));
  stInHeight = parseInt($(".scrollabletextInner").height());
  stHeight = parseInt($(".scrollabletext").height());
  if ((stHeight-stInTop)<=stInHeight) {
    $(".scrollabletextInner").animate({"top": "-=100px"});
  }
  return false;
}

function hideTextSliderControls() { 
  if ($('.scrollabletextInner').attr('scrollable')==1) {
    $('.scrollabletextInner').attr('scrollable',0);
    $('.scrollabletext').animate({'height': '+=140px'});
    $('#textcontrols').fadeOut(500);
  }
}

function showTextSliderControls() {
  if ($('.scrollabletextInner').attr('scrollable')==0) {
    $('.scrollabletextInner').attr('scrollable',1);
    $('.scrollabletext').animate({'height': '-=140px'});
    $('#textcontrols').fadeIn(500);
  }
}

function getParagraphsHeight(el) {
  height = 0;
  el.children('p').each( function() {
    height+=$(this).height();
  });
  return height;
}

function checkTextSliderControls() {
  var sb = $('.scrollabletextInner');
  sb.css('height','100%');
  h = getParagraphsHeight(sb);

  var tb = $('#textBlock');  
//  $('#debug').html(''+tb.height()+' '+h);
  if ((tb.height()-140)<h) {
  //  $('#debug').append(' show ' + textScrollable);
    showTextSliderControls();
  } else {
    //$('#debug').append(' hide ' + textScrollable);
    hideTextSliderControls();
  }
}

function showSliderControls() {
	var imageCount = $('#sliderPack img').length;
	var sliderHeight = ((58 + 10) * (imageCount / 3)) + 60; // Thumb Height + Padding * Image Rows + space for controls

	if (imageCount < 2) {
		$('#move #startStop').hide();
	}


	if (($('#leftBlock').height() - 220 - 60) > sliderHeight) {
		$('#move #left, #move #right').css('visibility', 'hidden');
	} else {
		$('#move #left, #move #right').css('visibility', 'visible');
	}
}


jQuery(document).ready(function(){

  if ($('.promocode')) {
    $('.promocode').hover( function() {
      $('#promopopupcode').focus();
    });
  }
  
  if ($('#photoBlockInner').length>0) {
    $('body').append('<div id="photonavigator">next</div>');
    $('#photonavigator').fadeOut(1);
  }
    
	// Resize On Start Up
	$('.fifty').css('width', '50%');
	resizeImages($('.alignLeft').length);
	if ($(window).height() > $('#contentBlock').height()) {
		$('#contentBlock').css('margin-top', (($(window).height() - $('#contentBlock').height() + 20) / 2)+'px');
	}

	// Resize on Resize
	$(window).resize(function() {
		$('.fifty').css('width', '50%');
		if ($('#rightBlock img').length) {
			resizeImages($('.alignLeft').length);
		}
		if ($(window).height() > $('#contentBlock').height()) {
			$('#contentBlock').css('margin-top', (($(window).height() - $('#contentBlock').height() + 20) / 2)+'px');
		}
        if ($(".scrollabletextInner").length) checkTextSliderControls();
	});
	


	// Gallery Controls
	if ($('#sliderPack').length) {
		showSliderControls();
		$(window).resize(function() {
			showSliderControls();
		});
	}

	$('#startStop').click(function() {
		if ($(this).html() == 'stop') {
			clearTimeout(timeoutID);
			timeoutID = 0;
			$(this).html('start');
		} else {
			gallerySlideShow();
			$(this).html('stop');
		}

		return false;
	});

	// Get the slideshow running.
	if ($('.slide').length && $('#rightBlock img').length > 1) {
		timeoutID = 0;
		homeCurrent = 0;
		homeImages = $('#photoBlockInner img');
		slideShow();
	} else {
		if ( ! $('#photoSlider').length) {
			$('#photoBlock img').first().fadeIn();
		}
	}

	// Prepare Backgrounds
	$('#nav a:not(#nav li li a)').each(function() {
		$(this).prepend('<div class="bg" style="background-color:' + $(this).attr('data-background') + ';display:none"></div>');
		var span = $(this).find('span').html();
		$(this).find('span').css('visibility', 'hidden');
		$(this).prepend('<span style="position:absolute">'+span+'</span>');
	});

	if ( ! isiPad()) {
		$('#nav a:not(#nav li li a)').hover(function() {
			$(this).find('div').fadeIn(300);
			$(this).css('color', $(this).attr('data-rollover'));
		}, function() {
			if ( ! $(this).hasClass('selected') && ! $(this).parent().find('ul').is(':visible')) {
				$(this).find('div').fadeOut(300);
				$(this).css('color', $(this).attr('data-color'));
			}
		});

        $('#nav li ul').each( function() {
          $(this).children().last().parent().css('border-bottom', '1px solid #B7BF5E');
        });
		$('#nav li li a').css('color', $(this).attr('data-color'));
		$('#nav li li a').hover(function() {
			$(this).css('color', $(this).attr('data-rollover'));
		}, function() {
			if ( ! $(this).hasClass('selected')) {
				$(this).css('color', $(this).attr('data-color'));
			}
		});
	}

	$('#nav a.selected').css('color', $('#nav a.selected').attr('data-rollover')).find('div').show();

	var parent = $('#nav li').has('.selected').find('a').first();
	if (parent.length == 1) {
		$(parent).addClass('selected').css('color', $('#nav a.selected').attr('data-rollover')).find('div').show();
	}

	$('#nav li li a.selected').css('color', $('#nav li li a.selected').attr('data-rollover'));
	//$('#nav li li a.selected').css('color', '#000');

	/**
     * End Menu
	 */

	/**
     * Main Menu
	 */
	$('#nav li a').click(function() {
		if ($(this).attr('href') == '#') {
			$(this).parent().find('ul').toggle(50);
			if (isiPad() && $(this).parent().find('ul:visible').length) {
				$(this).css({
					'background' : $(this).attr('data-background'),
					'color' : $(this).attr('data-rollover')
				});
			}

			return false;
		}
	});

	if ($('.sliderInner').length) {
		timeoutID = 0;
		homeCurrent = 0;
		homeImages = $('#photoBlockInner img');
		gallerySlideShow();

    $("body").mousemove(function(e){
      var cur = $('#photoBlockInner img:visible');
      if (cur) {

        var photonav = $("#photonavigator");
        if (photonav) {
          var offset = cur.offset();
          var offsetLeft = offset.left;
          var offsetTop = offset.top;
          var width = cur.width();
          var height = cur.height();
          
          var x = e.pageX - offsetLeft;
          var y = e.pageY - offsetTop;

          var hw = width/2;
          
          //$('#debug').html(''+x+","+y+" - "+width+","+height+" - "+offsetLeft+","+offsetTop+" - "+e.pageX+","+e.pageY);

          if ( (x<0) || (x>width) || (y<0) || (y>height) ) {
            try {
              photonav.fadeOut(50);
            } catch (err) { }
            $('body').css('cursor', 'default');
            overCurrentImage = false; 
          } else {
            try {
              photonav.fadeIn(50);
            } catch (err) { }
            $('body').css('cursor', 'none');
            overCurrentImage = true; 
          }

          if (x>hw) {
            $("#photonavigator").html('&rArr;');
          } else {
            $("#photonavigator").html('&lArr;');
          }
          x+=offsetLeft;
          y+=offsetTop;
          $("#photonavigator").css('left',''+ x +'px');
          $("#photonavigator").css('top',''+ y +'px');
        }
      }
    });
    
    $("body").click(function(e) {
      if (overCurrentImage) {

        var cur = $('#photoBlockInner img:visible');
        if (cur) {
          var offsetLeft = cur.offset().left;
          var width = cur.width();
        
          var x = e.pageX - offsetLeft;
        
          var hw = width/2;

          var photoid = parseInt($(".current").attr('rel').substring(5,8));
          var photocount = $('#photoBlockInner img').length;

          if (x>hw) {
            photoid+=1;
              if (photoid>photocount)
                photoid=1;
          } else { 
            photoid-=1;
            if (photoid<=0)
              photoid=photocount;
          }

          gallerySlideShow(photoid-1);
          clearTimeout(timeoutID);
        }
      }
    });
	}

  $(".sliderInner a").click(function(){
    if ($(this).attr("class") != "current") {
      gallerySlideShow($('#'+$(this).attr('rel')).index());
      clearTimeout(timeoutID);
    } else {
      clearTimeout(timeoutID);
    }
    return false;
  });
    

  if ($("#photoSlider")) {
    $("#photoSlider").css("overflow", "hidden");
    var slider=0;
    var sliderOriginal=0;
    
    $("#left").click(function(){
			var imageCount = $('#sliderPack img').length;
			slider = ((57 + 10) * Math.ceil(imageCount / 3)) - $("#photoSlider").height();
			if ($('.sliderInner').css('top') != 'auto') {
				var pos = $('.sliderInner').css('top');
				slider = slider - pos.substring(1, (pos.length-2));
			}

			//slider = $(".sliderInner").height()-$("#photoSlider").height();
			sliderOriginal = slider;

			if ( ! $(this).hasClass('off')) {
				if (slider>100) {
					$(".sliderInner").animate({"top": "-=100px"});
					slider = slider - 100;
				} else {
					$(".sliderInner").animate({"top": "-="+slider+"px"});
					slider = 0;
				};
			}
			if (slider==0) {
				$("#left").addClass("off");
			};
			if (slider>0) {
				$("#right").removeClass("off");
			};
			return false;
		});

		$("#right").click(function(){
			var imageCount = $('#sliderPack img').length;
			slider = ((58 + 10) * (imageCount / 3)) - $("#photoSlider").height();
			if ($('.sliderInner').css('top') != 'auto') {
				var pos = $('.sliderInner').css('top');
				slider = slider - pos.substring(1, (pos.length-2));
			}
			//slider = $(".sliderInner").height()-$("#photoSlider").height();
			sliderOriginal = slider;

			slider = slider + 100;
			if (slider < sliderOriginal) {
				$(".sliderInner").animate({"top": "+=100px"});
			} else {
				$(".sliderInner").animate({"top": "0px"});
				slider=sliderOriginal;
			};
			if (slider > 0) {
				$("#left").removeClass("off");
			};
			if (slider == sliderOriginal) {
				$("#right").addClass("off");
			};
			return false;
		});
	};
	
	if ($("#jouwalbum").length) {
	  $("#shoot").focus();
	}
	
	if ($(".scrollabletextInner").length) {
      $(".scrollabletextInner").attr('scrollable',0);
      $(".textBlockInner").append('<div id="textcontrols"><a href="#" onclick="return prevText();" id="prevtext">&uArr;</a><a href="#" onclick="return nextText()" id="nexttext">&dArr;</a></div>');
      checkTextSliderControls();
 	}

  var rankableCode = '<iframe src="http://rankable.com/w.php?tag=7dwarfsphoto&amp;type=btn-count&amp;color=dark" height="20" width="107" scrolling="no" frameborder="0"></iframe>';
  var fbCode = '<iframe src="http://www.facebook.com/plugins/like.php?app_id=214884988550144&amp;href=http://www.facebook.com/pages/Sevendwarfs-Photography/220061188008642&amp;send=false&amp;layout=button_count&amp;width=100&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; margin-left:10px; width:120px; height:21px;" allowTransparency="true"></iframe>';
  var twitterCode = '<a href="http://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
//  $('#afterload').append(rankableCode);
  if ($('#afterload')) {
    $('#afterload').append(fbCode);
    $('#afterload').append(twitterCode);
  }
  
  if ($('.flexcroll')) {
    fleXenv.initByClass("flexcroll");
  }
  
  if ($('#contactnaam')) { $('#contactnaam').focus(); }


  	
});

