(function($) {
	$.fn.overLabel = function() {
		return this.focus(function() {
		if (this.value == this.defaultValue) {
			this.value = '';
		}
	}).blur(function() {
		if (!this.value.length) {
			this.value = this.defaultValue;
		}
	});
};
})(jQuery);

jQuery(document).ready(function(){
$('#soundplayer').hide();
$('li.sound a').click(function() {
    $('#soundplayer').slideToggle('slow');
    return false;
  });

$("input.formText, textarea").overLabel();

    bindAjaxLinks();
});

function getFormValues(formId)
{
    var params = new Array();
    $('form#'+formId).find('input,textarea,select').each(function () {
        if ($(this).val())
        {
            params.push($(this).attr('name')+'='+Base64.encode($(this).val()));
        }
    });
    return params.join('&');
}

var logo_delay = 3;
var logo_scroll = true;
var logo_timer = 0;
function autoScrollLogo()
{
    if (logo_scroll)
    {
        if (logo_delay == 0)
        {
            if ($("#clientsList .item.centered").length > 0)
            {
                centerLogoObject($("#clientsList .item.centered").next(), 1000, true);
            }
            else
            {
                centerLogoObject($("#clientsList .item:eq(5)").next(), 1000, true);
            }
        }
        else
        {
            logo_delay--;
        }
    }
    logo_timer = setTimeout("autoScrollLogo()", 1000);
}

var range_collapse = 5;
function centerLogoObject(obj, anim, noactive)
{
    $this = obj;            
    
    $("#clientsList .item.centered").removeClass('centered');    
    $this.addClass('centered');
    
    if (noactive != true)
    {
        $("#clientsList .item.active").removeClass('active');
        $this.addClass('active');
    }
       
    var last_index = $('.slider .items > .item');                
    var item_pad = parseInt($('.item').css('padding-left')) + parseInt($('.item').css('padding-right'));
    var steps = 1;                            
    if ($this.index() < range_collapse)
    {
        steps = range_collapse - $this.index();                     
        while(steps > 0)
        {
            var clone = $this.siblings('.item:last');
            var l = parseInt($this.parent().css('left'));
            $this.parent().css({'left':(l- (clone.width()+item_pad) )+'px'})
            $this.parent().prepend( $this.siblings('.item:last') );
            steps--;
        }
    }
    else if ($this.parent().children('.item:last').index() - $this.index() < range_collapse)
    {
        steps = (($this.parent().children('.item:last').index() - $this.index()) - range_collapse)*-1;
        while(steps > 0)
        {
            var clone = $this.siblings('.item:first');
            var l = parseInt($this.parent().css('left'));
            $this.parent().css({'left':(l+ (clone.width()+item_pad) )+'px'})
            $this.parent().append( $this.siblings('.item:first') );
            steps--;
        }
    }
    processLogoObject($this, anim);
    
    logo_delay = 3;    
}
function processLogoObject(obj, anim)
{            
    var pos = obj.position();  
    if (pos != null)
    {
        if (anim == -1)
            $('.slider').find('.items').css({left:(-1*(pos.left- ( ($('.slider').width()/2)-(obj.width()/2) ) ))+'px'});
        else          
            $('.slider').find('.items').animate({left:(-1*(pos.left- ( ($('.slider').width()/2)-(obj.width()/2) ) ))+'px'}, 500, function () {});
    }
}   

