/*!
 * 	Jani Komulainen
 * 	jani@kelvin.fi
 */
 
/*
CSS Browser Selector v0.3.5 (Feb 05, 2010)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors

function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',o='opera',h=document.documentElement,b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);
*/

// html.no-js -> html.js
var elem = document.documentElement;
elem.className = elem.className.replace(/\bno-js\b/,'js');

// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject
(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);

/*
 * doTimeout - v0.4 - 7/15/2009
 * http://benalman.com/projects/jquery-dotimeout-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Licensed under the MIT license
 * http://benalman.com/about/license/
 */

(function($){var a={},c="doTimeout",d=Array.prototype.slice;$[c]=function(){return b.apply(window,[0].concat(d.call(arguments)))};$.fn[c]=function(){var e=d.call(arguments),f=b.apply(this,[c+e[0]].concat(e));return typeof e[0]==="number"||typeof e[1]==="number"?this:f};function b(l){var m=this,h,k={},n=arguments,i=4,g=n[1],j=n[2],o=n[3];if(typeof g!=="string"){i--;g=l=0;j=n[1];o=n[2]}if(l){h=m.eq(0);h.data(l,k=h.data(l)||{})}else{if(g){k=a[g]||(a[g]={})}}k.id&&clearTimeout(k.id);delete k.id;function f(){if(l){h.removeData(l)}else{if(g){delete a[g]}}}function e(){k.id=setTimeout(function(){k.fn()},j)}if(o){k.fn=function(p){o.apply(m,d.call(n,i))&&!p?e():f()};e()}else{if(k.fn){j===undefined?f():k.fn(j===false);return true}else{f()}}}})(jQuery);

function urlencode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str + '').toString();

    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

function utf8_encode (argString) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "",
        start, end, stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.slice(start, end);
            }
            utftext += enc;
            start = end = n + 1;
        }
    }

    if (end > start) {
        utftext += string.slice(start, stringl);
    }

    return utftext;
}

function base64_encode (data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        enc = "",
        tmp_arr = [];

    if (!data) {
        return data;
    }

    data = this.utf8_encode(data + '');

    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1 << 16 | o2 << 8 | o3;

        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;
        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);

    enc = tmp_arr.join('');

    switch (data.length % 3) {
    case 1:
        enc = enc.slice(0, -2) + '==';
        break;
    case 2:
        enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}
function base64_decode (data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_decode
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] == 'function') {
    //    return btoa(data);
    //}
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        dec = "",
        tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do { // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

        o1 = bits >> 16 & 0xff;
        o2 = bits >> 8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec);

    return dec;
}


function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 1102.614
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,
        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = r instanceof Array,
        sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
 
    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

function isNumber(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
}

