// usage: log('inside coolFunc', this, arguments);
// 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) {
   arguments.callee = arguments.callee.caller;
   var newarr = [].slice.call(arguments);
   (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try
{console.log();return window.console;}catch(err){return window.console={};}})());


// @version $Id: application.js 6089 2011-12-08 15:36:39Z dbunpia $

/**
 * Daten fuer preloader
 */
var isImagesLoaded      = false;
var hamlCreate          = false;
var preloaderCallback = function( callback ) {
    preLoader.callback = function() {
        var _this = this;
        if(  hamlCreate === true )
        {
            $('#loader-overlayer, #loader-info').animate(
                {
                    opacity : 0
                },
                {
                    queue       : false,
                    duration    : 500,
                    complete    : function() {
                        _this.removeLoader();
                        _this.removeImages();

                        $('#preloader').remove();
                        $('#loader-progress').remove();
                        $('#loader-info').remove();
                        $('#loader-overlayer').remove();

                        if(typeof callback === 'function' )
                        {
                            callback.call();
                        }
                    }
                }

            );
        }
    };
    preLoader.callback();
};

var headerLeft = {
	prepare: function() {
		//small dirty hack to manage all the transparency stuff in the header navigation
		$('ul#header-left > li > ul li.last').after(
			'<li class="background"></li>'
			+'<li class="background2">'
			+'</li><li class="border"></li>'
		);
		//cache the images for the background already here
		var sel = 'ul#header-left > li > ul > ';
		var already = {};
		$(sel+'li.background,'+sel+'li.background2,'+sel+'li.border,'+sel+'li.first > a').each(function() {
			var src = $(this).getBGSrc();
			if(
				src !== false &&
				typeof(already[src]) === 'undefined'
			) {
				already[src] = true;
				var tmp = new Image();
				tmp.src = src;
			};
		});
	}
};
/* ----------------------------------- */
var backgroundView = {
	//Internal
	bg_scale: false,
	bg_scale_ie: false,
	bg_darken: false,
	bg_darken_ie: false,
	bg_scale_fx: false,
	bg_scale_fx_ie: false,
	body: false,
	curSrc: false,
	oldImg: false,

	buildView: function() {
		$.extend(this,{
			bg_scale: $('#bg_scale'),
			bg_scale_ie: $('#bg_scale_ie'),
			bg_darken: $('#bg_darken'),
			bg_darken_ie: $('#bg_darken_ie'),
			bg_scale_fx: $('#bg_scale_fx'),
			bg_scale_fx_ie: $('#bg_scale_fx_ie'),
			body: $('body')
		});
		return true;
	},

	setFixed: function(img,callback1) {
		var that = this;
		if(this.oldImg === false) this.oldImg = img;
		$.imgLoaded(img,function() {
			$.imgLoaded(that.oldImg,function() {

				var src = img.attr('src');
				var callback2 = that.createCallback(
					that.bg_scale,
					that.bg_scale_ie,
					'bg_scale_ie',
					src,
					true,
					img
				);
				var oldSrc = that.oldImg.attr('src');
				var callback3 = that.createCallback(
					that.bg_scale_fx,
					that.bg_scale_fx_ie,
					'bg_scale_fx_ie',
					oldSrc,
					false,
					that.oldImg
				);
				that.callCallback(callback1,callback2,callback3,(src !== oldSrc));
				that.curSrc = src;
				that.oldImg = img;
                /* ----------------------------------- */
                // wenn alle Bilder geladen ist
                if(typeof isImagesLoaded === 'function')
                {
                    isImagesLoaded.call();
                    isImagesLoaded = false;
                }
                /* ----------------------------------- */
			});
		});
		return true;
	},

	createCallback: function(el1,el2,id,src,check,img) {
		var callback = function() {};
		if(typeof(imgScale) === 'object') {
			if(
				typeof(el2) === 'undefined' ||
				el2.length === 0
			) {
				/*
				 * we have to use a clone here! because otherwise every src-attribute
				 * change will change our original Image-object.
				 */
				callback = function() {
					el2 = img.clone();
					el2.attr('id',id).appendTo(el1);
					imgScale.start(el1,el2);
				};
			} else {
				if(this.checkSrc(src) || check === false) {
					callback = function() {
						el2.attr('src',src);
					};
				};
			};
		} else {
			if(this.checkSrc(src) || check === false) {
				callback = function() {
					el1.css('background-image','url("'+src+'")');
				};
			};
		};
		return callback;
	},

	setDarken: function(img) {
		var that = this;
		$.imgLoaded(img,function() {
			var src = img.attr('src');
			if(typeof(imgScale) === 'object') {
				if(
					typeof(that.bg_darken_ie) === 'undefined' ||
					that.bg_darken_ie.length === 0
				) {
					/*
					 * we have to use a clone here! because otherwise every src-attribute
					 * change will change our original Image-object.
					 */
					that.bg_darken_ie = img.clone();
					that.bg_darken_ie.attr('id','bg_darken_ie').appendTo(that.bg_darken);
					imgScale.start(that.bg_darken,that.bg_darken_ie);
				} else {
					that.bg_darken_ie.attr('src',src);
				};
			} else {
				that.bg_darken.css('background-image','url("'+src+'")');
			};
		});
		return true;
	},

	setStatic: function(img,callback) {
		var that = this;
		$.imgLoaded(img,function() {
			var src = img.attr('src');
			that.callCallback(callback,function() {
				that.body.css({
					'background-image': 'url("'+src+'")',
					'background-repeat': 'no-repeat',
					'background-position': 'center top'
				});
			});
		});
	},

	callCallback: function(callback1,callback2,callback3,srcChange) {
		if(typeof(callback1) === 'function') {
			callback1(this,callback2,callback3,srcChange);
			return true;
		} else return false;
	},

	destroyView: function() {
		$.extend(this,{
			bg_scale: false,
			bg_scale_ie: false,
			bg_darken: false,
			bg_darken_ie: false,
			bg_scale_fx: false,
			bg_scale_fx_ie: false,
			body: false
		});
		return true;
	},

	checkSrc: function(src) {
		if(
			this.curSrc === false ||
			(
					this.curSrc !== src &&
					this.curSrc.indexOf(src) === -1 &&
					src.indexOf(this.curSrc) === -1
			)
		) return true;
		else return false;
	}
};

var JSONRequests = {
	
	jqXHR: '',

	getGenresMovies: function(fileUrl, callback)
    {
		if(typeof(callback) !== 'function')
        {
            callback = function(e, d) {};
        }
        
		var now = new Date().getTime();
         
        this.jqXHR = $.ajax({
            url     : fileUrl,
            type    : 'GET',
            //data  : 'nocache='+config.nocache, //no caching please
            dataType : 'json',
            success : function( data )
            {
                var duration = new Date().getTime()-now;
                callback(data, duration);
            }
        });
        
        /**
         * es soll nicht mehr genutzt werden
         * 
        this.jqXHR = $.ajax(url,{
            'type': 'GET',
            //'data': 'nocache='+config.nocache, //no caching please
            'dataType': 'text',
            'success': function(data) {
                var tmp = false;
                try {eval('tmp = '+data+';');} catch(ex) {};
                var duration = new Date().getTime()-now;
                callback(tmp,duration);
            }
        });
        */
        
		return true;
	},

	abortRequest: function(){
		this.jqXHR.abort();
	}
};

var deepURLs = {
	getValue: function(key,callback) {
		var expr;
		eval('expr = /'+key+'=([^&]*)/i;');
		if(decodeURIComponent(location.search).match(expr)) {
			var tmp = RegExp.$1.toLowerCase();
			tmp = tmp.replace(/[^a-zA-Z0-9]+/g,'');
			callback(tmp);
			return true;
		} else return false;
	},

	match: function(expr,callback) {
		if(decodeURIComponent(location.search).match(expr)) {
			callback();
			return true;
		} else return false;
	}
};