function bindAjaxLinks()
{
    $(".engine-controller").hover(function () {
        var tmp_arrZ = array(0,0,0,0 ,0,0,0,0);
        if ($(this).hasClass('print')){tmp_arrZ[0] = 1;}
        if ($(this).hasClass('internet')){tmp_arrZ[1] = 1;}
        if ($(this).hasClass('design')){tmp_arrZ[2] = 1;}
        if ($(this).hasClass('filmfunk')){tmp_arrZ[3] = 1;}
        if ($(this).hasClass('dialog')){tmp_arrZ[4] = 1;}
        if ($(this).hasClass('messe')){tmp_arrZ[5] = 1;}
        if ($(this).hasClass('produktion')){tmp_arrZ[6] = 1;}
        if ($(this).hasClass('offroad')){tmp_arrZ[7] = 1;}
        
        console.log("Set Engine: ", tmp_arrZ);
        
        setSmallEngine (tmp_arrZ[0],tmp_arrZ[1],tmp_arrZ[2],tmp_arrZ[3],tmp_arrZ[4],tmp_arrZ[5],tmp_arrZ[6],tmp_arrZ[7]);
    }, function () {
        restoreSmallEngine();
    });
    
    $("a").click(function () {
        var lnk = $(this).attr("href");
        if (lnk != undefined && !$(this).parent().hasClass("download") && !$(this).parent().hasClass("links") && !$(this).hasClass("no-ajax"))
        {
            goLink(lnk);
            return false;
        }
    });
}

function bindPortfolio()
{
    jQuery(document).ready(function(){
    	$("#portfolio").scrollable({
    		keyboard: 'static',
    		next: '.nextItem',
    		prev: '.prevItem',
    		onSeek: function(event, i) {
    			horizontal.eq(i).data("scrollable").focus();
    		}
    	}).navigator("#portfolioNavi");
    	var horizontal = $(".scrollable").scrollable({
    		next: '.nextIMG',
    		prev: '.prevIMG',
    		circular: true }).navigator(".navi");
    	horizontal.eq(0).data("scrollable").focus();
    });
}

var active_zylinder = new Array(0,0,0,0 ,0,0,0,0);
var cache_zylinder = new Array(0,0,0,0 ,0,0,0,0);
function setSmallEngine (z1,z2,z3,z4,z5,z6,z7,z8)
{
    cache_zylinder = active_zylinder;
    active_zylinder = new Array(z1,z2,z3,z4,z5,z6,z7,z8);
    
    loadSmallEngine();
}
function restoreSmallEngine()
{
    var tmp_cache_cache = new Array(active_zylinder[0],active_zylinder[1],active_zylinder[2],active_zylinder[3],active_zylinder[4],active_zylinder[5],active_zylinder[6],active_zylinder[7]);    
    active_zylinder = new Array(cache_zylinder[0],cache_zylinder[1],cache_zylinder[2],cache_zylinder[3],cache_zylinder[4],cache_zylinder[5],cache_zylinder[6],cache_zylinder[7]);
    cache_zylinder = tmp_cache_cache;
    loadSmallEngine();
}
function resetSmallEngine()
{
    cache_zylinder = active_zylinder;
    active_zylinder = new Array(0,0,0,0 ,0,0,0,0);
    loadSmallEngine();
}

function loadSmallEngine () 
{
    var isSafari3 = false;
    if(window.devicePixelRatio) 
    {
        isSafari3 = true;
    }
    
    if (!isSafari3)
    {
    	var flashvars = {};
    	var params = {};
    	params.movie = "../swf/ideenmotor_small_v1.swf";
    	params.wmode = "transparent";
    	params.quality = "high";
    	var attributes = {};
       
    	if(active_zylinder[0]){flashvars.wertzyl1 = 100;}
    	if(active_zylinder[1]){flashvars.wertzyl2 = 100;}
    	if(active_zylinder[2]){flashvars.wertzyl3 = 100;}
    	if(active_zylinder[3]){flashvars.wertzyl4 = 100;}
    	if(active_zylinder[4]){flashvars.wertzyl5 = 100;}
    	if(active_zylinder[5]){flashvars.wertzyl6 = 100;}
    	if(active_zylinder[6]){flashvars.wertzyl7 = 100;}
    	if(active_zylinder[7]){flashvars.wertzyl8 = 100;}
    	attributes.align = "center";
    	swfobject.embedSWF("../swf/ideenmotor_small_v1.swf", "small-engine", "111", "80", "9.0.0", "../js/expressInstall.swf", flashvars, params, attributes);
    }
}