$(document).ready(function() { // jQuery

// detect iphone/ipad
if(navigator.userAgent.match(/iPhone/i)) { $("html").addClass("mobile"); }
if(navigator.userAgent.match(/Android/i)) { $("html").addClass("android").addClass("mobile"); }
if(navigator.userAgent.match(/iPad/i)) { $("html").addClass("ipad").addClass("mobile"); }

//$("body").addClass("showgrid");

if('localStorage' in window && window['localStorage'] !== null){
	$('html').addClass('local-storage');
	
	if($.jStorage.get('jcart_qty')) {
		var minimart_qty = $.jStorage.get('jcart_qty');
		if(minimart_qty > 0) {
			$('#header .minimart span').before('<span class="qty"> ('+minimart_qty+')</span>');
		}
	}
		
	if($.jStorage.get('lightbox')) {
		var lightbox_qty = $.jStorage.get('lightbox').length;
		if(lightbox_qty > 0) {
			$('#header .lightbox span').before('<span class="qty"> ('+lightbox_qty+')</span>');
		}
	}
}

$("footer ul li a, a.anchor").each(function() {
	$(this).append("<span> &raquo;</span>");
});

$("body#news ul.pagination li").each(function() {
	$(this).addClass("title");
});
if($("body#news").length) {
	if($("li.previous").length < 1) {
		$('li.page-total').css("margin-left","235px");
	}
	var tots = $('li.page-total').html();
	var new_tots = str_replace('Page ', '', tots);
	$('li.page-total').html(str_replace(' of ', '<span class="separator"> / </span>', new_tots));
}

// fix input placeholder=""
var i = document.createElement("input");
// Only bind if placeholder isn't natively supported by the browser
if (!("placeholder" in i)) {
    $("input[placeholder]").each(function () {
        var self = $(this);
        self.val(self.attr("placeholder")).bind({
            focus: function () {
                if (self.val() === self.attr("placeholder")) {
                    self.val("");
                }
            },
            blur: function () {
                var label = self.attr("placeholder");
                if (label && self.val() === "") {
                    self.val(label);
                }
            }
        });
    });
}

// open links in new window
$("a.blank").attr("target", "_blank");

// link back
$('a.back').click(function() {
	history.back();
	return false;
});

// easing for animation
// from http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js
$.easing.custom = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
}

if($("body#home").length) {
	$('#featured').orbit({
		//"animation" : "custom-slide",
		"animation" : "horizontal-push",
		animationSpeed: 230,
		bullets: true,
		captions: true,
		captionAnimation: 'none', 
		//captionAnimationSpeed: 200,
		//afterSlideChange: function(){
//			$("#content .orbit-caption").
			//log($(this).activeSlide);
		//} 
	});
	$('.slider-nav').delegate('span.left, span.right', 'click', function() {
		$(this).blur().addClass("focus").doTimeout(64, function() {
			$(this).removeClass("focus");
		})
	});
}

// toggler
$("a.toggler").addClass('toggler-off');
$('#footer #categories, #footer #connect, #footer #login').hide();
$.fn.toggler = function(div) 
{		
	$(div).slideToggle(175);
	
	if($(this).is('.toggler-on') ) {
      $(this).removeClass('toggler-on').addClass('toggler-off');
    } else {
      $(this).removeClass('toggler-off').addClass('toggler-on');
    }
    return false;
};

$("#footer a.toggler").click(function() 
{
	$(this).toggler($(this).attr("href"));
	return false;
});
	
	
// jQuery SmoothScroll
// from http://blog.medianotions.de/en/articles/2009/smoothscroll-for-jquery
$('a.target[href*=#], a.toggler-off').bind("click", function() {
    
	// make sure it's the same location      
	   if(location.pathname.replace(/^\//,'')==this.pathname.replace(/^\//,'') && location.hostname==this.hostname && this.hash.replace(/#/,'')) {
	      // get parameters
	      var hash=this.hash;
	      var target=$(hash).offset().top;
	      
	      // animate to target and set the hash to the window.location after the animation
	    
	      $.doTimeout(300, function(){ // wait a second
	    	//console.log("hammertime!");
	    	$("html:not(:animated),body:not(:animated)").animate({ scrollTop: target }, 525, "custom", function() { /*location.hash=hash;*/ });
		  });
	      // cancel default click action
	      return false;
	   }
});


/*
$("a.fancy").fancybox({
	'transitionIn'	:	'fade',
	'transitionOut'	:	'fade',
	'speedIn'		:	600, 
	'speedOut'		:	200, 
	'width'			:	$(window).width(),
	'height'		:	$(window).height()-100,
	'overlayShow'	:	true,
	'overlayColor'	:	'#333',
	'overlayOpacity'	:	'0.85',
	'hideOnContentClick'	:	false
});
*/

var imgInd = 1;
var imgCnt = 0;
var timeout = false;
var animationTimes = 700;
if($('html.mobile').length) var animationTimes = 200;

//$(function(){

	$('#scroller li').each(function() {
		imgCnt = imgCnt+1;
		$(this).css("width", $(this).width()+3 + "px").attr("id","s"+imgCnt);
		$(this).children("img,video").attr("id","img"+imgCnt);
	});
	
	$('#scroller li video').each(function() {
		$(this).parent().css("width", Number($(this).attr("width"))+3 + "px");
	});
	
/*
	$('#scroller li img').click(function(){
		var me = $(this);
		if(me.attr("id").length <= 2) return;
		var ind = getImgInd(me);
		imgInd = ind + 1;
		scrollToImg(ind + 1, true);
	});
*/	
	$('#scroller-nav .tip_trigger_next, #scroller-nav-text .next, #scroller-nav-text .next1, #scroller-nav-text .next2, #scroller-nav-text .next3').bind("click", function(){
		nextImg();
		return false;
	});

	$('#scroller-nav .tip_trigger_prev, #scroller-nav-text .prev').bind("click", function(){
		prevImg();
		return false;
	});
	
//});

function getImgInd(imgObj){
	if(imgCnt <= 0) return;
	return parseInt(imgObj.attr("id").replace("s", "")) - 1;
}

$('html').keydown(function(eve){
	if (eve.keyCode == '37') {
		$("#scroller li .work-info").animate({ opacity: 0 }, 300);
		prevImg();
	}else if(eve.keyCode == '39') {
		$("#scroller li .work-info").animate({ opacity: 0 }, 300);
		nextImg();
	}else if(eve.keyCode == '35') {
		lastImg();
	}else if(eve.keyCode == '36') {
		firstImg();
	}

});


if($("html.mobile").length) {	// enable touchwipe

	$.getScript('http://www.pekkafinland.fi/js/jquery.touchwipe.1.1.1.js', function() {
  		//alert('Load was performed.');
  		
  		// remove navigation so it doesn't interfere
  		$("#scroller-nav").remove();
  		
  		$("#scroller").touchwipe({
        wipeLeft: function() {
            //$("#imagegallery").cycle("next");
            nextImg();
            $("#scroller li .work-info").animate({ opacity: 0 }, 300);
            //alert("next");
        },
        wipeRight: function() {
            //$("#imagegallery").cycle("prev");
            prevImg();
            $("#scroller li .work-info").animate({ opacity: 0 }, 300);
            //alert("prev");
        },
        min_move_x: 225,
    	min_move_y: 20000
   	 });
	});
}

function nextImg(){
	if(imgCnt <= 0) return;
	if(imgInd >= imgCnt) return;
	//imgInd++;
	imgInd = Number($("li.active").attr("id").replace("s", ""));
	imgInd++;
	scrollToImg(imgInd, true);
}
function prevImg(){
	if(imgCnt <= 0) return;
	//if(imgInd <= 1) return;
	//imgInd--;
	imgInd = Number($("li.active").attr("id").replace("s", ""));
	imgInd--;
	//scrollToImg(imgInd, true);
	if(imgInd > 0) scrollToImg(imgInd, true);
}
function firstImg(){
	if(imgCnt <= 0) return;
	imgInd = 1;
	scrollToImg(1, true);
}
function lastImg(){
	if(imgCnt <= 0) return;
	imgInd = imgCnt;
	scrollToImg(imgCnt, true);
}

function scrollToImg(ind, anim, addr){
	
	if(imgCnt <= 0) return;
	
	var img = $('#scroller li:nth-child(' + (ind) + ')');
	var img2 = $('#scroller li:nth-child(' + (ind + 1) + ') img');

	$('#scroller li img').removeClass('curimg');
	img2.addClass('curimg');

	if(ind <= 1){
		//$('#scroller-nav .prev').animate({opacity: "0"}, animationTimes);
		$('#scroller-nav .prev, #scroller-nav-text .prev').addClass("disabled").removeClass("enabled");
		$(".tip_prev").hide();
	} else {
		//$('#scroller-nav .prev').animate({opacity: "1"}, animationTimes);
		$('#scroller-nav .prev, #scroller-nav-text .prev').removeClass("disabled").addClass("enabled");
	}

	if(ind >= imgCnt){
		//$('#scroller-nav .next').animate({opacity: "0"}, animationTimes);
		$('#scroller-nav .next, #scroller-nav-text .next, #scroller-nav .tip_trigger_next').addClass("disabled").removeClass("enabled");
		$(".tip_next").hide();
	} else {
		//$('#scroller-nav .next').animate({opacity: "1"}, animationTimes);
		$('#scroller-nav .next, #scroller-nav-text .next, #scroller-nav .tip_trigger_next').removeClass("disabled").addClass("enabled");
	}
	
	var previousWidths = 0;
	$("#scroller li").slice(0,ind).each(function() {
		previousWidths = previousWidths + $(this).width();
		//log($(this).eq());
	});
	
	$("#scroller-index .num").html(ind);
	
	// change facebook share data
	/*
	$("meta[property=og\\:image]").attr("content", $("#thumbnails img").eq(ind-1).attr("src"));
	if($("#biography p").eq(0).length) {
		$("meta[property=og\\:description]").attr("content", $("#biography p").eq(0).html());
	}
	*/
	
	var le = Math.floor(previousWidths-img.width());
	
	//alert(img + '\n' + img.offset().left + '\n' + le + '\n' + ind);	
	
	
	$('#scroller li').each(function(){

		var _ind = getImgInd($(this));
		if(ind != (_ind + 1)) {
			//if($("html.no-csstransforms").length) $(this).animate({opacity: "0.25"}, animationTimes);
			$(this).attr("class","inactive");
		} else {
			//if($("html.no-csstransforms").length) $(this).animate({opacity: "1"}, animationTimes);
			$(this).attr("class","active");
			/*
			if($(this).children("video").length) {
				log("has video!");
			}
			*/
		}
	});
	
	if(anim){
		if($('html.mobile').length) {
			$('.imagecontainer').stop().animate({scrollLeft: le}, animationTimes, "linear");
		} else {
			$('.imagecontainer').stop().animate({scrollLeft: le}, animationTimes, "custom");
		}
	} else {
		$('.imagecontainer').stop().animate({scrollLeft: le}, 650);
		
		// play video if scrolled from thumbnail
		if($('#scroller li#s'+ind+' video').length) {
			$('#scroller li#s'+ind+' video').trigger('play');
		}
	}
	
	
	if($('#scroller li#s'+ind+' video').length) {
		//log("video");
		$('#scroller li#s'+ind).addClass('has-video');
		$("#scroller-nav .prev").attr("style","height: 415px;");
		$("#scroller-nav .next1, #scroller-nav .next2").attr("style","height: 0px; overflow: hidden;");
		$("#scroller-nav .next3").attr("style","width: 205px; margin-left: 970px;");
	} else {
		$("#scroller-nav .prev, #scroller-nav .next1, #scroller-nav .next2, #scroller-nav .next3").removeAttr("style");
	}
	
	if(addr) {
		// don't change window hash
	} else {
		// update url
		if(window.history && window.history.replaceState) {
			var data = { foo: "bar" }
			history.replaceState(data,"trololo","#"+ind);
		}
	}
	
	// INFO tooltip
	if($("#scroller li#s"+ind+" .work-info").length) {
    	$("a.info").fadeIn();
		$(".tip_info").html($("#scroller li#s"+ind+" .work-info").html()).hide();
	} else {
    	$("a.info").fadeOut();
	}
	// lightbox button 
	if($("#scroller li#s"+ind).attr('data-defer-src')) {
    	$("a.lightbox-add").fadeIn();
	} else {
    	$("a.lightbox-add").fadeOut();
	}
	
	// Stop all video if playing
	$('#scroller li video').trigger('pause');
	
	// Flash, so we need to load swf and hide the placeholder image
	if($("#scroller li#s"+ind+"").attr("data-flash") == "true") {
		if($("#scroller li#s"+ind+" .swf").hasClass('swf-loaded')) {
			//log("cool, already loaded")
		} else {
			swf_id = $("#scroller li#s"+ind+"").children('.swf').attr('id');
			swf_src =  $("#scroller li#s"+ind+"").children('.swf').attr('data-swf-defer-src');
			swf_w =  $("#scroller li#s"+ind+"").children('.swf').attr('data-width');
			swf_h =  $("#scroller li#s"+ind+"").children('.swf').attr('data-height');
			//log(swf_id);
			$('#'+swf_id).delay(1200).flash(
			{
				swf: swf_src,
				width: swf_w,
				height: swf_h,
				wmode: 'transparent'
			});
			$("#scroller li#s"+ind+" .swf").addClass('swf-loaded');
			//log("loaded");
		}
	}
	
	var current_elm = $("#scroller li#s"+ind); 
	$("#content h1#author").html('<a href="' + current_elm.attr("data-href") + '">' + current_elm.attr("data-author") + '</a>');
	
	/*
		Lazy loader for images
	*/
	
	var lazyLoader = true;
	// pos browser(s)
	if($("html.opera").length) {
		lazyLoader = false;
		// replace animation with something far worse
		$("section#portfolio").css("overflow","hidden")
		$('.imagecontainer').animate({left: "-"+le}, 10, "linear");
	}
	
	var lazyAmount = 2;
	var lazyLt = Number(ind)+(lazyAmount);
	var lazyGt = Number(ind)-(1);
	var lazyPrev = Number(ind)-(2);
	//log(lazyGt);
//	log(lazyPrev);
	
	if(lazyLoader) {
		//load first image
		
		$('#scroller .img:eq('+(ind-1)+')').each(function(){
			//log($(this).parent("li").attr("id"));
			if($(this).hasClass('loaded') == false) {
				$(this).attr('src', $(this).parents('li').attr('data-defer-src')).addClass('loaded');
				//log('Loaded: '+$(this).parent("li").attr("id"));
			}
			//log($(this).parent('div').attr('data-swf-defer-src'));
		});
		
		$('#scroller .img:eq('+lazyGt+')').each(function(){
			//log($(this).parent("li").attr("id"));
			if($(this).hasClass('loaded') == false) {
				$(this).attr('src', $(this).parents('li').attr('data-defer-src')).addClass('loaded');
				//log('Loaded: '+$(this).parent("li").attr("id"));
			}
			//log($(this).parent('div').attr('data-swf-defer-src'));
		});
		//load next images
		$('#scroller .img:lt('+lazyLt+'):gt('+lazyGt+')').each(function(){
			//log($(this).parent("li").attr("id"));
			if($(this).hasClass('loaded') == false) {
				$(this).attr('src', $(this).parents('li').attr('data-defer-src')).addClass('loaded');
				//log('Loaded: '+$(this).parent("li").attr("id"));
			}
		});
		// load prev image
		if(ind > 3) {
			$('#scroller .img:eq('+lazyPrev+')').each(function(){
				//log($(this).parent("li").attr("id"));
				if($(this).hasClass('loaded') == false) {
					$(this).attr('src', $(this).parents('li').attr('data-defer-src')).addClass('loaded');
					//log('Loaded: '+$(this).parent("li").attr("id"));
				}
			});
			
		}
	}  else {	// no lazyloader

		$("#scroller .img").each(function() {
			$(this).attr('src', $(this).parents('li').attr('data-defer-src')).addClass('loaded');
			//alert($(this).parent('li').attr('data-defer-src'));
		});
		$(".imagecontainer").css("width", "90000px");
	}
	
}

$("#scroller li:first").addClass("first");
$("#scroller li:last").addClass("last");

if($("#scroller").length) {

	// check if new location hash exists and is numeric
	if(window.location.hash != "") {
		var _hash = window.location.hash.substr(1);
		//log(_hash);
		if(isNumber(_hash)) {
			if(_hash.length > 3) {
				var _hashid = $("#scroller li[data-id="+ _hash +"]").attr("id").substr(1);
				//log(_hashid);
				scrollToImg(_hashid,false,false);
				// autoplay video
				if($('#scroller li[data-id='+ _hash +'] video').length) {
					$('#scroller li[data-id='+ _hash +'] video').trigger('play');
				}
			} else {
				scrollToImg(_hash,false,false);
			}
		}
	} else {
		scrollToImg(1,true,true);	// init
	}
}

$("body#illustrators #thumbnails a, body#cgi #thumbnails a, body#creative-agencies #thumbnails a").click(function() {
	var id = $(this).attr("rel").replace("s", "");
	scrollToImg(id);
	$("html body").animate({ scrollTop: $("#header").height() }, 200);
	return false;
});
/*
$(".tabs a").click(function() 
{
	$(".tabs a").removeClass("active");
	$(this).addClass("active");
	$(".tab-content").hide();
	$("#"+$(this).attr("rel")).fadeIn();
	//log($("#"+$(this).attr("rel")));
	return false;
});
*/
$('.tabs a').click(function() {
  
  var clicked_el = $(this);
  var clicked_target = $("#"+$(this).attr("rel"));
  var anim_height = clicked_target.height();
  $(".tab-content").hide();
  
  $('.tabs-wrapper').animate({
    height: anim_height
  }, 175, function() {
    // Animation complete.
    $(".tabs a").removeClass("active");
	clicked_el.addClass("active");
	
	clicked_target.fadeIn();
  });
  return false;
});

$('#biography').hide();
//$('#content .tabs-wrapper').attr("style", "min-height: " + ($('#thumbnails').height()) + "px")

// position footer to the bottom on short pages
function fixFooter() { 
	
	var used_height = $("div#header").height() + $("div#footer").height();
	var min_height = 200 + used_height;
	//var min_height = 600;
	//log(used_height);
	var avail_height = $(window).height() - used_height;
	
	if($(window).height() > min_height) {
		var target_height = avail_height;
		$("div#content").css("min-height", (avail_height - 94) + "px");
	} else {
		$("div#content").css("min-height", "400px");
	}
}
var resizeTimer = null;
$(window).bind('resize', function() {
   if (resizeTimer) clearTimeout(resizeTimer);
   resizeTimer = setTimeout(fixFooter, 100);
});
fixFooter();


// Tooltips
// http://www.sohtanaka.com/web-design/simple-tooltip-w-jquery-css/

var tip; // say what?
//var tip = $(".tip_trigger.next .tip");

$("#scroller-nav").livequery(function(){ 
    // use the helper function hover to bind a mouseover and mouseout event 
        $(this).children("div").hover(function() { 
               
            //Caching the tooltip and removing it from container; then appending it to the body
			tip = $(this).find('.tip').remove();
			$('body').append(tip);
			//tip.show(); //Show tooltip
		
			imgInd = Number($("#scroller li.active").attr("id").replace("s", ""));
			imgLast = $("#scroller li").length;
			
			if($(this).hasClass("tip_trigger_prev") && imgInd > 1) 			tip.fadeIn(500);
			if($(this).hasClass("tip_trigger_next") && imgInd < imgLast) 	tip.fadeIn(500);
		
		}, function() { 
               
            if( typeof(tip) != "undefined") {
				tip.hide().remove(); //Hide and remove tooltip appended to the body
				$(this).append(tip); //Return the tooltip to its original position
			}   
                
		}); 
    }, function() { 
        // unbind the mouseover and mouseout events 
        $(this) 
            .unbind('mouseover') 
            .unbind('mouseout'); 
    }).delegate("div", "mousemove", function(e) {
    
		if( typeof(tip) != "undefined") {
			  //if($(this).hasClass("next")) var offset = 40;
			  //var mousex = (e.pageX + 1); //Get X coodrinates
			  //log(e.pageX + 20 + ',' + mousex);
			  var mousex = e.pageX + 20; //Get X coodrinates
		    var mousey = e.pageY + 10; //Get Y coordinates
			  //var mousey = e.pageY - 28; //Get Y coordinates
			  var tipWidth = tip.width(); //Find width of tooltip
			  var tipHeight = tip.height(); //Find height of tooltip
		
			 //Distance of element from the right edge of viewport
			  var tipVisX = $(window).width() - (mousex + tipWidth);
			  var tipVisY = $(window).height() - (mousey + tipHeight);
		
			if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
				//mousex = e.pageX - tipWidth - 20;
				$(this).find('.tip').css({  top: mousey, left: mousex });
			} if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
				//mousey = e.pageY - tipHeight - 10;
				tip.css({  top: mousey, left: mousex });
			} else {
				tip.css({  top: mousey, left: mousex });
			}
		}
});
$("#scroller-nav div").click(function() {
	$("span.tip").addClass("focus").doTimeout(64, function() {
		$(this).removeClass("focus");
	});
});