var genreView = {
	//Internal
	genres: [],
	curGenre: 0,
	content: false,
	genreEl: false,
	ignoreGET: false,
	//Settings
	genreMaxOpc: 5,
	genreBottom: 210,
	//Keycode "Constants"
	KEYCODE_UP: 38,
	KEYCODE_DOWN: 40,
	KEYCODE_ENTER: 13,
	KEYCODE_POS1: 36,
	KEYCODE_END: 35,

	buildView: function() {
		var that = this;
		this.content = $('#article');

        /* ----------------------------------- */
        /* image preloader */
        preLoader.init();
        preLoader.createPreloader();
        /* end image preloader */
        /* ----------------------------------- */
        
		JSONRequests.getGenresMovies(config.genreScript, function(genres, duration) {
			if(genres !== false)
            {
                /* ----------------------------------- */
                /* image preloader */
                preLoader.loadWallpapers(genres );
                isImagesLoaded = function() { preloaderCallback(); };
                /* end image preloader */
                /* ----------------------------------- */

				//check the initial state set in the JSON
				var initGenre = genres.initGenre;
				if(typeof(initGenre) !== 'number') initGenre = 0;
				//set genres
				that.genres = genres.genres;
				//set the darken image before the deepURL-test
				var darken = new Image();
				darken.src = config.images+config.darkenImage;
				backgroundView.setDarken($(darken));
				//check the GET-parameter for a genre
				if(that.ignoreGET === false)
                {
					deepURLs.getValue('genre', function(genreGET) {
						if(typeof(genres.mapping[genreGET]) !== 'undefined')
                        {
							that.ignoreGET = true;
							that.loadGenre(genres.mapping[genreGET]);
							return true;
						};
					});
				};
				//first load ALL images
				for(var i=0;i<that.genres.length;i++)
                {
					that.genres[i]._bgsImg = new Image();
					that.genres[i]._bgsImg.src = config.images+that.genres[i].bigsizeURL;
					that.genres[i]._bgsImg = $(that.genres[i]._bgsImg);
				};
                
				//construct the navigation
				if(that.genreEl)
                {
                    that.genreEl.remove();
                }
                
				var ul = ['%ul',{'id':'genre'},[]]; //haml code
                
				for(var i=0;i<that.genres.length;i++) {
					//haml code
					ul[2].push(['%li',[
						//what a construct. but every wrapper is necessary!
						['%div',{'class':'title'},
							['%div',{'class':'wrap'},[
							 	['%div',{'class':'wrap2'},
									['%a',{
										'href':'#',
										'events':{
											'click':$.hardcode(function(e,args) {
												e.target.blur();
												e.preventDefault();
												e.stopPropagation();
												that.moveTo(args[0]);
											},[i])}
										},
										that.genres[i].title
									]
								],
								['%a',{
									'class': 'backward',
									'href':'#',
									'events':{
										'click':function(e) {
											e.target.blur();
											e.preventDefault();
											e.stopPropagation();
											that.moveBackward();
										}}
									}
								],
								['%a',{
									'class': 'forward',
									'href':'#',
									'events':{
										'click':function(e) {
											e.target.blur();
											e.preventDefault();
											e.stopPropagation();
											that.moveForward();
										}}
									}
								]
							]]
						],
						['%div',{'class':'button'},
							['%a',{
									'href':'#',
									'events':{'click':$.hardcode(function(e,args) {
										var target = $(e.target);
										if(
											target[0].nodeName.toLowerCase() !== 'div' &&
											!target.hasClass('title') &&
											!target.hasClass('wrap')
										) {
											target[0].blur();
											e.preventDefault();
											e.stopPropagation();
											that.loadGenre(args[0]);
										};
									},[i])}
								},'Das, was ich will']
							]
					]]);
				};
                var hamlLoaded = function() {
                    hamlCreate = true;
                };
				that.content.haml(ul, hamlLoaded());
				that.genreEl = $('#genre');
				new makeButton(that.genreEl.find('.button a'),'active-big');
				that.moveTo(initGenre);
				$(document).bind({
					'keydown': $.proxy(that.evtKeydown,that),
					'mousewheel': $.proxy(that.evtMousewheel,that)
				});
				return true;
			};
		});
		return true;
	},

	animateEl: function(obj,callback1,callback2,srcChange) {
		if(srcChange) {
			//obj.bg_scale.stop(true,true);
			//obj.bg_scale_fx.stop(true,true);
			obj.bg_scale.stop(true,true).css({
				'left': 0,
				'opacity':0,
				'right': 0
			});
			obj.bg_scale_fx.stop(true,true).css({
				'left': 0,
				'opacity':1,
				'right': 0
			});
			callback1();
			callback2();
			obj.bg_scale.animate({'opacity':1},{'duration': 400});
			obj.bg_scale_fx.animate({'opacity':0},{'duration': 400});
		} else {
			callback1();
			callback2();
		};
		return true;
	},

	setActiveGenre: function() {
		var that = this;
		var lis = this.genreEl.find('li');
		var befAct = false;
		var nowAct = false;
		lis.each(function(i,el) {
			el = $(el);
			el.find('.wrap2 a').stop(true,true);
			if(el.hasClass('active')) befAct = el;
			if(i === that.curGenre) nowAct = el;
		});
		if(nowAct) {
			var nowAct2 = nowAct.find('.wrap2 a');
			if(befAct) {
				var befAct2 = befAct.find('.wrap2 a');
				if(!$.browser.msie || parseInt($.browser.version) >= 9) {
					befAct2.animate({'opacity':0},{
						'duration': 200,
						'complete': function() {
							that.setActiveGenre2(lis,befAct,nowAct,befAct2,nowAct2);
						}
					});
				} else {
					this.setActiveGenre2(lis,befAct,nowAct,befAct2,nowAct2);
				};
			} else {
				this.setActiveGenre2(lis,false,nowAct,false,nowAct2);
			};
		};
		return true;
	},

	setActiveGenre2: function(lis,befAct,nowAct,befAct2,nowAct2) {
		var curLi;
		if(this.curGenre !== 0) curLi = $(lis[0]);
		else curLi = $(lis[1]);
		lis.each(function(i,el) {
			el = $(el);
			el.removeClass();
			if(i === 0) el.addClass('first');
			if(i === lis.length-1) el.addClass('last');
		});
		nowAct.addClass('active');
		if(!$.browser.msie || parseInt($.browser.version) >= 9) {
			nowAct2.css('opacity',0).animate({'opacity':1},{
				'duration':200,
				'complete': function() {
					nowAct2.removeInlineStyle('opacity');
				}
			});
			if(befAct2) befAct2.removeInlineStyle('opacity');
		};
		for(var i=this.curGenre;i>=0;i--) {
			$(lis[i]).addClass(this.opacityClass(this.curGenre-i));
		};
		for(var i=this.curGenre+1;i<lis.length;i++) {
			$(lis[i]).addClass(this.opacityClass(i-this.curGenre));
		};
		Cufon.replace('#genre li .title a',{'fontFamily': 'ConduitITCStd'});
		Cufon.replace('#genre li.active .title a',{'fontFamily': 'ConduitITCStd Bold'});
		//The VML-fallbacks have an offset to the parent element
		var offsetTop = 0;
		if($.browser.msie && parseInt($.browser.version) <= 8) {
			var vml = curLi.find('cufon.cufon-vml');
			if(typeof(vml) !== 'undefined' && vml.length > 0) {
				offsetTop = vml[0].offsetTop;
				if(typeof(offsetTop) !== 'number') offsetTop = 0;
			};
		};
		this.genreEl.css('bottom',
			(this.genreBottom-parseInt(this.genreEl.height()))+
			(this.curGenre*(offsetTop+curLi.height()+parseInt(curLi.css('margin-bottom'))))
		);
	},

	opacityClass: function(val) {
		return 'opacity'+Math.max(1,this.genreMaxOpc-val);
	},

	moveBackward: function() {
		this.moveTo(Math.max(0,this.curGenre-1));
		return true;
	},

	moveForward: function() {
		this.moveTo(Math.min(this.genres.length-1,this.curGenre+1));
		return true;
	},

	moveTo: function(val) {
		var oldVal = this.curGenre;
		var newVal = Math.min(this.genres.length-1,Math.max(0,val));
		if(newVal !== oldVal) {
			this.curGenre = newVal;
			backgroundView.setFixed(this.genres[this.curGenre]._bgsImg,this.animateEl);
			this.setActiveGenre();
		};
		return true;
	},

	moveToFirst: function() {
		this.moveTo(0);
		return true;
	},

	moveToLast: function() {
		this.moveTo(this.genres.length-1);
		return true;
	},

	loadGenre: function(val) {
		if(typeof(movieView) === 'object')
        {
            /* ----------------------------------- */
            /* image preloader */
            isImagesLoaded      = null;
            var _genres         = this.genres,
                that            = this;

            hamlCreate          = false;
            preLoader.callback  = null;
            preLoader.init();
            preLoader.createPreloader();
            JSONRequests.getGenresMovies(this.genres[val].moviesURL,function(movies, duration) {
                preLoader.loadWallpapers(movies);
                isImagesLoaded = function() {
                    preloaderCallback();
                };
                movieView.buildView({genres:_genres,curGenre:val});
                that.destroyView();
            });
            /* end image preloader */
            /* ----------------------------------- */
        }

		TvTracking.tvGenreChanged(this.genres[val].title);

		return true;
	},

	destroyView: function() {
		this.genreEl.remove();
		$.extend(this,{
			genres: [],
			curGenre: 0,
			content: false,
			genreEl: false
		});
		$(document).unbind({
			'keydown': this.evtKeydown,
			'mousewheel': this.evtMousewheel
		});
		return true;
	},

	evtKeydown: function(e) {
		switch(e.which) {
			case this.KEYCODE_UP:this.moveBackward();break;
			case this.KEYCODE_DOWN:this.moveForward();break;
			case this.KEYCODE_ENTER:this.loadGenre(this.curGenre);break;
			case this.KEYCODE_POS1:this.moveToFirst();break;
			case this.KEYCODE_END:this.moveToLast();break;
		};
	},

	evtMousewheel: function(e,delta) {
		if(delta > 0) this.moveBackward();
		else if(delta < 0) this.moveForward();
	}
};