var portfolioIdent = 0;
var portfolioType = 0;
var portfolioBook = 0;
var portfolioOffset = 0;
var portfolioText_bookNav = 'Arbeit dieser Kategorie';
var portfolioText_pageNav = 'Abbildung dieser Arbeit';
var portfolioText_prev = 'Vorherige';
var portfolioText_next = 'Nächste';
function resetPortfolio()
{
    portfolioIdent = 0;
    portfolioType = 0;
    portfolioBook = 0;
    portfolioOffset = 0;
}
function initPortfolio()
{
    processOffsetPortfolio(0);
    $('.portfolioBtns a.prev').click(function () {prevPortfolio();});
    $('.portfolioBtns a.next').click(function () {nextPortfolio();});
    
    
    
    
    /*$(window).jkey('left, right', function (key) {
        if (key == 'left')
        {
            prevPortfolio();
        }
        else
        {
            nextPortfolio();
        }
    });*/
}
function nextPortfolio()
{
    processOffsetPortfolio(portfolioOffset+1);
}
function prevPortfolio()
{
    processOffsetPortfolio(portfolioOffset-1);
}
function jumpPortfolio(n)
{
    processOffsetPortfolio(n);
}
function processOffsetPortfolio(n, strParam)
{
    if (n <= 0)
    {
        portfolioOffset = 0;
    }
    else if (n > $('.portfolio-page').length-1)
    {
        portfolioOffset = $('.portfolio-page').length-1;
    }
    else
    {
        portfolioOffset = n;
    }

    if ($('.portfolio-page').length == 0)
    {
        firstBookPortfolio();
    }
    else 
    {
        if (n == 0)
        {
            prevBookPortfolio();
        }
        else if (n >= $('.portfolio-page').length-1)
        {
            nextBookPortfolio();
        }
    }
    
    if (n != 0)
    {
        $("div.portfolioBtns a.prevItem").show();
    }
    if (n < $('.portfolio-page').length-1)
    {
        $("div.portfolioBtns a.nextItem").show();
    }

    if (n < $('.portfolio-page').length)
    {
        if (strParam == 'noanimation')
        {
            $("#portfolioItems").animate({"left":"-"+(950*portfolioOffset)+"px"},0);            
        }
        else
        {
            $("#portfolioItems").animate({"left":"-"+(950*portfolioOffset)+"px"},"slow");
        }
    }
    updateNavigation();
}
function firstBookPortfolio()
{
    $.ajax({
        url: 'http://'+top.location.host+'/cms/?s=354&portfolioBook=true&type=' + portfolioType + '&ident=' + portfolioIdent + '&book=' + portfolioBook,
        type: 'POST',
        success: function(data) {
            if (data.charAt(0) != '0' && data.length > 0)
            {
                $("#portfolioItems").html(data);
                portfolioOffset = 0;
                processOffsetPortfolio(portfolioOffset, "noanimation");
            }
            else
            {
                if (data.substr(1).length > 1) {alert(data.substr(1));}
            }
        }
    });
}
function prevBookPortfolio()
{
    var pagesBefore = $('.portfolio-page').length;
    var currentPage = $('.portfolio-page:eq('+portfolioOffset+')');
    portfolioBook = currentPage.parent().find('input[name="book"]').val();
    $.ajax({
        url: 'http://'+top.location.host+'/cms/?s=354&portfolioBook=true&type=' + portfolioType + '&ident=' + portfolioIdent + '&book=' + portfolioBook + '&prev=true',
        type: 'POST',
        success: function(data) {
            if (data.charAt(0) != '0' && data.length > 0)
            {
                $("#portfolioItems").prepend(data);
                portfolioOffset += $('.portfolio-page').length - pagesBefore;
                $("div.portfolioBtns a.prevItem").show();
                processOffsetPortfolio(portfolioOffset, "noanimation");
            }
            else
            {
                if (data.substr(1).length > 1) {alert(data.substr(1));}
                else {$("div.portfolioBtns a.prevItem").hide();}
            }
        }
    });
}
function nextBookPortfolio()
{
    var currentPage = $('.portfolio-page:eq('+portfolioOffset+')');
    portfolioBook = currentPage.parent().find('input[name="book"]').val();
    $.ajax({
        url: 'http://'+top.location.host+'/cms/?s=354&portfolioBook=true&type=' + portfolioType + '&ident=' + portfolioIdent + '&book=' + portfolioBook + '&next=true',
        type: 'POST',
        success: function(data) {
            if (data.charAt(0) != '0' && data.length > 0)
            {
                $("#portfolioItems").append(data);                
                processOffsetPortfolio(portfolioOffset);
            }
            else
            {
                if (data.substr(1).length > 1) {alert(data.substr(1));}
                else {$("div.portfolioBtns a.nextItem").hide();}
            }
        }
    });
}
function updateNavigation()
{
    var currentPage = $('.portfolio-page:eq('+portfolioOffset+')');
    if (currentPage.prev('.portfolio-page').length > 0)
    {
        $('.portfolioBtns a.prev span').html(portfolioText_prev + ' ' + portfolioText_pageNav);
        $('.portfolioBtns a.prev').removeClass('prevItem');
    }
    else
    {
        $('.portfolioBtns a.prev span').html(portfolioText_prev + ' ' + portfolioText_bookNav);
        $('.portfolioBtns a.prev').addClass('prevItem');
    }
    if (currentPage.next('.portfolio-page').length > 0)
    {
        $('.portfolioBtns a.next span').html(portfolioText_next + ' ' + portfolioText_pageNav);
        $('.portfolioBtns a.next').removeClass('nextItem');
    }
    else
    {
        $('.portfolioBtns a.next span').html(portfolioText_next + ' ' + portfolioText_bookNav);
        $('.portfolioBtns a.next').addClass('nextItem');
    }

    $('#portfolioNavi').html('');
    var pagesBefore = currentPage.parent().children('.portfolio-page:first').index('.portfolio-page');
    currentPage.parent().find('.portfolio-page').each(function (index) {
        $('#portfolioNavi').append('<a id="navi-portfolio-page-'+(pagesBefore+index)+'" class="navi-portfolio-page" href="javascript:void(0);" onclick="processOffsetPortfolio('+(pagesBefore+index)+');"></a>');
    });

    $('.navi-portfolio-page').removeClass('active');
    $('.navi-portfolio-page').each(function (index) {
        if ($(this).attr('id') == 'navi-portfolio-page-' + portfolioOffset)
        {
            $(this).addClass('active');
        }
    });
    
    /*$('.portfolioBtns span').css({'display':'none'});
    $(document).ready(function () {
        $('.nextItem').mouseover(function () { if ($('.nextItem span').not(':visible')) {$('.nextItem span').fadeIn("fast");} });
        $('.nextItem').mouseout(function () { if ($('.nextItem span').is(':visible')) {$('.nextItem span').fadeOut("fast");} });
        $('.prevItem').mouseover(function () { if ($('.prevItem span').not(':visible')) {$('.prevItem span').fadeIn("fast");} });
        $('.prevItem').mouseout(function () { if ($('.prevItem span').is(':visible')) {$('.prevItem span').fadeOut("fast");} });
    });*/
}