var tipp;
$("#content .tip_info, #scroller .work-info").removeClass('hide');

$(".tip_trigger").hover(function(){
    //$(".tip_info").html($("#scroller li.active").attr("data-info"));
    /*
    tipp = $(this).find('.tip_info').remove();
	$('body').append(tipp);
	tipp.show();
	*/
	
	$("#scroller li.active .work-info").animate({ opacity: 1 }, 200);

}, function() {
   
   $("#scroller li.active .work-info").animate({ opacity: 0 }, 200);
   
   /*
    if( typeof(tipp) != "undefined") {
		tipp.hide().remove(); //Hide and remove tooltip appended to the body
		$(this).append(tipp); //Return the tooltip to its original position
	}
	*/
/*	
}).mousemove(function(e) {
	if( typeof(tipp) != "undefined") {
	    var mousex = e.pageX + 20; //Get X coodrinates
	    var mousey = e.pageY + 20; //Get Y coordinates
	    var tipWidth = tipp.width(); //Find width of tooltip
	    var tipHeight = tipp.height(); //Find height of tooltip
		mousey = mousey - (80 + tipHeight);
		mousex = mousex - (tipWidth/2);
		
	    //Distance of element from the right edge of viewport
	    var tipVisX = $(window).width() - (mousex + tipWidth);
	    //Distance of element from the bottom of viewport
	    var tipVisY = $(window).height() - (mousey + tipHeight);
	
	    if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
	        mousex = e.pageX - tipWidth - 20;
	    } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
	        mousey = e.pageY - tipHeight - 20;
	    }
	    if($("html.ff3").length) mousey = mousey - 40;
	    
	    //Absolute position the tooltip according to mouse position
	    tipp.css({  top: mousey, left: mousex });
	}
*/
}).click(function(e) {
	
	if($('html.mobile').length) {	// substitute mouseovers with click
/*
    	tipp = $(this).find('.tip_info').remove();
		$('body').append(tipp);
		tipp.show();
		if( typeof(tipp) != "undefined") {
			tipp.css({  top: "630px", left: "585px" });
		}
*/
		
		$("#scroller-nav .next3").hide();
		$("#scroller li.active .work-info").animate({ opacity: 1 }, 200);
		
		/*
		$('.tip').click(function() {
			if( typeof(tipp) != "undefined") {
				tipp.hide().remove(); //Hide and remove tooltip appended to the body
				$(this).append(tipp); //Return the tooltip to its original position
			}
		});
		*/
	
	} else {
		return false;
	}
});	