var movieView = {
	//Internal
	genres: [],
	curGenre: 0,
	movies: [],
	curMovie: [false,false],
	frmMovie: false,
	content: false,
	sushibarEl: false,
	ignoreGET: false,
	//Settings
	sushibarWdth: 228,
	sushibarMrg: 15,
	sushibarOvrl: 100,
	sushibarVport: 1000,
	liWidth: 228,
	liHeight: 256,
	//Keycode "Constants"
	KEYCODE_PREV: 37,
	KEYCODE_NEXT: 39,
	KEYCODE_ESC: 27,
	KEYCODE_ENTER: 13,
	KEYCODE_POS1: 36,
	KEYCODE_END: 35,
	//Callbacks
	buildViewCallback: false,
	setActiveCallback: false,
	destroyViewCallback: false,
	evtKeydownCallback: false,
	loadMovieHamlCallback: false,
	loadMovieBeforeOpenCallback: false,
	loadMovieTrackingCallback: false,
	//Behaviour
	showLinks: false,

	buildView: function(options)
    {
		var that = this;
		this.content = $('#article');
		$.extend(this,options);

	
        JSONRequests.getGenresMovies(this.genres[this.curGenre].moviesURL, function(movies, duration) {
			if(movies !== false)
            {
				//initial state
				var initMovie = 0;
				//check the GET-parameter for a genre
				if(that.ignoreGET === false) {
					deepURLs.getValue('movie',function(movieGET) {
						if(typeof(movies.mapping[movieGET]) !== 'undefined') {
							that.ignoreGET = true;
							initMovie = movies.mapping[movieGET];
						};
					});
				};
				that.movies = movies.movies;
				//first load ALL images
				for(var i=0;i<that.movies.length;i++) {
					that.movies[i]._bgsImg = new Image();
					that.movies[i]._bgsImg.src = config.images+that.movies[i].bigsizeURL;
					that.movies[i]._bgsImg = $(that.movies[i]._bgsImg);
					that.movies[i]._prvImg = new Image();
					if(
						$.browser.opera ||
						$.browser.webkit
					) {
						/*
						 * for the next line to work, the server needs to support CORS.
						 * see the desaturate method for fruther information.
						 */
						that.movies[i]._prvImg.crossOrigin = '';
					};
					that.movies[i]._prvImg.src = config.images+that.movies[i].previewURL;
					that.movies[i]._prvImg = $(that.movies[i]._prvImg);
				};
				//construct the sushibar
				if(that.sushibarEl) that.sushibarEl.remove();
				var ulWdth = (that.movies.length*that.sushibarWdth)
					+((that.movies.length-1)*that.sushibarMrg)
					+100; //little safety value! to avoid any line breaks!
				var ul = ['%div',{'id':'sushibar'},['%ul',{'css':{'width':ulWdth}},[]]]; //haml code
				var styles = [];
				for(var i=0;i<that.movies.length;i++)
                {
					var j = i+1;
					var cls = '';
					if(i === 0) cls += 'first ';
					if(i === that.movies.length-1) cls += 'last ';
					if(cls !== '') cls = cls.substr(0,cls.length-1);
					//background-images with desaturation workaround for opera and webkit
					var canvasEl = [];
					if(
						$.browser.opera ||
						$.browser.webkit
					) {
						canvasEl = [that.desaturate(that.movies[i]._prvImg[0])];
					}
					//haml code
					ul[2][2].push(['%li',{
						'class': cls,
						'css': {
							'background-image': 'url("'+config.images+that.movies[i].previewURL+'")'
						}
					},[
						canvasEl,
						['%a',{
							'href': '#',
							'class': ((that.showLinks) ? 'visible' : 'invisible'),
							'events':{
								'click': $.hardcode(function(e,args) {
									var trgt = $(e.target);
									trgt[0].blur();
									while(trgt[0].nodeName.toLowerCase() !== 'li') trgt = $(trgt).parent();
									e.preventDefault();
									if(
										!trgt.hasClass('active') &&
										!trgt.hasClass('outside')
									) that.setActive(args[0]);
								},[i])
							}
						},['%span',that.movies[i].title]]
					]]);
				};

                var hamlLoaded = function()
                {
                    hamlCreate      = true;
                };
				that.content.haml(ul, hamlLoaded());
				that.sushibarEl = $('#sushibar');
				Cufon.replace(that.sushibarEl.find('li a.visible span'),{
					'fontFamily': 'ConduitITCStd Bold',
					'textShadow': '#000 -1px -1px,#000 1px 1px'
				});
                that.moveTo(false, initMovie);
				//events
				$(document).bind('keydown',$.proxy(that.evtKeydown,that));
				that.sushibarEl.bind('mousewheel',$.proxy(that.evtMousewheel,that));
				if(typeof(that.buildViewCallback) === 'function') that.buildViewCallback();
				//open popup if GET-param contains loadmovie=1
				deepURLs.match(/load[^a-zA-Z0-9]*movie=1/i,function() {that.loadMovie();});
			};
		});
		return true;
	},

	desaturate: function(imgObj) {
		/*
		 * CAUTION!!! The following code does not work if the images are in another
		 * domain as the website that contains this script.
		 *
		 * the only possible solution is to use CORS on the server with the other domain-name.
		 */
		var el      = $('<canvas />'),
            ctx     = el[0].getContext('2d');
            
		el.width = this.liWidth;
		el.height = this.liHeight;
        
        try
        {
            ctx.drawImage(imgObj,0,0);
            
            var pxls = ctx.getImageData(0,0,this.liWidth,this.liHeight);
            
            for(var i=0; i<pxls.height; i++)
            {
                for(var j=0; j<pxls.width; j++)
                {
                    var k   = (i*4)*pxls.width+j*4,
                        avg = (pxls.data[k]+pxls.data[k+1]+pxls.data[k+2])/3;
                        
                    pxls.data[k]    = avg;
                    pxls.data[k+1]  = avg;
                    pxls.data[k+2]  = avg;
                };
            };
            ctx.putImageData(pxls,0,0,0,0,pxls.width,pxls.height);
        }
        catch ( e )
        {
            console.log( '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' );
            console.log( e ); 
            console.log( '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' );
        }
        
		return el;
		return '';
	},

	animateEl: function(obj,callback1,callback2,srcChange) {
		if(srcChange) {
			if(this.frmMovie !== this.curMovie[1]) {
				obj.bg_scale.stop(true,true);
				var wdth = obj.bg_scale.width();
				//from right to left
				if(this.frmMovie < this.curMovie[1]) {
					obj.bg_scale_fx.css({
						'left': 0,
						'opacity': 1,
						'right': 'auto',
						'width': wdth
					});
					obj.bg_scale.css({
						'left': wdth,
						'opacity': 1,
						'right': 'auto',
						'width': wdth
					});
					callback1();
					callback2();
					obj.bg_scale_fx.animate({'left':0-wdth,'opacity':0},{'duration':800});
					obj.bg_scale.animate({'left':0},{'duration':800});
				//from left to right
				} else {
					obj.bg_scale_fx.css({
						'left': 'auto',
						'opacity': 1,
						'right': 0,
						'width': wdth
					});
					obj.bg_scale.css({
						'left': 'auto',
						'opacity': 1,
						'right': wdth,
						'width': wdth
					});
					callback1();
					callback2();
					obj.bg_scale_fx.animate({'opacity':0,'right':0-wdth},{'duration':800});
					obj.bg_scale.animate({'right':0},{'duration':800});
				};
			};
		}
        else
        {
			callback1();
			callback2();
		};
		return true;
	},

	setSushibar: function() {
		var that = this;
		var wdth = this.sushibarWdth+this.sushibarMrg;
		var org;
		if(this.curMovie[0] === 0) org = this.sushibarOvrl;
		else org = 0-Math.abs((this.curMovie[0]*(wdth))-this.sushibarOvrl);
		var ul = this.sushibarEl.find('ul');
		ul.animate({'left':org},{
			'duration': 800,
			'complete': function() {
				var lis = ul.find('li');
				lis.each(function(n,el) {
					el = $(el);
					el.unbind();
					el.removeClass('outside');
					var lft = org+(n*wdth);
					if(lft < 0) {
						el.addClass('outside');
						el.click(function() {
							that.moveBackward();
						});
					} else if(
						(lft+that.sushibarWdth) > (that.sushibarOvrl+that.sushibarVport)
					) {
						el.addClass('outside');
						el.click(function() {
							that.moveForward();
						});
					};
				});

                /* ----------------------------------- */
                // preloaderLoeschen
                preloaderCallback();
                /* ----------------------------------- */
			}
		});
		return true;
	},

	setActive: function(val) {
		this.frmMovie = this.curMovie[1];
		this.curMovie[1] = Math.min(this.movies.length-1,Math.max(0,val));
		this.setActiveEl();
		if(typeof(this.setActiveCallback) === 'function') this.setActiveCallback();
		return true;
	},

	setActiveEl: function() {
		var that = this;
		this.sushibarEl.stop(true,true).find('li').each(function(n,el) {
			el = $(el);
			if(n === that.curMovie[1]) el.addClass('active');
			else el.removeClass('active');
		});
	},

	activatePrev: function() {
		if(this.curMovie[1] > 0) {
			var nxtAct = this.sushibarEl.stop(true,true).find('ul li:eq('+(this.curMovie[1]-1)+')');
			if(typeof(nxtAct) !== 'undefined') {
				if(nxtAct.hasClass('outside')) this.moveBackward();
				else this.setActive(this.curMovie[1]-1);
			};
		};
	},

	activateNext: function() {
		if(this.curMovie[1] < this.movies.length-1) {
			var nxtAct = this.sushibarEl.stop(true,true).find('ul li:eq('+(this.curMovie[1]+1)+')');
			if(typeof(nxtAct) !== 'undefined') {
				if(nxtAct.hasClass('outside')) this.moveForward();
				else this.setActive(this.curMovie[1]+1);
			};
		};
	},

	moveBackward: function() {
		this.moveTo(
			this.curMovie[0]-Math.floor(this.sushibarVport/(this.sushibarWdth+this.sushibarMrg)),
			this.curMovie[0]-1
		);
		return true;
	},

	moveForward: function() {
		this.moveTo(this.curMovie[0]+Math.floor(this.sushibarVport/(this.sushibarWdth+this.sushibarMrg)));
		return true;
	},

	moveTo: function(val1,val2) {
		var old = this.curMovie;
		if(val1 === false && typeof(val2) !== 'undefined') {
			var wdth = Math.floor(this.sushibarVport/(this.sushibarWdth+this.sushibarMrg));
			val1 = (wdth*(Math.ceil((val2+1)/wdth)-1));
		};
		if(typeof(val2) === 'undefined') val2 = val1;
		if(val1 !== old[0]) {
			this.curMovie[0] = Math.min(this.movies.length-1,Math.max(0,val1));
			this.setSushibar();
		};
		if(val2 !== old[1]) this.setActive(val2);
		return true;
	},

	moveToFirst: function() {
		this.moveTo(0);
		return true;
	},

	moveToLast: function() {
		this.moveTo(false,this.movies.length-1);
		return true;
	},

	loadMovie: function() {
		var that = this;
		var url = config.detailsScript;
		var movie1 = this.movies[this.curMovie[1]];
		url = url.replace(/%s/,movie1.id);
		if(typeof(this.loadMovieTrackingCallback) === 'function') this.loadMovieTrackingCallback();
        
		JSONRequests.getGenresMovies(url,function(movie2, duration) {
			if(movie2 !== false) {
				new popup({
					'hamlCallback': function(popup) {
						var inv = {'class':'invisible'}, prices = [], result;
                        
						if(typeof(movie2.price) === 'string') {
							prices.push(['%li',Price.construct('',movie2.price,movie2.period)]);
						};
						if(typeof(movie2.priceHD) === 'string') {
							prices.push(['%li',Price.construct('HD',movie2.priceHD,movie2.period)]);
						};
						if(typeof(movie2.price3d) === 'string') {
							prices.push(['%li',Price.construct('3D',movie2.price3d,movie2.period)]);
						};

						if(movie1.genre === 'redbull'){
							result = ['%div',{
									'class':'video-details',
									'id':'video-details'+popup.instance
								},[
								['%h1',{'class':'video-details-title'},movie1.title],
						 		['%div',{'class':'clear'}],
								['%div',
									{'class':'video-details-flash'},
									['%div',{'id':'video-details-flash'+popup.instance}]
								],
								['%ul',{'class':'video-details-more'},[
		                 			['%li',{'class':'copy'},movie2.copy]
		                 		]],
								['%div',{'class':'clear'}]
							]];
						} else {
							result = ['%div',{
									'class':'video-details',
									'id':'video-details'+popup.instance
								},[
								['%h1',{'class':'video-details-title'},movie1.title],
						 		['%div',{'class':'clear'}],
								['%div',
									{'class':'video-details-flash'},
									['%div',{'id':'video-details-flash'+popup.instance}]
								],
								['%ul',{'class':'video-details-more'},[
		                 			['%li',{'class':'video-details-short'},
		                 				['%ul',[
		                 					['%li',{'class':'genre first'},[
		                 						['%span',inv,'Genre: '],
		                 						[movie1.genre]
		                 					]],
		                 					['%li',{'class':'country'},[
		                 						['%span',inv,'Land: '],
		                 						[movie1.country]
		                 					]],
		                 					['%li',{'class':'year'},[
		                 						['%span',inv,'Jahr: '],
		                 						[movie1.year]
		                 					]],
		                 					['%li',{'class':'duration'},[
		                 						['%span',inv,'Länge: '],
		                 						[movie1.duration]
		                 					]],
		                 					['%li',{'class':'fsk last'},[
		                                    	['%span',inv,'FSK: '],
		                                    	[movie1.fsk]
		                                    ]]
		                 				]],
		                 				['%div',{'class':'clear'}]
		                 			],
		                 			['%li',{'class':'actors'},[
		                            	['%div',{'class':'label'},'Hauptdarsteller: '],
		                            	['%div',{'class':'content'},movie2.actors],
		                            	['%div',{'class':'clear'}]
		                            ]],
		                 			['%li',{'class':'copy'},movie2.copy],
		                 			['%li',{'class':'title-nr'},'Titelnummer: '+movie2.titleNr],
		                 			['%li',{'class':'prices'},[['%ul',prices],['%div',{'class':'clear'}]]]
		                 		]],
								['%div',{'class':'clear'}]
							]];
						};

						if(typeof(that.loadMovieHamlCallback) === 'function') {
							result = that.loadMovieHamlCallback(result);
						};
						return result;
					},
					'beforeMeasure': function(popup,el) {
						Cufon.replace(
							$(
								'#video-details'+popup.instance+' h1.video-details-title,'
								+'#video-details'+popup.instance+' ul.video-details-more li.prices > ul > li > div.price > div'
							),
							{'fontFamily':'ConduitITCStd Bold'}
						);
						Cufon.replace('#video-details'+popup.instance+' .name',
								{'fontFamily':'ConduitITCStd'}
						);
						new makeButton($('#video-details'+popup.instance
								+' *[data-transform=button-active-small]'),'active-small');
					},
					'beforeOpen': function(popup) {
						if(movie2.trailer) {
							jwplayer('video-details-flash'+popup.instance).setup({
								'flashplayer': config.jwPlayer,
								'width': '100%',
								'height': '100%',
								'file': movie2.trailer,
								'autostart': true,
								'id': 'video-details-flash-player'+popup.instance
							});
						}
						else
						{
							$('.video-details-flash').html('<img src="/kabelbw/cms/resources_tv/images/kein-trailer.jpg" alt="Leider ist kein Trailer vorhanden">');
						};

						$(document).unbind({
							'keydown': that.evtKeydown,
							'mousewheel': that.evtMousewheel
						});
						if(typeof(that.loadMovieBeforeOpenCallback) === 'function') {
							that.loadMovieBeforeOpenCallback(popup);
						};
					},
					'afterClose': function(popup) {
						$(document).bind({
							'keydown': $.proxy(that.evtKeydown,that),
							'mousewheel': $.proxy(that.evtMousewheel,that)
						});
					}
				});
			};
		});
		return true;
	},

	destroyView: function() {
		this.sushibarEl.unbind('mousewheel',this.evtMousewheel);
		this.sushibarEl.remove();
		$.extend(this,{
			genres: [],
			curGenre: 0,
			movies: [],
			curMovie: [false,false],
			content: false,
			sushibarEl: false
		});
		$(document).unbind('keydown',this.evtKeydown);
		if(typeof(this.destroyViewCallback) === 'function') this.destroyViewCallback();
		return true;
	},

	evtKeydown: function(e) {
		// TODOif
        // ($('body').hasClass('fixed') === true && $('body').hasClass('bottom-oriented'))
        //{
            switch(e.which) {
                case this.KEYCODE_PREV:this.activatePrev();break;
                case this.KEYCODE_NEXT:this.activateNext();break;
                case this.KEYCODE_POS1:this.moveToFirst();break;
                case this.KEYCODE_END:this.moveToLast();break;
            };
            if(typeof(this.evtKeydownCallback) === 'function') this.evtKeydownCallback(e);
        //}
	},

	evtMousewheel: function(e,delta) {
        if($('body').hasClass('fixed') === true && $('body').hasClass('bottom-oriented'))
        {
		    e.preventDefault();
		    if(delta > 0) this.activateNext();
		    else if(delta < 0) this.activatePrev();
        }
	}
};

