var speed = 800;
var delay = 3000;
var interval;
var c = 0; // Current Image
var p = 0; // Previous Image
var t = 0; // Total Images
var first = true;
var obj;
var loop=false;
var device;

jQuery.easing.def = "easeInOutQuad";


$(document).ready(function() {	
	window.scrollTo(0, 1);
	
	if(swfobject.getFlashPlayerVersion().major < 10 && !isiDevice()){	
		initSlideShow();		
	}
	
	else if(isiDevice()){
		var a=document.getElementsByTagName("a");
		for(var i=0;i<a.length;i++)
		{
		    a[i].onclick=function()
		    {
		        window.location=this.getAttribute("href");
		        return false
		    }
		}
		
		device = 'mobile';
		initSlideShow();
		$('#images').find('.caption').each(function(){
			$(this).html('<p>'+$(this).text().replace(/&#160;/g,' ')+'</p>');
		});
	}
	
	else if($('.pg_home').length!=0){
		initSlideShow();
	}
	
	else{
		if($('#images').length!=0){
			var theString = ieInnerHTML($('#images').html().replace(/&amp;/g,'#38;'),true).split('"').join('#34;').replace(/#38;nbsp;/g,'#160;');
			
			// console.log(theString);
				
			var params = {
				quality: "high",
				scale: "noscale",
				wmode: "window",
				allowscriptaccess: "always",
				bgcolor: "#fff"
			};
			var flashvars = {
				imagesML: theString
			};
			var attributes = {
				id: "images",
				name: "images"
			};	

			swfobject.embedSWF(siteURL+"images/SwfCycle.swf", "images", "100%", "100%", "10.0.0", "expressInstall.swf", flashvars, params, attributes);

			resizeImagesHolderDiv();

			$(window).resize(resizeImagesHolderDiv);

			$('#pause').click(function(){
				if($(this).html()=="Pause"){
					$('#images')[0].pause();
					$(this).html("resume");
				}
				else{
					$('#images')[0].playShow();					
					$(this).html("Pause");
				}
			});

			$('#next').click(function(){
				$('#images')[0].pause();
				$('#pause').addClass('paused').html('resume');
				$('#images')[0].next();
			});

			$('#previous').click(function(){
				$('#images')[0].pause();
				$('#pause').addClass('paused').html('resume');
				$('#images')[0].prev();
			});
	    }
	}
	
	$('.credit').hover(function(){
		$(this).animate({
			'width': '157px',
			backgroundPosition: '(0 0)'
		}, 200);
	}, function(){
		$(this).animate({
			'width': '12px',
			backgroundPosition: '(-155px 0)'
		}, 200);
	});
	
});

function ieInnerHTML(string, convertToLowerCase) {
 var zz = string
     ,z = zz.match(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/g);

  if (z){
    for (var i=0;i<z.length;i++){
      var y
          , zSaved = z[i]
          , attrRE = /\=[a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9]+[?\s+|?>]/g;
      z[i] = z[i]
              .replace(/(<?\w+)|(<\/?\w+)\s/,function(a){return a.toLowerCase();});
      y = z[i].match(attrRE);//deze match

       if (y){
        var j = 0
            , len = y.length
        while(j<len){
          var replaceRE = /(\=)([a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9]+)?([\s+|?>])/g
              , replacer = function(){
                  var args = Array.prototype.slice.call(arguments);
                  return '="'+(convertToLowerCase ? args[2].toLowerCase() : args[2])+'"'+args[3];
                };
          z[i] = z[i].replace(y[j],y[j].replace(replaceRE,replacer));
          j++;
        }
       }
       zz = zz.replace(zSaved,z[i]);
     }
   }
  return zz;
 }

function resizeImagesHolderDiv(){
	
	if ($(window).height()-162-19-15 > 475 && $(window).width()-200-19 > 675) {
		$("#images").css({width:$(window).width()-200-19});
		$("#images").css({height:$(window).height()-162-19-15});
	};
	

}

function preloadImages(el){
	var images = new Array(), loadedimages=0;
	var postaction=function(){}
	var arr=(typeof arr!="object")? [arr] : arr;
	
	function imageloadpost(){        	 
		// // console.log('W: '+images[loadedimages].width+' - H: '+images[loadedimages].height);			
		loadedimages++
		if (loadedimages==arr.length){
            postaction(images)
        }
    }	

	el.find('img').each(function(i){
		images[i] = new Image();
		images[i].src = $(this).attr('src')+'?c='+Math.floor(Math.random()*200846518000);
		images[i].onload=function(){   imageloadpost(); }
		images[i].onerror=function(){  imageloadpost(); }
	});	
	
	return {
		done:function(f){
			postaction=f || postaction
		}
	}	
}


function initSlideShow(device){
	
	preloadImages($('#images li')).done(function(){
		$('#footer').fadeIn(speed);
		
		if ($('#images li').length>1) slideshowInit(obj=$('#images ul li'), delay, loop=true, true, device); // Multiple Images
		else $('#images li').fadeIn(speed); // Only 1 Image
	});
}

function slideshowInit(localObj, delay, loop, controls){
	if(controls) controller($('#previous'),$('#next'),$('#pause'), obj); // If Slideshow has controls.
	t = obj.length;			
	play(delay);
}

function play(delay){	
	// Load the First image. Update variables.	
	if(first){
		if (device=='mobile') {	
			
			obj.eq(c).delay(250).removeClass('fadeOut').addClass('fadeIn');
		}	
		else{
			obj.eq(c).delay(250).stop(true,true).fadeIn(speed);
		}		
		
		p=0;
		++c;
		first=false;
	}
	
	// Then start interval
	if(t>1){
		interval = setInterval(updateGallery, 3000);
	}
}

function updateGallery(dir){
	
	if (dir==undefined) dir="next";
	if(p!=null) {
		if(dir=='next'){
			
			if (device=='mobile') {	
				obj.eq(p).stop(true,true).removeClass('fadeIn').addClass('fadeOut');
				obj.eq(c).stop(true,true).removeClass('fadeOut').addClass('fadeIn');
			}	
			else{
				obj.eq(p).stop(true,true).fadeOut(0);
				obj.eq(c).stop(true,true).fadeIn(speed);
			}
			
							
			p = c;
			c = ((t - 1)==c) ? 0 : ++c;
		}
		if(dir=='prev'){				
			c = p;
			if(p==0) { p=(t-1); }
			else{ --p;}
			
			if (device=='mobile') {	
				obj.eq(c).stop(true,true).removeClass('fadeIn').addClass('fadeOut');
				obj.eq(p).stop(true,true).removeClass('fadeOut').addClass('fadeIn');
			}	
			else{
				obj.eq(c).stop(true,true).fadeOut(0);
				obj.eq(p).stop(true,true).fadeIn(speed);
			}
			
			
		}
	}
}


function controller(prev,next,pause,obj){	
	prev.click(function(e){
		dir = 'prev';
		e.preventDefault();
		pause.html('resume').addClass('paused');
		prevImage(obj);		
	});
	
	next.click(function(e){
		dir = 'next';
		e.preventDefault();
		pause.html('resume').addClass('paused');
		nextImage(obj);		
	});
	
	pause.click(function(e){
		e.preventDefault();
		$(this).toggleClass('paused');
		if($(this).hasClass('paused')){
			$(this).html('resume');
			stopGallery();
		}
		else{
			$(this).html('pause');
			
			stopGallery();
			nextImage();
			play(delay);
		}		
	});
}

function stopGallery(){ 
	clearInterval(interval); 
}

function nextImage(){	
	stopGallery();
	checkAnimationStatus('next');
}

function prevImage(){
	stopGallery();
	checkAnimationStatus('prev');
}

function checkAnimationStatus(dir){		
	$('#previous, #next, #pause').click(function(e){ e.preventDefault();	});
	var wait = setInterval(function(){
		if(!obj.eq(c).is(":animated") ) {		
			clearInterval(wait);
			updateGallery(dir);
		}
	}, 5);
}

function isiDevice(){
    return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1) || (navigator.platform.indexOf("iPad") != -1));
}

/**
 * @author Alexander Farkas
 * v. 1.02
 */
(function($) {
	$.extend($.fx.step,{
	    backgroundPosition: function(fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
			}
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

           function toArray(strg){
               strg = strg.replace(/left|top/g,'0px');
               strg = strg.replace(/right|bottom/g,'100%');
               strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
               var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
               return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
           }
        }
	});
})(jQuery);