function goLink(lnk)
{   
    $("#ajax_history_frame").contents().find("#ajax_history_link_cache").val( $("#ajax_history_frame").contents().find("#ajax_history_link").val() );    
    
    /*if (lnk.indexOf('/News/',0) > 0)
    {
        $("#ajax_history_frame").contents().find("#ajax_history_link").val('http://'+top.location.host+lnk.replace(top.location.host, "").replace("http://","").replace("/News/","/ajax/News/"));
    }    
    else */if (lnk.indexOf('?',0) === -1)
    {
        /*$("#ajax_history_frame").contents().find("#ajax_history_link").val(lnk+'?ajax=true');*/        
        $("#ajax_history_frame").contents().find("#ajax_history_link").val('http://'+top.location.host+'/ajax'+lnk.replace(top.location.host, "").replace("http://",""));        
    }
    else
    {
        $("#ajax_history_frame").contents().find("#ajax_history_link").val(lnk+'&ajax=true');
    }        
    $("#ajax_history_frame").contents().find("form#ajax_history").submit();
    try
    {
        pageTracker._trackPageview(lnk.replace(top.location.host, "").replace("http://",""));
    } catch (err) {}
    return false;
}

function nlaboSend()
{
    $.ajax({
        type: "POST",
        url: 'http://'+top.location.host+'/cms/?nlabo=true&email=' + Base64.encode($('input#nladr').val()),
        success: function (resp) {
            var arrResp = resp.split('#');
            if (arrResp[0] != 0)
            {
                $('li.newsletterabo').html('<span class="success">'+arrResp[1]+'</span><br class="clearfloat">');
            }
            else
            {
                $('#nlabo_error').html(arrResp[1]);                
            }
        }        
    });
}