if($('html.mobile').length) {	// info box close button for mobile
	$("#scroller .work-info").append('<a href="" class="close">Close</a>');
	
	$("#scroller .work-info .close").bind("click", function() {
		$("#scroller li.active .work-info").animate({ opacity: 0 }, 200);
		$("#scroller-nav .next3").show();
		return false;
	});
}

$("body#contact-us form#freeform").submit(function(){  

    var error = false;
   // $("div.error").fadeOut();

    if ($("input#name").val() == "" || $("input#email").val() == "") {
		error = "Please fill in all applicable fields.";
	}
    if(error) {
    	//$('.error').remove();
    	if(!$("p.error").length) {
    		$("form#freeform").parent('div').append('<p class="error prepend-top">' + error + '</p>');
    	}
    	return false;
    } else {
		$("form#freeform").submit();    
    }
	return false;
});

/*
	Playlist functions
*/


$('a.lightbox-add').click(function() {
	if($('html.local-storage').length) {

		if($('#scroller li.active').hasClass('added-to-lightbox')) {
			// don't add this again, lol
		} else {
			
			var _id = $("#scroller li.active").attr("data-id");
			var _thumb = $("#scroller li.active").attr("data-thumb");
			var _detail = $("#scroller li.active").attr("data-defer-src");
			var _author = $("#scroller li.active").attr("data-author");
			
			var vals = new Array(_id, _thumb, _detail, _author);
			var data = $.jStorage.get('lightbox');
			if(data != null) {
				data[data.length] = vals;	// add to array
			} else {
				var data = new Array(vals);
			};
			$.jStorage.set('lightbox', data);
			//log(data);
			$('#scroller li.active').addClass('added-to-lightbox');
			//$('#header .lightbox .qty').html()
			
			if($('#header .lightbox span.qty').length) {
				$('#header .lightbox span.qty').html(' ('+$.jStorage.get('lightbox').length+')');
			}  else {
				$('#header .lightbox span').before('<span class="qty"> ('+$.jStorage.get('lightbox').length+')</span>');
			}
		}
		return false;
	}
});