/*! Respond.js v1.0.1pre: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs  */
(function(e,h){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=h;if(h){return}var u=e.document,r=u.documentElement,i=[],k=[],p=[],o={},g=30,f=u.getElementsByTagName("head")[0]||r,b=f.getElementsByTagName("link"),d=[],a=function(){var B=b,w=B.length,z=0,y,x,A,v;for(;z<w;z++){y=B[z],x=y.href,A=y.media,v=y.rel&&y.rel.toLowerCase()==="stylesheet";if(!!x&&v&&!o[x]){if(y.styleSheet&&y.styleSheet.rawCssText){m(y.styleSheet.rawCssText,x,A);o[x]=true}else{if(!/^([a-zA-Z]+?:(\/\/)?)/.test(x)||x.replace(RegExp.$1,"").split("/")[0]===e.location.host){d.push({href:x,media:A})}}}}t()},t=function(){if(d.length){var v=d.shift();n(v.href,function(w){m(w,v.href,v.media);o[v.href]=true;t()})}},m=function(G,v,x){var E=G.match(/@media[^\{]+\{([^\{\}]+\{[^\}\{]+\})+/gi),H=E&&E.length||0,v=v.substring(0,v.lastIndexOf("/")),w=function(I){return I.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+v+"$2$3")},y=!H&&x,B=0,A,C,D,z,F;if(v.length){v+="/"}if(y){H=1}for(;B<H;B++){A=0;if(y){C=x;k.push(w(G))}else{C=E[B].match(/@media ([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1;k.push(RegExp.$2&&w(RegExp.$2))}z=C.split(",");F=z.length;for(;A<F;A++){D=z[A];i.push({media:D.match(/(only\s+)?([a-zA-Z]+)(\sand)?/)&&RegExp.$2,rules:k.length-1,minw:D.match(/\(min\-width:[\s]*([\s]*[0-9]+)px[\s]*\)/)&&parseFloat(RegExp.$1),maxw:D.match(/\(max\-width:[\s]*([\s]*[0-9]+)px[\s]*\)/)&&parseFloat(RegExp.$1)})}}j()},l,q,j=function(E){var v="clientWidth",x=r[v],D=u.compatMode==="CSS1Compat"&&x||u.body[v]||x,z={},C=u.createDocumentFragment(),B=b[b.length-1],w=(new Date()).getTime();if(E&&l&&w-l<g){clearTimeout(q);q=setTimeout(j,g);return}else{l=w}for(var y in i){var F=i[y];if(!F.minw&&!F.maxw||(!F.minw||F.minw&&D>=F.minw)&&(!F.maxw||F.maxw&&D<=F.maxw)){if(!z[F.media]){z[F.media]=[]}z[F.media].push(k[F.rules])}}for(var y in p){if(p[y]&&p[y].parentNode===f){f.removeChild(p[y])}}for(var y in z){var G=u.createElement("style"),A=z[y].join("\n");G.type="text/css";G.media=y;if(G.styleSheet){G.styleSheet.cssText=A}else{G.appendChild(u.createTextNode(A))}C.appendChild(G);p.push(G)}f.insertBefore(C,B.nextSibling)},n=function(v,x){var w=c();if(!w){return}w.open("GET",v,true);w.onreadystatechange=function(){if(w.readyState!=4||w.status!=200&&w.status!=304){return}x(w.responseText)};if(w.readyState==4){return}w.send(null)},c=(function(){var v=false;try{v=new XMLHttpRequest()}catch(w){v=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return v}})();a();respond.update=a;function s(){j(true)}if(e.addEventListener){e.addEventListener("resize",s,false)}else{if(e.attachEvent){e.attachEvent("onresize",s)}}})(this,(function(f){if(f.matchMedia){return true}var e,i=document,c=i.documentElement,g=c.firstElementChild||c.firstChild,h=!i.body,d=i.body||i.createElement("body"),b=i.createElement("div"),a="only all";b.id="mq-test-1";b.style.cssText="position:absolute;top:-99em";d.appendChild(b);b.innerHTML='_<style media="'+a+'"> #mq-test-1 { width: 9px; }</style>';if(h){c.insertBefore(d,g)}b.removeChild(b.firstChild);e=b.offsetWidth==9;if(h){c.removeChild(d)}else{d.removeChild(b)}return e})(this));