var videoInfoView = {
	//Internal
	videoInfoEl: false,
	movies: [],
	curMovie: [false,false],
	content: false,

	buildView: function(movies,curMovie) {
		var that = this;
		$.extend(this,{
			movies: movies,
			curMovie: curMovie,
			content: $('#article')
		});
		if(this.videoInfoEl) {
			if(!$.browser.msie || parseInt($.browser.version) >= 9) {
				//this.videoInfoEl.stop(true,true);
				this.videoInfoEl.stop(true,true).animate({'opacity':0},{
					'duration': 500,
					'complete': function() {
						that.videoInfoEl.remove();
						that.buildView2();
					}
				});
			} else {
				this.videoInfoEl.remove();
				this.buildView2();
			}
		} else this.buildView2();
		return true;
	},

	buildView2: function() {
		var that = this;
		var movie = this.movies[this.curMovie[1]];
		var inv = {'class':'invisible'};
		var css = {};
		if(!$.browser.msie || parseInt($.browser.version) >= 9) {
 			css = {'opacity':0};
 		};
        
		var ul = ['%ul',{'id':'video-info','css':css},[
 			['%li',{'class':'headline'},'Videothek'],
 			['%li',{'class':'title'},movie.title],
 			['%li',[
 				['%ul',[
 					['%li',{'class':'country'},[
 						['%span',inv,'Land: '],
 						[movie.country]
 					]],
 					['%li',{'class':'year'},[
 						['%span',inv,'Jahr: '],
 						[movie.year]
 					]],
 					['%li',{'class':'duration'},[
 						['%span',inv,'Länge: '],
 						[movie.duration]
 					]],
 					['%li',{'class':'fsk'},[
 						['%span',inv,'FSK: '],
 						[movie.fsk]
 					]]
 				]],
 				['%div',{'class':'clear'}]
 			]],
 			['%li',{'class':'link'},['%a',{
 				'href': '#',
 				'events': {
 					'click': function(e) {
 						e.preventDefault();
 						this.blur();
 						movieView.loadMovie();
 					}
 				}
 			},'Mehr Infos']]
 		]];
 		this.content.haml(ul);
 		this.videoInfoEl = $('#video-info');
 		Cufon.replace(this.videoInfoEl.find('li.headline'),{'fontFamily': 'ConduitITCStd'});
 		Cufon.replace(this.videoInfoEl.find('li.title'),{'fontFamily': 'ConduitITCStd Bold'});
 		new makeButton(this.videoInfoEl.find('li.link a'),'active-small');
 		this.videoInfoEl.stop(true,true);
 		if(!$.browser.msie || parseInt($.browser.version) >= 9) {
 			this.videoInfoEl.stop(true,true).animate({'opacity':1},{'duration':300});
 		};
 		return true;
	},

	destroyView: function() {
		this.videoInfoEl.remove();
		$.extend(this,{
			videoInfoEl: false,
			movies: [],
			curMovie: [false,false],
			content: false
		});
		return true;
	}
};