if($('body#lightbox').length) {	// list all

	var index = $.jStorage.index();
	var lbs = $.jStorage.get('lightbox');
	var download_str = "";
	
	$('#content ul.lightbox-items').hide();
	
	for (var i=0, len=lbs.length; i<len; ++i ){
		_val = $.jStorage.get('lightbox')[i];
		$('#content ul.lightbox-items').append('<li class="span-1 left" id="'+_val[0]+'"><a href="'+_val[2]+'" class="fancy" rel="gruppe"><img src="'+_val[1]+'" width="225" height="150" alt="" class="img" /><h2 class="title">'+_val[3]+'</h2></a><span class="close"><a href="javascript:;" data-id="'+[i]+'" data-key="'+_val[0]+'">Remove</a></span></li>');
		download_str = download_str += _val[2]+'|';
	}
	$('#content ul.lightbox-items').fadeIn();
	
	if(lbs.length) {
		$('#content p.empty').hide();
		$('#content a.zip-link').removeClass('hide');
		//var url = $('head base').attr("href");
		$('#content a.zip-link').attr("href", '../zip/'+base64_encode(download_str));
	} else {
		$('#content p.empty').removeClass('hide');
	}
	
	$("a.fancy").fancybox({
		'transitionIn'	:	'fade',
		'transitionOut'	:	'fade',
		'speedIn'		:	300, 
		'speedOut'		:	200, 
		'overlayShow'	:	true,
		'hideOnContentClick' : false,
		'hideOnOverlayClick' : true,
		'showCloseButton' : true,
		'enableEscapeButton' : true,
		'cyclic' : true,
		'autoScale' : false,
		'overlayColor' : '#1d1d1d',
		'overlayOpacity' : 0.2,
		'centerOnScroll' : true,
		'showNavArrows' : true
	});
	
	$("ul.listing li .close a").hover(function() {
		$(this).parent('.close').addClass('active');
	}, 
	function() {
		$(this).parent('.close').removeClass('active');
	}).
	click(function() {	// remove lightbox item
	
		var current = new Array($.jStorage.get('lightbox'));
		var id = Number($(this).attr('data-id'));
		var key = Number($(this).attr('data-key'));
		//current[0].splice(id,1);
		var listItem = document.getElementById(key);
		var offset = $("ul.lightbox-items li").index(listItem);
		current[0].splice(offset,1);
		
		_updated = current;
		$.jStorage.set('lightbox', _updated[0]);
		//log(_updated[0]);
		//log('length: ' + _updated[0].length);		
		//log($(this).attr('data-id'));
		
		$(this).parents('li').fadeOut(600).doTimeout(20, function() {
			$(this).remove();
		});
		var download_str = "";
		for (var i=0, len=_updated[0].length; i<len; ++i ){
			log(_updated[0][i]);
			_val = $.jStorage.get('lightbox')[i];
			download_str = download_str += _val[2]+'|';
		}

		var url = $('head base').attr("href");
		$('#content a.zip-link').attr("href", url+'zip/'+base64_encode(download_str));
		
		$('#header .lightbox span.qty').html(' ('+$.jStorage.get('lightbox').length+')');
		
		if($.jStorage.get('lightbox').length == 0) {
			$('#content p.empty').show();
			$('#content a.zip-link').addClass('hide');
			$('#header a.lightbox .qty').remove();
		}
		
		return false;
	});
}

}); // end jQuery

//	asynchronous google analytics: mathiasbynens.be/notes/async-analytics-snippet

var _gaq = [['_setAccount', 'UA-1011169-14'], ['_trackPageview']];
(function(d, t) {
 var g = d.createElement(t),
     s = d.getElementsByTagName(t)[0];
 g.async = true;
 g.src = '//www.google-analytics.com/ga.js';
 s.parentNode.insertBefore(g, s);
}(document, 'script'));