function goLinkBack()
{   
    if(window.devicePixelRatio)
    {
        var old_lnk = $("#ajax_history_frame").contents().find("#ajax_history_link_cache").val().replace("/ajax","");
        goLink(old_lnk);
    }
    else
    {
        history.back();
    }
}

function processAjaxJson(jsonObject)
{
    if( typeof jsonObject == "object" )
    {
        // debug,alerts
        if (typeof jsonObject.debug == "object")
        {
            $.each(jsonObject.debug, function(k,v) {
                alert(Base64.decode(v));
            });
        }

        // prepend
        if (typeof jsonObject.prepend == "object")
        {
            $.each(jsonObject.prepend, function(k,v) {
                if (typeof v == "object" && v.ident != null)
                {
                    $(v.ident).prepend(Base64.decode(v.content));
                }
            });
        }
        // append
        if (typeof jsonObject.append == "object")
        {
            $.each(jsonObject.append, function(k,v) {
                if (typeof v == "object" && v.ident != null)
                {
                    $(v.ident).append(Base64.decode(v.content));
                }
            });
        }
        // after
        if (typeof jsonObject.after == "object")
        {
            $.each(jsonObject.after, function(k,v) {
                if (typeof v == "object" && v.ident != null)
                {
                    $(v.ident).after(Base64.decode(v.content));
                }
            });
        }
        // before
        if (typeof jsonObject.before == "object")
        {
            $.each(jsonObject.before, function(k,v) {
                if (typeof v == "object" && v.ident != null)
                {
                    $(v.ident).before(Base64.decode(v.content));
                }
            });
        }

        // assign
        if (typeof jsonObject.assign == "object")
        {
            // assign-html
            if (typeof jsonObject.assign.html == "object")
            {
                $.each(jsonObject.assign.html, function(k,v) {
                    if (typeof v == "object" && v.ident != null)
                    {
                        $(v.ident).html(Base64.decode(v.content));
                    }
                });
            }
            // assign-value
            if (typeof jsonObject.assign.val == "object")
            {
                $.each(jsonObject.assign.val, function(k,v) {
                    if (typeof v == "object" && v.ident != null)
                    {
                        $(v.ident).val(Base64.decode(v.content));
                    }
                });
            }
            // assign-attr
            if (typeof jsonObject.assign.attr == "object")
            {
                $.each(jsonObject.assign.attr, function(k,v) {
                    if (typeof v == "object" && v.ident != null)
                    {
                        $(v.ident).attr(v.attr, Base64.decode(v.content));
                    }
                });
            }
        }

        // script
        if (typeof jsonObject.script == "object")
        {
            $.each(jsonObject.script, function(k,v) {
                eval(Base64.decode(v));
            });
        }

        bindAjaxLinks();
    }
}


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = Base64._utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
		}
		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		while (i < input.length) {
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = Base64._utf8_decode(output);
		return output;
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}