var productInfoView = {
	//Internal
	productInfoEl: false,
	genres: [],
	curGenre: 0,
	content: false,

	buildView: function(genres,curGenre) {
		$.extend(this,{
			genres: genres,
			curGenre: curGenre,
			content: $('#article')
		});
		if(this.productInfoEl) this.productInfoEl.remove();
		this.content.haml(['%div',{'id':'product-info'}]);
		this.productInfoEl = $('#product-info');
		var product = this.genres[this.curGenre]['product'];
		this.productInfoEl.haml([
			['%div',{'class':'headline'},product.headline],
			['%div',{'class':'name'},product.name],
			['%div',{'class':'subname'},product.subname],
			['%div',{'class':'clear'}],
			['%div',{'class':'description'},product.description],
			Price.construct('',product.price,product.period,product.supinfo),
			['%div',{'class':'link'},['%a',{'href':product.link},'Mehr Infos']],
			['%div',{'class':'clear'}]
		]);
		Cufon.replace(this.productInfoEl.find('.headline,.name,.subname'),{'fontFamily':'ConduitITCStd'});
 		Cufon.replace(this.productInfoEl.find('.euro,.cent,.period'),{'fontFamily':'ConduitITCStd Bold'});
 		new makeButton(this.productInfoEl.find('.link a'),'active-small');
		return true;
	},

	destroyView: function() {
		this.productInfoEl.remove();
		$.extend(this,{
			productInfoEl: false,
			genres: [],
			curGenre: 0,
			content: false
		});
		return true;
	}
};

var videoStoreGenre = {
	//Internal
	videoStoreGenreEl: false,
	genres: [],
	curGenre: 0,
	content: false,

	buildView: function(genres,curGenre) {
		$.extend(this,{
			genres: genres,
			curGenre: curGenre,
			content: $('#article')
		});
		if(this.videoStoreGenreEl) this.videoStoreGenreEl.remove();
		this.content.haml(['%h1',{'id':'videostore-genre'},this.genres[this.curGenre].title]);
		this.videoStoreGenreEl = $('#videostore-genre');
		Cufon.replace(this.videoStoreGenreEl,{'fontFamily':'ConduitITCStd'});
		return true;
	},

	destroyView: function() {
		this.videoStoreGenreEl.remove();
		$.extend(this,{
			videoStoreGenreEl: false,
			genres: [],
			curGenre: 0,
			content: false
		});
		return true;
	}
};


// Rotate:
/*
 *	jquery.easyRotate 1.0 - 3-11-2010
 * author: Jordan Andree (jordan@noblegiant.com)
 * http://noblegiant.com
 *
 *	Written to ease the implementation of element rotation for cross-browser support
 *	Feel free to do whatever you want with this file
 *
 */
(function ($) {

	// base function
	$.fn.extend({
		easyRotate: function(options) {

			// default config
			var defaults = {
				degrees: 0
			};

			// extend the options
			var options = $.extend(defaults, options);

			// return function
			return this.each(function() {

				// the object
				var obj = this;

				// the degrees param
				var deg = options.degrees;

				// calculations to get our matrix
				var deg2radians = Math.PI * 2 / 360;
				var rad = deg * deg2radians;
				var costheta = Math.cos(rad);
				var sintheta = Math.sin(rad);

				// vars for cosin and sin
				var a = parseFloat(costheta).toFixed(8);
				var c = parseFloat(-sintheta).toFixed(8);
				var b = parseFloat(sintheta).toFixed(8);
				var d = parseFloat(costheta).toFixed(8);

				// the matrix string
				var matrix = "matrix(" + a + ", " + b + ", " + c + ", " + d + ", 0, 0);";
				
				// if IE filters are present
				if (obj.filters && ($.browser.version !== '9.0')) {

					
					obj.style.filter = "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand');";
					obj.filters.item(0).M11 = costheta;
					obj.filters.item(0).M12 = -sintheta;
					obj.filters.item(0).M21 = sintheta;
					obj.filters.item(0).M22 = costheta;

				// else for Safari, Firefox, etc
				} 
				else if ($.browser.version === '9.0') {
					obj.setAttribute("style",   "position:absolute; -ms-transform: rotate(270deg)" +
														"; transform: ");
				}
				else {
					obj.setAttribute("style",   "position:absolute; -moz-transform:  " + matrix +
									"; -webkit-transform:  " + matrix +
									"; -o-transform: " + matrix + 
									"; -ms-transform: " + matrix +
									"; transform: " + matrix +"");
				}
			});
		}
	});
})(jQuery);

var videoStoreDetails = {
	//Internal
	videoStoreDetailsEl: false,
	movie: {},
	content: false,
	hamlCreate: false,

	buildView: function(movie) {
		var that = this;
		if(this.videoStoreDetailsEl) {

			
			this.destroyView(function() {
				that.buildView(movie);
			});
			return false;
		};
		$.extend(this,{
			movie: movie,
			content: $('#article')
		});
		var url = config.detailsScript;
		url = url.replace(/%s/,this.movie.id);

		

		JSONRequests.getGenresMovies(url,function(movie2,duration) {
			//debug
			var inv = {'class':'invisible'};
			var prices = [];
			if(typeof(movie2.price) === 'string') {
				prices.push(['%li',Price.construct('',movie2.price,movie2.period,'1)')]);
			};
			if(typeof(movie2.priceHD) === 'string') {
				prices.push(['%li',Price.construct('HD',movie2.priceHD,movie2.period,'1)')]);
			};
			if(typeof(movie2.price3d) === 'string') {
				prices.push(['%li',Price.construct('3D',movie2.price3d,movie2.period,'1)')]);
			};
			var css = {};
			if(!$.browser.msie || parseInt($.browser.version) >= 9) {
	 			css = {'opacity':0};
	 		};

	 		var hamlLoaded = function()
	        {
	            
	        };

			that.content.haml(['%div',{
				'id':'videostore-details',
				'css': css
			},[
				['%a',{
					'href': '#',
					'class': 'videostore-details-close',
					'events': {
						'click': function(e) {
							e.preventDefault();
							e.target.blur();
							that.destroyView();
						}
					}
				},'schlie\u00DFen'],
				['%div',{'class':'width-2-1'},['%img',{
					'src': config.images+movie2.coverURL,
					'alt': movie.title
				}]],
				['%div',{'class':'width-2-2'},[
					['%div', {'id':'legal'}, movie2.legal],
					['%h1', movie.title],
					['%ul',[
            			['%li',{'class':'videodetails-details-short'},
            				['%ul',[
            					['%li',{'class':'genre first'},[
            						['%span',inv,'Genre: '],
            						[movie.genre]
            					]],
            					['%li',{'class':'country'},[
            						['%span',inv,'Land: '],
            						[movie.country]
            					]],
            					['%li',{'class':'year'},[
            						['%span',inv,'Jahr: '],
            						[movie.year]
            					]],
            					['%li',{'class':'duration'},[
            						['%span',inv,'Länge: '],
            						[movie.duration]
            					]],
            					['%li',{'class':'fsk last'},[
            						['%span',inv,'FSK: '],
            						[movie.fsk]
                            	]]
            				]],
            				['%div',{'class':'clear'}]
            			],
            			['%li',{'class':'title-nr'},[
            				['%span',{'class':'label'},'Titelnummer:'],
            				['%span',{'class':'value'},movie2.titleNr],
            				['%div',{'class':'clear'}]
            			]],
            			['%li',{'class':'link'},[
            				['%a',{
            					'href':'#','class':'arrow-orange-big',
            					'events': {
            						'click': function(e) {
            							e.preventDefault();
            							e.target.blur();
            							movieView.loadMovie();
            						}
            					}
            				},'Trailer & Inhalt']
            			]],
            			['%li',{'class':'prices'},['%ul',prices]]
            		]]
				]],
				['%div',{'class':'clear'}]
			]]);

			that.videoStoreDetailsEl = $('#videostore-details');
            Cufon.replace(
				$('#videostore-details').find('h1, .prices > ul > li > div.price > div'),
				{'fontFamily':'ConduitITCStd Bold'}
			);
			if(!$.browser.msie || parseInt($.browser.version) >= 9) {
				//that.videoStoreDetailsEl.stop(true,true);
				that.videoStoreDetailsEl.stop(true,true).animate({'opacity':1},{'duration':Math.max(0,(300-duration))});
			};

			// Rotate the legal text
			$('#legal').easyRotate({
				degrees: 270
			});
			
		});
		return true;
	},

	destroyView: function(callback) {
		if(typeof(callback) === 'undefined')
        {
            callback = function() {};
        }
		
		if(JSONRequests.jqXHR)
        {
			JSONRequests.jqXHR.abort();
		}
        
		if(this.videoStoreDetailsEl)
        {
			//debug
			// console.log('test ' + this.videoStoreDetailsEl);
            
			var that = this;
			if(!$.browser.msie || parseInt($.browser.version) >= 9)
            {
				//this.videoStoreDetailsEl.stop(true,true);
				this.videoStoreDetailsEl.stop().animate({'opacity':0},{
					'duration': 10,
					'complete': function()
                    {						
						that.videoStoreDetailsEl.remove();
						
						$.extend(that,{
							videoStoreDetailsEl: false,
							movie: {},
							content: false
						});
						callback()
					}
				});
			}
            else
            {
				this.videoStoreDetailsEl.remove();
				$.extend(this,{
					videoStoreDetailsEl: false,
					movie: {},
					content: false
				});
				callback();
			};
			return true;
		}
        else
        {
            return false;
        }
	}
};

var redBullTvDetails = {
	//Internal
	videoStoreDetailsEl: false,
	movie: {},
	content: false,
	buildView: function(movie)
    {
		var that = this;
		if(this.videoStoreDetailsEl) {
			this.destroyView(function() {
				that.buildView(movie);
			});
			return false;
		};
		$.extend(this,{
			movie: movie,
			content: $('#article')
		});
		var url = config.detailsScript;
		url = url.replace(/%s/,this.movie.id);
		JSONRequests.getGenresMovies(url,function(movie2,duration) {
			var inv = {'class':'invisible'};
			var prices = [];
			if(typeof(movie2.price) === 'string') {
				prices.push(['%li',Price.construct('',movie2.price,movie2.period)]);
			};
			if(typeof(movie2.priceHD) === 'string') {
				prices.push(['%li',Price.construct('HD',movie2.priceHD,movie2.period)]);
			};
			if(typeof(movie2.price3d) === 'string') {
				prices.push(['%li',Price.construct('3D',movie2.price3d,movie2.period)]);
			};
			that.content.haml(['%div',{
				'id':'videostore-details',
				'css': {
					'opacity': 0
				}
			},[
				['%a',{
					'href': '#',
					'class': 'videostore-details-close',
					'events': {
						'click': function(e) {
							e.preventDefault();
							e.target.blur();
							that.destroyView();
						}
					}
				},'schlie\u00DFen'],
				['%div',{'class':'width-2-1'},['%img',{
					'src': config.images+movie2.coverURL,
					'alt': movie.title
				}]],
				['%div',{'class':'width-2-2'},[
					['%h1', movie.title],
					['%p', movie.info],
					['%p',{'class':'link'},[
	    				['%a',{
	    					'href':'#','class':'arrow-orange-big',
	    					'events': {
	    						'click': function(e) {
	    							e.preventDefault();
	    							e.target.blur();
	    							movieView.loadMovie();
	    						}
	    					}
	    				},'Inhalt']
    				]]
				]],
				['%div',{'class':'clear'}]
			]]);



			that.videoStoreDetailsEl = $('#videostore-details');
			Cufon.replace(
				$('#videostore-details').find('h1, .prices > ul > li > div.price > div'),
				{'fontFamily':'ConduitITCStd Bold'}
			);
			//that.videoStoreDetailsEl.stop(true,true);
			that.videoStoreDetailsEl.stop(true,true).animate({'opacity':1},{'duration':Math.max(0,(300-duration))});
		});
		return true;
	},

	destroyView: function(callback) {
		if(typeof(callback) === 'undefined') callback = function() {};
		if(this.videoStoreDetailsEl) {
			var that = this;
			//this.videoStoreDetailsEl.stop(true,true);
			this.videoStoreDetailsEl.stop(true,true).animate({'opacity':0},{
				'duration': 500,
				'complete': function() {
					that.videoStoreDetailsEl.remove();
					$.extend(that,{
						videoStoreDetailsEl: false,
						movie: {},
						content: false
					});
					callback();
				}
			});
			return true;
		} else return false;
	}
};



var genreSmallView = {
	//Internal
	genres: [],
	curGenre: 0,
	topGenre: 0,
	content: false,
	genreSmallEl: false,
	genreSmallList: false,
	genreSmallUl: false,
	genreSmallLi: false,
	liHeight: false,
	elsPerView: false,
	//Settings
	genreMaxOpc: 4,
	//Keycode "Constants"
	KEYCODE_UP: 38,
	KEYCODE_DOWN: 40,
	//Callback
	changeGenreCallback: false,

	buildView: function(genres,curGenre) {
		var that = this;
		$.extend(this,{
			genres: genres,
			curGenre: curGenre,
			content: $('#article')
		});
		//construct the small genre-selector
		ul = ['%div',{'id':'genre-small'},[
			['%div',{'class':'genre-small-current'},['%a',{
				'href': '#',
				'events': {
					'mouseover': function(e) {
						that.genreSmallEl.addClass('hover');
					},
					'mouseout': function(e) {
						that.genreSmallEl.removeClass('hover');
					},
					'click': function(e) {
						e.preventDefault();
						e.stopPropagation();
						e.target.blur();
						if(that.genreSmallEl.hasClass('flyout')) {
							that.genreSmallEl.removeClass('flyout');
						} else {
							that.genreSmallEl.addClass('flyout');
							that.topGenre = that.calcRange(that.curGenre-1);
							that.setTopGenre(false);
						};
					}
				}
			},this.genres[that.curGenre].title]],
			['%div',{'class':'genre-small-claim'},'Das, was ich will'],
			['%a',{
				'href':'#',
				'class':'genre-small-up',
				'events': {
					'click': function(e) {
						e.preventDefault();
						e.stopPropagation();
						e.target.blur();
						that.moveBackward();
					}
				}
			},'Nach oben'],
			['%div',{'class':'genre-small-list'},['%ul',[]]],
			['%a',{
				'href':'#',
				'class':'genre-small-down',
				'events': {
					'click': function(e) {
						e.preventDefault();
						e.stopPropagation();
						e.target.blur();
						that.moveForward();
					}
				}
			},'Nach unten']
		]];
		for(var i=0;i<this.genres.length;i++) {
			ul[2][3][2][1].push(['%li',['%a',{
				'href':'#',
				'events': {
					'click': $.hardcode(function(e,args) {
						e.target.blur();
						e.preventDefault();
						e.stopPropagation();
						that.changeGenre(args[0]);
					},[i])
				}
			},this.genres[i].title]]);
		};
		this.content.haml(ul);
		this.genreSmallEl = $('#genre-small');
		this.genreSmallList = this.genreSmallEl.find('.genre-small-list');
		this.genreSmallUl = this.genreSmallList.find('ul');
		this.setActiveGenre();
		//events
		$(document).bind({
			'click': $.proxy(this.evtClick,this),
			'keydown': $.proxy(this.evtKeydown,this)
		});
		this.genreSmallEl.bind('mousewheel',$.proxy(this.evtMousewheel,this));
	},

	setActiveGenre: function() {
		var that = this;
		this.genreSmallLi = this.genreSmallUl.find('li');
		this.genreSmallLi.each(function(i,el) {
			el = $(el);
			el.removeClass();
			if(i === that.curGenre) el.addClass('active');
			if(i === 0) el.addClass('first');
			if(i === that.genreSmallLi.length-1) el.addClass('last');
		});
		Cufon.replace(this.genreSmallEl.find(
			'.genre-small-current a, .genre-small-claim'),
			{'fontFamily':'ConduitITCStd'}
		);
		Cufon.replace(this.genreSmallUl.find('li a'),{
			'fontFamily':'ConduitITCStd',
			'hover': {
				'color': '#D68609'
			}
		});
		//measure the height a single li
		this.genreSmallList.css({
			'visibility': 'hidden',
			'display': 'block'
		});
		var tmp = $(this.genreSmallLi[0]);
		this.liHeight = tmp.height()+parseInt(tmp.css('margin-top'));
		this.elsPerView = Math.floor(this.genreSmallList.height()/this.liHeight);
		this.genreSmallList.removeInlineStyle(['display','visibility']);
		this.setTopGenre(true);
		return true;
	},

	setTopGenre: function(animate) {
		var that = this;
		var callback = function() {
			for(var i=that.topGenre;i>=0;i--) {
				el = $(that.genreSmallLi[i]);
				that.removeOpacities(el);
				el.addClass(that.opacityClass(that.topGenre-i));
			};
			for(var i=that.topGenre+1;i<that.genreSmallLi.length;i++) {
				el = $(that.genreSmallLi[i]);
				that.removeOpacities(el);
				el.addClass(that.opacityClass(i-that.topGenre));
			};
		};
		if(animate) {
			//this.genreSmallUl.stop(true,true);
			this.genreSmallUl.stop(true,true).animate({'top':0-(this.topGenre*this.liHeight)},{
				'duration': 300,
				'complete': callback
			});
		} else {
			this.genreSmallUl.css('top',0-(this.topGenre*this.liHeight));
			callback();
		};
		return true;
	},

	opacityClass: function(val) {
		return 'opacity'+Math.max(1,this.genreMaxOpc-val);
	},

	removeOpacities: function(el) {
		for(i=1;i<=this.genreMaxOpc;i++) el.removeClass('opacity'+i);
	},

	changeGenre: function(val) {
		this.curGenre = val;
		if(typeof(this.changeGenreCallback) === 'function') this.changeGenreCallback();
		old = this.genres;

        /* ----------------------------------- */
        /* image preloader */
        hamlCreate                  = false;
        isImagesLoaded              = null;
        preLoader.callback          = null;
        preLoader.init();
        preLoader.createPreloader();
        
        JSONRequests.getGenresMovies(old[val].moviesURL,function(movies, duration) {
            preLoader.loadWallpapers( movies );
            
            movieView.destroyView();
            movieView.buildView({genres:old,curGenre:val});
        });
        /* end image preloader */
        /* ----------------------------------- */

		return true;
	},

	destroyView: function() {
		this.genreSmallEl.unbind('mousewheel',this.evtMousewheel);
		this.genreSmallEl.remove();
		$.extend(this,{
			genres: [],
			curGenre: 0,
			topGenre: 0,
			content: false,
			genreSmallEl: false,
			genreSmallList: false,
			genreSmallUl: false,
			genreSmallLi: false,
			liHeight: false,
			elsPerView: false
		});
		$(document).unbind({
			'click': this.evtClick,
			'keydown': this.evtKeydown
		});
		return true;
	},

	moveBackward: function() {
		this.moveTo(Math.max(0,this.topGenre-1));
		return true;
	},

	moveForward: function() {
		this.moveTo(Math.min(this.genres.length-1,this.topGenre+1));
		return true;
	},

	moveTo: function(val) {
		var oldVal = this.topGenre;
		var newVal = this.calcRange(val);
		if(newVal !== oldVal) {
			this.topGenre = newVal;
			this.setTopGenre(true);
		};
		return true;
	},

	calcRange: function(val) {
		return Math.min(this.genres.length-this.elsPerView,Math.max(0,val));
	},

	moveToFirst: function() {
		this.moveTo(0);
		return true;
	},

	moveToLast: function() {
		this.moveTo(this.genres.length-1);
		return true;
	},

	evtClick: function(e) {
		this.genreSmallEl.removeClass('flyout');
	},

	
	evtKeydown: function(e) {
		if(this.genreSmallEl !== false && this.genreSmallEl.hasClass('flyout')) {
			e.stopPropagation();
			switch(e.which) {
				case this.KEYCODE_UP:this.moveBackward();break;
				case this.KEYCODE_DOWN:this.moveForward();break;
			};
		};
	},

	evtMousewheel: function(e,delta) {
		if(this.genreSmallEl.hasClass('flyout')) {
			e.stopPropagation();
			if(delta > 0) this.moveBackward();
			else if(delta < 0) this.moveForward();
		};
	} 
};

var popupInstances = 0;
var popupStack = {};

function popup(options) {
	$.extend(this,{
		//Internal
		instance: 	++popupInstances,
		stack: 		new Date().getTime(),
		ovrlEl: 	false,
		cntEl: 		false,
		cntWrpEl: 	false,
		vPort: 		((options.vPort) ? options.vPort : $(window)),
		doc: 		((options.doc)   ? options.doc   : $(document)),
		body: 		((options.body)  ? options.body  : $('body')),
		top: 		((typeof(options.top) !== 'undefined') ? options.top : 'auto'),
		left: 		((typeof(options.left) !== 'undefined') ? options.left : 'auto'),
		width: 		((options.width) ? options.width : 'auto'),
		height: 	((typeof(options.height) !== 'undefined') ? options.height : 'auto'),
		cntDims: 	[0,0],
		//Settings
		minZIndex: 200, //the menu has 100+, it is rarely possible to have 99 submenus
		closeHeight: 29,
		closeBodyClick: ((typeof(options.closeBodyClick) !== 'undefined') ? options.closeBodyClick : true),
		//Keycode "Constants"
		KEYCODE_ESC: 27,
		//Callbacks
		hamlCallback: ((typeof(options.hamlCallback) !== 'undefined') ? options.hamlCallback : false),
		beforeOpen: ((typeof(options.beforeOpen) !== 'undefined') ? options.beforeOpen : false),
		afterClose: ((typeof(options.afterClose) !== 'undefined') ? options.afterClose : false),
		beforeMeasure: ((typeof(options.beforeMeasure) !== 'undefined') ? options.beforeMeasure : false),

		buildPopup: function() {
			var that = this;
			popupStack[this.stack] = this;
			var cnt = [];
			if(this.hamlCallback) cnt = this.hamlCallback(this);
			var tmp = $('<div>').css({
				'visibility': 'hidden',
				'position': 'absolute',
				'top': -9999,
				'left': -9999,
				'display': 'block'
			}).attr({
				'class': 'popup-content',
				'id': 'popup-content'+this.stack
			});
			var tmp2 = $('<div>').css({'position':'static'}).addClass('popup-content-wrapper');
			tmp2.appendTo(tmp);
			tmp.appendTo(this.body);
			/*
			 * best case is, that the data from the callback is an haml-array.
			 * if the data is a pure string, we assume, that it is HTML.
			 */
			if(typeof(cnt) === 'object') tmp2.haml(cnt);
			else tmp2.append(cnt);
			if(this.beforeMeasure) this.beforeMeasure(this,tmp);
			this.cntDims = [tmp.width(),tmp.height()];
			tmp.attr({'class':'','id':''});
			tmp2.removeClass();
			if(this.width !== 'auto') this.cntDims[0] = this.width;
			if(this.height !== 'auto') this.cntDims[1] = this.height;
			this.body.haml([
				['%div',{
					'id': 'popup-overlay'+this.stack,
					'class': 'popup-overlay',
					'css': {
						'left': 0,
						'opacity': 0,
						'position': 'absolute',
						'top': 0,
						'z-index': this.minZIndex+((this.instance-1)*2)
					},
					'events': {
						'click': function(e) {
							e.stopPropagation();
							if(that.closeBodyClick) that.destroyPopup();
						}
					}
				}],
				['%div',{
					'id': 'popup-content'+this.stack,
					'class': 'popup-content',
					'css': {
						'height': this.cntDims[1]+this.closeHeight,
						'opacity': 0,
						'position': 'absolute',
						'width': this.cntDims[0],
						'z-index': this.minZIndex+((this.instance-1)*2)+1
					}
				},[
					['%div',{'class':'popup-content-close'},['%a',{
						'href':'#',
						'events': {
							'click': function(e) {
								e.preventDefault();
								e.target.blur();
								that.destroyPopup();
							}
						}
					},'zur\u00FCck']],
					['%div',{'class':'popup-content-wrapper'}]
				]]
			]);
			this.ovrlEl = $('#popup-overlay'+this.stack);
			this.cntEl = $('#popup-content'+this.stack);
			this.cntWrpEl = this.cntEl.find('.popup-content-wrapper');
			this.cntWrpEl.append(tmp2.children()[0]);
			this.cntWrpEl.find('*[data-event=evt-close]').bind('click',function (e) {
				e.preventDefault();
				e.target.blur();
				that.destroyPopup();
			});
			tmp.remove();
			this.calcPos();
			if(this.beforeOpen) this.beforeOpen(this);
			this.ovrlEl.animate({'opacity':0.9},{'duration':500});
			this.cntEl.animate({'opacity':1},{'duration':500});
			this.vPort.bind({
				'resize': $.proxy(this.evtResize,this),
				'keydown': $.proxy(this.evtKeydown,this),
				'scroll': $.proxy(this.evtScroll,this)
			});
		},

		calcPos: function() {
			this.cntEl.css('display','none');
			var vPortDims = [this.vPort.width(),this.vPort.height()];
			var top;
			var left;
			if(this.top === 'auto') {
				top = Math.max(0,this.vPort.scrollTop()+Math.round((vPortDims[1]-(this.cntDims[1]+this.closeHeight))/2));
			} else top = this.top;
			if(this.left === 'auto') {
				left = Math.max(0,this.vPort.scrollLeft()+Math.round((vPortDims[0]-this.cntDims[0])/2));
			} else left = this.left;
			this.cntEl.css({
				'left': left,
				'top': top,
				'display': 'block'
			});
			this.ovrlEl.css('display','none');
			var ovrlDims = [this.doc.width(),this.doc.height()];
			this.ovrlEl.css({
				'height': ovrlDims[1],
				'width': ovrlDims[0],
				'display': 'block'
			});
		},

		destroyPopup: function() {
			var that = this;
			this.ovrlEl.animate({'opacity':0},{
				'duration': 500,
				'complete': function() {
					that.ovrlEl.remove();
				}
			});
			this.cntEl.animate({'opacity':0},{
				'duration': 500,
				'complete': function() {
					if(that.afterClose) that.afterClose(that);
					that.cntEl.remove();
					that.vPort.unbind({
						'resize': $.proxy(that.evtResize,that),
						'keydown': $.proxy(that.evtKeydown,that),
						'scroll': $.proxy(that.evtScroll,that)
					});
					delete popupStack[that.stack];
					var instMax = 0;
					$.each(popupStack,function(key,value) {
						instMax = Math.max(instMax,value.instance);
					});
					popupInstances = instMax;
				}
			});
		},

		evtResize: function() {
			this.calcPos();
		},

		evtKeydown: function(e) {
			switch(e.which) {
				case this.KEYCODE_ESC:e.preventDefault();this.destroyPopup();break;
			}
		},

		evtScroll: function() {
			this.calcPos();
		}
	});

	this.buildPopup();
};

var Price = {
	'construct': function(prefix,price,period,supinfo) {
		price = price.split(/[\.,]/);
		if(price.length === 1) price[1] = '00';
		var el = ['%div',{'class':'price'},[
			['%div',{'class':'euro'},price[0]],
			['%div',{'class':'cent'},price[1]],
			['%div',{'class':'period'},period]
		]];
		if(typeof(supinfo) !== 'undefined') el[2].push(['%div',{'class':'supinfo'},supinfo]);
		el[2].push(['%div',{'class':'clear'}]);
		if(typeof(prefix) === 'string' && prefix !== '') el[2].unshift(['%div',{'class':'prefix'},prefix]);
		return el;
	}
};


//Transformations
var readyTransforms = function(sel) {
	//transform all buttons present in the document
	new makeButton($(sel+'*[data-transform=button-active-big]'),'active-big');
	new makeButton($(sel+'*[data-transform=button-active-small]'),'active-small');
	//transform form-elements
	if(typeof(makeForm) !== 'undefined') {
		//transform radios
		var radio = new makeForm($(sel+'*[data-transform=radio]'));
		radio.transformRadio();
		//transform checkboxes
		var checkbox = new makeForm($(sel+'*[data-transform=checkbox]'));
		checkbox.transformCheckbox();
		//transform selects
		var select = new makeForm($(sel+'*[data-transform=select]'));
		select.transformSelect();
	};
	//transform popup-links and -elements
	if(typeof(popup) !== 'undefined') {
		$(sel+'*[data-event=evt-popup]').bindPopup();
		$(sel+'*[data-transform=popup]').openPopup();
	};
	return true;
};


var TvTracking = {
	tvGenreChanged : function(genre) {
		var track = new Tracker();
		track.evars({'TV Genre' : genre});
		track.track();
	},
	tvTeaserClicked : function(genre, movie) {
		var track = new Tracker();
		track.evars({'TV Teaser' : 'TV_' + genre + '_' + movie});
		track.track();
	},
	videothekGenreChanged : function(genre) {
		var track = new Tracker();
		track.evars({'Videothek Genre' : genre});
		track.track();
	},
	videothekTeaserClicked : function(genre, movie) {
		var track = new Tracker();
		if(genre == "") {
			track.evars({'Videothek Trailer' : 'Videothek_' + movie});
		} else {
			track.evars({'Videothek Trailer' : 'Videothek_' + genre + '_' + movie});
		}
		track.track();
	}
};

//###CAUTION!### here is the part for workarounds that let your hair stand to mountains
var Workarounds = {
	//productnames are always in one piece!
	splitProductName: function(els) {
		els.each(function(i,el) {
			el = $(el);
			var tag = el[0].tagName.toLowerCase();
			el.html().match(/^\s*(Mein\s*TV\*International|Mein\s*TV\s*HD|Mein\s*TV|Sky\s*Welt|Sky|TV\s*Digital)\s*(.*?)$/i);
			
			if(
				typeof(RegExp.$1) !== 'undefined' &&
				RegExp.$1 !== '' &&
				typeof(RegExp.$2) !== 'undefined' &&
				RegExp.$2 !== '' && 
				RegExp.$2 !== '='
			) {

				var pName = RegExp.$1;
				var pSubName = RegExp.$2;
				el.html(pName);
				var el2 = false;
				if(tag === 'h1') { 
					el2 = $('<h2/>');
				}
				else if(tag === 'h3'){ 
					el2 = $('<h4/>');
				}
				else if(tag === 'div') { 
					el2 = $('<div/>');
				}
				
				if(el.hasClass('product-name')) 
					el2.addClass('product-subname');
				if(el2 !== false) 
					el.after(el2.html(pSubName));
			};
		});
	}
};


/**
 * @author Alexandre Magno
 * @desc Center a element with jQuery
 * @version 1.0
 * @example
 * $("element").center({
 *
 * 		vertical: true,
 *      horizontal: true
 *
 * });
 * @obs With no arguments, the default is above
 * @license free
 * @param bool vertical, bool horizontal
 * @contribution Paulo Radichi
 *
 */
jQuery.fn.center = function(params) {

		var options = {

			vertical: true,
			horizontal: true

		}
		op = jQuery.extend(options, params);

   return this.each(function(){

		//initializing variables
		var $self = jQuery(this);
		//get the dimensions using dimensions plugin
		var width = $self.width();
		var height = $self.height();
		//get the paddings
		var paddingTop = parseInt($self.css("padding-top"));
		var paddingBottom = parseInt($self.css("padding-bottom"));
		//get the borders
		var borderTop = parseInt($self.css("border-top-width"));
		var borderBottom = parseInt($self.css("border-bottom-width"));
		//get the media of padding and borders
		var mediaBorder = (borderTop+borderBottom)/2;
		var mediaPadding = (paddingTop+paddingBottom)/2;
		//get the type of positioning
		var positionType = $self.parent().css("position");
		// get the half minus of width and height
		var halfWidth = (width/2)*(-1);
		var halfHeight = ((height/2)*(-1))-mediaPadding-mediaBorder;
		// initializing the css properties
		var cssProp = {
			position: 'absolute'
		};

		if(op.vertical) {
			cssProp.height = height;
			cssProp.top = '50%';
			cssProp.marginTop = halfHeight;
		}
		if(op.horizontal) {
			cssProp.width = width;
			cssProp.left = '50%';
			cssProp.marginLeft = halfWidth;
		}
		//check the current position
		if(positionType == 'static') {
			$self.parent().css("position","relative");
		}
		//aplying the css
		$self.css(cssProp);


   });

};


// --------------------
// Kabel BW Errormessage Overlay

// jQuery Plugin Boilerplate
// A boilerplate for jumpstarting jQuery plugins development
// version 2.0, July 8th, 2011
// by Stefan Gabos

(function($) {

	$.errorMsg = function(el, options) {

        // plugin's default options
        // this is private property and is accessible only from inside the plugin
        var defaults = {
            alpha    : 0.8,
            top      : 0,
            left     : 0,
			bottom   : 0,
			right    : 0,
			closeBtn : '/kabelbw/export/sites/default/resources_tv/images/popup_content.png',
			closeTxt : 'schlie\u00DFen',
			msg      : 'Bitte w\u00e4hlen Sie einen Receiver aus!'
        }

        // to avoid confusions, use "plugin" to reference the current instance of the object
        var plugin = this;

        plugin.settings = {}

        var init = function() {
            // the plugin's final properties are the merged default and user-provided options (if any)
            plugin.settings = $.extend({}, defaults, options);

            plugin.el = el;

            plugin.el.css( 'position', 'relative' );
            plugin.el.prepend(
	            $('<div>').css({
					position   : 'absolute',
					top  	   : plugin.settings.top,
					left       : plugin.settings.left,
					bottom     : plugin.settings.bottom,
					right      : plugin.settings.right,
					'background-color' : 'rgba(0,0,0,' + plugin.settings.alpha + ')',
					'z-index'  : 100
				})
				.append(
					$('<div class="popup-content-close">')
						.css({
							background        : 'transparent url(' + plugin.settings.closeBtn + ') no-repeat left top',
							display           : 'inline-block',
							'font-size'       : '14px',
							height            : '24px',
							'line-height'     : '24px',
							'padding-left'    : '26px',
							'text-decoration' : 'none',
							'cursor'		  : 'pointer',
							margin			  : '10px'
						})
						.text(plugin.settings.closeTxt)
				)
				.append('<div id="error_msg">' + plugin.settings.msg + '</div>')
				.addClass('errormsg-container')
			);

			$('.popup-content-close').click(function(e){
				e.preventDefault();
				destroyMsg();
			});

			$("#error_msg").css({
				'font-size'      : '20px',
				'text-transform' : 'uppercase',
				'text-align' 	 : 'center'
			});

			$("#error_msg").center();

			Cufon.replace( $("#error_msg"), {
				'fontFamily' : 'ConduitITCStd bold',
				'color'      : '#D68609'
			});

        }

        var destroyMsg = function() {
            plugin.el.find('div:first').eq(0).remove();
        }

        init();
    }

})(jQuery);

/**
 * Image Preloader
 */
var preLoader = {
    wallpapers  : 0,
    callback    : 0,
    json        : 0,
    loadable    : true,
    bodyClass   : 'fixed',
    imgClass    : 'preload-image',
    imagePath   : config.images,
    init : function ()
    {
        this.jq             = jQuery;
        this._body          = $('body');
        if(this._body.hasClass(this.bodyClass) === true )
        {
            this.loadable   = true;
        }
        this.loader         = $('<div></div>'),
        this.loaderDiv      = $('<div></div>'),
        this.loadProgress   = $('<div></div>'),
        this.overlayer      = $('<div></div>');
        
        this.totalImage     = 0;
        this.loadedImage    = 0;
        this.imageReady     = false;

    },
    createPreloader : function()
    {
        if(this.loadable === false)
        {
            return;
        }
        
        this.loader.attr({
            'id'    : 'preloader'
        });
        
        this.loadProgress.attr({
            'id'    : 'loader-progress'
        });
        
        this.loaderDiv.attr({
            'id'    : 'loader-info'
        })
        .prepend(this.loader);
        
        this.overlayer.attr({
           'id'     : 'loader-overlayer'
        });
        
        this.loader.append(this.loadProgress);
        this._body.prepend(this.overlayer, this.loaderDiv);
    },
    loadWallpapers : function(json)
    {
        if(this.loadable === false)
        {
            return;
        }
        
        this.json           = json;
        var data = null,
            key  = '';
            
        if( Object.prototype.toString.apply( this.json.genres ) === "[object Array]" )
        {
            data    = this.json.genres;
            key     = 'bigsizeURL';
        }
        else if ( Object.prototype.toString.apply( this.json.movies ) === "[object Array]" )
        {
            data    = this.json.movies;
            key     = 'previewURL';
        }
        
        if( Object.prototype.toString.apply( data ) === "[object Array]" )
        {
            var wallpapers = new Array();
            for( var id in data )
            {
                var img = data[id];
                wallpapers[wallpapers.length] = this.imagePath + img[key];
            }
            this.wallpapers = wallpapers;
            this.loadImages();
        }

    },
    removeLoader : function()
    {
        this.loader.remove();
        this.loaderDiv.remove();
        this.loadProgress.remove();
        this.overlayer.remove();
    },
    preloaderComplete : function()
    {
        if(this.loadable === false)
        {
            return;
        }
        
        this.loadedImage +=1;
        var status = ( 0.5 + ((this.loadedImage/this.totalImage) * 100) ) << 0;
        
        if( this.loadedImage === this.totalImage )
        {
            this.imageReady = true;
            if( typeof (this.callback) === 'function' )
            {
                this.callback.call(this);
            }
        }
    },
    removeImages : function()
    {
        $('.'+this.imgClass).remove();
    },
    loadImages : function ()
    {
        if(this.loadable === false)
        {
            return;
        }
        
        var _this = this;
        this.totalImage     = (this.jq.isArray(this.wallpapers) === true ) ? this.wallpapers.length : 0;
        if( this.jq.isArray(this.wallpapers) === true )
        {
            for (var i = 0; i < this.wallpapers.length; i++)
            {
                var img     = new Image(),
                    $img    = $(img);
                    
                $img.attr({
                    'id':'wallpaper_preload_'+i
                })
                .css({
                    'display'     : 'none',
                    'position'    : 'absolute',
                    'width'       : '1px',
                    'height'      : '1px'
                })
                .addClass(this.imgClass);
                    
                this._body.append( $img );
                    
                $img.unbind('load');
                $img.bind('load', function(){
                    _this.preloaderComplete();
                });
                
                $img.attr('src', this.wallpapers[i]);
            }
        }
    }
};

jQuery.extend({
	openPopUp : function(url, options){
		options.height 		= options.height || 400;
		options.width 		= options.width || 400;
		options.top 		= options.top || 50;
		options.left 		= options.left || 50;
		options.scrollbars 	= (options.scollbars) ? "yes" : "no";
		var popup  = window.open(url, "popup", "width="+options.width+",height="+options.height+",scrollbars=yes, top=" +options.top + ",left=" +options.left);
		popup.focus();
	}
});
