//Application Specific global js functions


//specify page to pop-under
var popunder="http://www.happynight.com";

//specify popunder window features
var winfeatures="width=1024,height=600,scrollbars=1,resizable=1,toolbar=1,location=1,menubar=1,status=1,directories=0"

function loadornot(){
	if (Cookie.read('popunder')!='yes'){
		Cookie.write("popunder","yes", {domain: getDomain(window.location), path: '/'});
		loadpopunder();
	}
}

function loadpopunder(){
	var win2=window.open(popunder,"",winfeatures);
	if(typeof(win2) != 'undefined') {
		win2.blur();
		window.focus();
	}
}


function getDomain (thestring) {
	//simple function that matches the beginning of a URL
	//in a string and then returns the domain.
	var urlpattern = /(http|ftp|https):\/\/(.*?)(:.*?)?\/.*$/;
	urlpattern.exec(thestring);
	return RegExp.$2;
}

var myTips;
window.addEvent('load', function() {
	//Login Boxen
	$$('.overText').each(function(el) { new OverText(el) } );
	
	//if(	getDomain(window.location)!='www.happynight.de' && getDomain(window.location)!='happynight.de' &&
	//	getDomain(window.location)!='www.youpornflat.com' && getDomain(window.location)!='youpornflat.com')
	//	loadornot();
});

window.addEvent('domready', function() {
	// login required
	$$('.login-req').each(function(el){
		el.addEvent('click', function() {
			new MooPrompt("Login benötigt", new Element('div').set('html', registerHTML), {
				buttons: 0,
				width: 490,
				horizontal: 'center', vertical: 'middle', effect:'slide', 
				button1: 'Speichern',
				button2: 'Abbruch',
				overlay: true
			});
	
			return false;
		});
	});

	
	init_rating();
	$$(".rating").getChildren().each(function(star) {
		star.addEvent('click', submitRating);
	});
	
	// Add to fav.
	if ($('option-fav'))
		$('option-fav').addEvent('click', function(gallery_id) { fav(this, gallery_id); return false; }.bind($('option-fav')).pass(clip_id));
	
	$$('.option-fav').each(function(el2) {
		if (!el2.hasClass('login-req')) {
			gallery_id = getParentIntID(el2);
			el2.addEvent('click', function(gallery_id) { fav(this, gallery_id); return false; }.bind(el2).pass(gallery_id));
		}
	});
	
	
	
	/* tags */
	if ($('filter-box') && $('filter-taglist'))
	{
		var size = $('filter-search').getSize();
		$('filter-taglist').style.display = 'block';

		if ($('filter-tags-image').hasClass('tag-open'))
	    {
	        $('filter-taglist').fade('show');
	        $('filter-box').setStyle('height', $('filter-search').getSize().y + 'px');
	    }
	    else
	    {
	        $('filter-taglist').fade('hide');
	    }
	    $('filter-tags').addEvent('click', function(e)
	    {
	        e.stop();
	        var open = ($('filter-tags-image').hasClass('tag-open'));
	        var newsize = $('filter-search').getSize();
	        $('filter-taglist').fade(open ? '0' : '1')
	        $('filter-box').set('tween', {duration: 'short'}).tween('height', (open ? size.y : newsize.y) + 'px');
	        $('filter-tags-image').addClass('tag-'+(open ? 'closed' : 'open')).removeClass('tag-'+(open ? 'open' : 'closed'));
	    });
	}
});

function getParentIntID(el) {
	var parent = el.getParent();
	if(parent.getProperty('id') && parent.getProperty('id').test(/^[a-z]*?[0-9]*?/)) return parent.getProperty('id').replace(/\D/g,'');
	return getParentIntID(parent);
}

function fav(el, gallery_id)
{
	var isFav = el.hasClass('isFav');
	var isLivecam = document.getElementById('livecam_fav_'+gallery_id) ? true : false;
	el.addClass('loading');
	el.set('html', '');
	jslink('/DE/clips/' + (isFav ? 'del' : 'add') + 'Fav', {'id': gallery_id}, 'Content::' + (isFav ? 'del' : 'add') + 'Fav', function(result)
	{
		el.removeClass('loading');
		if (isLivecam) {
      el.set('html', !isFav ? '<img id="livecam_fav_' + gallery_id + '" class="favourite" title="Von Favoriten entfernen" alt="Von Favoriten entfernen" src="/images/livecams/no-favourite.jpg"/>' : '<img id="livecam_fav_' + gallery_id + '" class="favourite" title="Zu Favoriten hinzufügen" alt="Zu Favoriten hinzufügen" src="/images/livecams/favourite.jpg"/>');
    }
    else {
		  el.set('html', isFav ? '<span>Zu Favoriten hinzufügen</span>' : '<span>Von Favoriten entfernen</span>');
		}
		isFav ? el.removeClass('isFav') : el.addClass('isFav');
		el.removeEvents('click');
		el.addEvent('click', function(gallery_id) { fav(this, gallery_id); return false; }.bind(el).pass(gallery_id));
	}); 
	return false;
}

var NUMBER_OF_STARS = 5;

function init_rating()
{
    var ratings = document.getElementsByTagName('div');
    for (var i = 0; i < ratings.length; i++)
    {
        if (ratings[i].className != 'rating')
            continue;
            
        var rating = ratings[i].firstChild.nodeValue;
        ratings[i].removeChild(ratings[i].firstChild);
        if (rating > NUMBER_OF_STARS || rating < 0)
            continue;
        for (var j = 1; j <= NUMBER_OF_STARS; j++)
        {
            var star = new Element('div');
            if (rating >= 1)
            {
                // star.setAttribute('src', '/images/rating/rating_on.gif');
                star.addClass('starOn');
                star.className = 'on';
                rating--;
            }
            else if(rating == 0.5)
            {
                // star.setAttribute('src', '/images/rating/rating_half.gif');
                star.className = 'half';
                star.addClass('starHalf');
                rating = 0;
            }
            else
            {
                // star.setAttribute('src', '/images/rating/rating_off.gif');
                star.className = 'off';
                star.addClass('starOff');
            }
            var widgetId = ratings[i].getAttribute('id').substr(7);
            star.setAttribute('id', 'star_'+widgetId+'_'+j);
            
            star.addEvent('mouseover', function(widgetId,j) {displayHover(widgetId, j);}.pass([widgetId,j]));
            star.addEvent('mouseout', function(widgetId,j) {displayNormal(widgetId, j);}.pass([widgetId,j]));
            ratings[i].appendChild(star);
        } 
    }
}

function displayHover(ratingId, star)
{
    for (var i = 1; i <= star; i++)
    {
        // $('star_'+ratingId+'_'+i).setAttribute('src', '/images/rating/rating_over.gif');
    	$('star_'+ratingId+'_'+i).addClass('starHover');
    }
}

function displayNormal(ratingId, star)
{
    for (var i = 1; i <= star; i++)
    {
        var status = $('star_'+ratingId+'_'+i).className;
        // $('star_'+ratingId+'_'+i).setAttribute('src', '/images/rating/rating_'+status+'.gif');
        $('star_'+ratingId+'_'+i).removeClass('starHover');
    }
}

function submitRating(evt)
{
	var etarget = new Event(evt).target;
	var tmp = etarget.getAttribute('id').substr(5);
	var widgetId = tmp.substr(0, tmp.indexOf('_'));
	var starNbr = tmp.substr(tmp.indexOf('_')+1);
	jslink('/DE/clips/vote', {id:widgetId, value:starNbr}, 'Content::rate', function(result) {
		//etarget.set('html', starNbr)
	}); 
	
	
	//$$('#rating_'+widgetId+' *').removeEvent('mouseout');
	$$('#rating_'+widgetId+' *').removeEvents();
	$$('#rating_'+widgetId+' *').removeClass('on').addClass('off');
	displayNormal(widgetId, 5);
	displayHover(widgetId, starNbr);
	if($('rating_'+widgetId+'_fin')) $('rating_'+widgetId+'_fin').removeClass('hidden');
	if($('text-no-vote')) $('text-no-vote').set('html','erste Bewertung!');	
	//$('rating_'+widgetId).remove();
	
	//$('rating_'+widgetId).set('html', starNbr);
	//init_rating();
}

function correctHeight(el) {
	el.effect('height').set(el.getSize().scrollSize.y);	
}

function sendform(theForm, phpfunc, jsfunc) {
	var myRequest = new Request({
		'method': 'post',
		'url': $(theForm).get('action'),
		'onComplete': function(ret){
			if(ret=='error_login_required'){location.href='/'+LANG.LANG+'/nologin/';
			}else{jsfunc.attempt(ret);}
		},
		'onFailure': jsfunc.pass('failure'),
		'onSuccess': function(){
			if($$('.load')) $each($$('.load'), function(el){
				el.addClass('ok'); new Fx.Style(el, 'opacity').set(1);
			})
		},
		'onRequest': function(el){
			if($$('.load')) $each($$('.load'), function(el){
				el.removeClass('ok');  new Fx.Style(el, 'opacity').set(1);
			})
		}.pass($(theForm))
	}).send( $(theForm).toQueryString()+'&jscall='+phpfunc );
	return false;
}

function jslink(url, params, phpfunc, jsfunc, errorFallback) {
	if($type(jsfunc)==false) jsfunc = $empty;
	params['jscall'] = phpfunc;
	var call = new Request({url: url, method: 'post', data: params, onComplete: function(ret){if(ret=='error_login_required'){location.href='/'+LANG.LANG+'/nologin/';}else{jsfunc.attempt(ret);}}, onFailure: errorFallback}).send();
	return call;
}

function alterNate(elm){
	if (!elm.base) elm.base = elm.value
	if (elm.value == elm.base) elm.value = "";
	//else if (elm.value == "") elm.value = elm.base;
}

/**
 * an alternate alterNate :) using DOM defaults and returning default value on no changes
 */
function alterNate2(el)
{
	if (el.value == el.defaultValue)
		el.value = '';
	else if (el.value == '')
		el.value = el.defaultValue;
}

/**
 * Extends Array with 2 helpers: isSimilar(array) and complement(array)
 * 
 */
/*
Array.extend({
*/
	/**
	 * isSimilar - Returns true for similar arrays, type-insensitive
	 * 
	 * @example
	 *  [1].isSimilar(['1']) == true
	 *  [1, 2].isSimilar([1, false]) == false
	 *  
	 * @return	{Boolean}
	 * @param	{Object} Array
	 */
/*
	isSimilar: function(array) {
		return (this.toString() == array.toString());
	},
*/
	/**
	 * complement - Fills up empty array values from another array, length is the same
	 * 
	 * @example
	 *  [1, null].complement([3, 4]) == [1, 4]
	 *	[undefined, '1'].complement([2, 3, 4]) == [2, '1']

	 * @return	{Array} this
	 * @param	{Object} Array
	 */
/*
	complement: function(array) {
		for (var i = 0, j = this.length; i < j; i++) this[i] = $pick(this[i], array[i] || null);
		return this;
	}
	
});
*/
//get width of text element
function widthEl(el){
	if (document.layers){
	w=document.layers[el].clip.width;
	} else if (document.all && !document.getElementById){
	w=document.all[el].offsetWidth;
	} else if(document.getElementById){
	w=$(el).offsetWidth;
	}
	return w;
}

//get height of text element
function heightEl(el){
	if (document.layers){
	h=document.layers[el].clip.height;
	} else if (document.all && !document.getElementById){
	h=document.all[el].offsetHeight;
	} else if(document.getElementById){
	h=$(el).offsetHeight;
	}
	return h;
}

function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit)
	field.value = field.value.substring(0, maxlimit);
	else
	countfield.set('html', maxlimit - field.value.length);
}



var MooPrompt = box = new Class({
	setOptions: function(options){
		this.options = {
			buttons: 1,
			width: 300, // Set width of the box
			height: 0, // Set height of the box (0 = sized to content)
			maxHeight: 500, // Maximum height of the dialog box
			vertical: 'middle', // top middle bottom
			horizontal: 'center', // left center right
			delay: 0, // Delay before closing (0=no delay)
			overlay: true, // Cover the page
			effect: 'grow'
				// 'grow' - Expands box from a middle point and fades in content
				// 'slide' - Slides in the box from the nearest side.
			// button1: 'Ok' --- supply this for setting button text
			// onButton1: function --- supply function for button action
		};
		$extend(this.options, options);
	},
	
	initialize: function(title, content, options){
		this.setOptions(options);
		this.title = title;
		this.text = content;
		if (document.all && document.compatMode) {
			/*this.iframe = new Element('iframe').setStyles({
				'position': 'absolute', 'top': 0, 'left': 0,
				'height': Window.getScrollHeight()+'px', 'width': Window.getScrollWidth()+'px'
			}).setProperties({
				'frameborder': 0, 'scrolling': 'no'
			}).injectInside(document.body);*/
		}
		if (this.options.overlay) {
			if ($('cbOverlay')) {
				this.overlay = $('cbOverlay');
			} else {
				this.overlay = new Element('div').setProperty('id', 'cbOverlay');
				this.overlay.addEvent('click', this.close.pass([this.options['onButton'+this.options.buttons]], this));
				this.overlay.setStyles({
					'position': 'absolute', 'top': 0, 'left': 0, 'width': '100%', 'visibility': 'hidden'
				}).injectInside(document.body);
			}
		}
		this.container = new Element('div').setProperty('class', 'cbContainer');
		this.container.setStyles({
			'position': 'absolute', 'visibility': 'hidden'
		}).injectInside(document.body);
		this.box = new Element('div').setProperty('class', 'cbBox');
		this.box.setStyles({
			'width': this.options.width+'px',
			'overflow': 'auto'
		}).injectInside(this.container);
		this.header = new Element('h3').setProperty('class', 'headbar').appendText(this.title).injectInside(this.box);
		new Element('a').setProperty('class', 'cbClose pngfix').appendText("[schliessen]").addEvent('click', this.close.pass([this.options['onButton'+this.options.buttons]], this)).injectInside(this.header);
		this.content = new Element('div').setProperty('class', 'cbContent').injectInside(this.box);
		if ($type(content) == 'element' ) {content.injectInside(this.content);
		} else {this.content.appendText(this.text);}
		this.buttons = new Element('div').setProperty('class', 'cbButtons').injectInside(this.box);
		for (var i = 1; i <= this.options.buttons; i++) {
			if (typeof(this.options['button'+i]) == 'undefined') {
				this.options['button'+i] = 'Ok';
			}
			if ($type(this.options['button'+i]) == 'element') {
				this['button'+i] = this.options['button'+i]
				this['button'+i].injectInside(this.buttons);
			} else {
				this['button'+i] = new Element('input').setProperties({type: 'button', value: this.options['button'+i]}).injectInside(this.buttons);
			}
			if ($type(this.options['button'+i]) != 'function') {
				this.options['button'+i] = function() {};
			}
			this['button'+i].onclick = this.close.pass([this.options['onButton'+i]], this);
		}
		this.boxHeight = (this.box.offsetHeight < this.options.maxHeight) ? this.box.offsetHeight : this.options.maxHeight;
		this.boxHeight = (this.options.height > 0) ? this.options.height : this.boxHeight;
		this.box.setStyle('display', 'none');
		this._position();
		this.eventPosition = this._position.bind(this);
		window.addEvent('scroll', this.eventPosition).addEvent('resize', this.eventPosition);
		if (this.options.overlay && this.overlay.getStyle('visibility') == 'hidden') {
			this.fx1 = new Fx.Style(this.overlay, 'opacity', {duration:500}).start(0, .8);
		}
		if (this.options.effect == 'grow') {
			this.container.setStyle('top', (Window.getScrollTop()+(Window.getHeight()/2))+'px');
			var style = {}; style.height = 0; style.width = 0;
			if (this.options.horizontal != 'center') {
				style[this.options.horizontal] = (this.options.width/2)+'px';
			}
			if (this.options.vertical == 'top') {
				style[this.options.vertical] = (Window.getScrollTop()+(this.boxHeight/2))+'px';
			} else if (this.options.vertical == 'bottom') {
				style.top = (Window.getScrollTop()+Window.getHeight()-(this.boxHeight/2)-25)+'px';
			}
			this.container.setStyles(style);
			this.container.setStyle('visibility', '');
			this.fx2 = new Fx.Morph(this.container, {duration: 500});
			this.fx2.start({
				'width': [0, this.options.width], 'margin-left': [0, -this.options.width/2], 'margin-right': [0, -this.options.width/2],
				'height': [0, this.boxHeight], 'margin-top': [0, -this.boxHeight/2], 'margin-bottom': [0, -this.boxHeight/2]
			}).chain(function() {
				this.box.setStyles({
					'visibility': 'hidden', 'display': '', 'height': this.boxHeight+'px'
				});
				new Fx.Style(this.box, 'opacity', {duration: 500}).start(0, 1).chain(function() {
					this.box.setStyle('filter', '');
					if (this.options.delay > 0) {
						var fn = function () {
							this.close()
						}.bind(this).delay(this.options.delay);
					}
				}.bind(this));
			}.bind(this));
		} else {
			this.container.setStyles({
				'height': this.boxHeight, 'width': this.options.width,
				'left': '', 'visibility': 'hidden'
			});
			this.box.setStyles({
				'visibility': '', 'display': '', 'height': this.boxHeight+'px'
			});
			this.fx2 = new Fx.Morph(this.container, {duration: 500});
			var special = {};
			if (this.options.horizontal != 'center') {
				special[this.options.horizontal] = [-this.options.width, 0];
			} else {
				this.container.setStyles({
					'left': '50%', 'margin-left': (-this.options.width/2)+'px', 'margin-right': (-this.options.width/2)+'px'
				});
			}
			if (this.options.vertical == 'top') {
				special[this.options.vertical] = [Window.getScrollTop()-this.boxHeight, Window.getScrollTop()];
			} else if (this.options.vertical == 'bottom') {
				special.top = [Window.getScrollTop()+Window.getHeight(), Window.getScrollTop()+Window.getHeight()-this.boxHeight-25];
			} else {
				this.container.setStyles({
					'top': (Window.getScrollTop()+(Window.getHeight()/2))+'px', 'margin-top': (-this.boxHeight/2)+'px', 'margin-bottom': (-this.boxHeight/2)+'px'
				});
			}
			special.opacity = [0, 1];
			this.fx2.start(special).chain(function() {
				if (this.options.delay > 0) {
					var fn = function () {
						this.close()
					}.bind(this).delay(this.options.delay);
				}
			}.bind(this));
		}
	},
	
	_position: function() {
		var wHeight = (Window.getScrollHeight() > Window.getHeight()) ? Window.getScrollHeight() : Window.getHeight();
		var lr = (this.options.effect == 'grow') ? this.options.width/2 : 0;
		var tb = (this.options.effect == 'grow') ? this.boxHeight/2 : 0;
		if (this.iframe) {
			this.iframe.setStyles({
				'height': Window.getScrollHeight()+'px',
				'width': Window.getScrollWidth()+'px'
			});
		}
		if (this.options.overlay) {
			this.overlay.setStyles({height: wHeight+'px'});
		}
		switch(this.options.vertical) {
			case 'top':
				this.container.setStyle('top', (Window.getScrollTop()+tb)+'px');
				break;
			case 'middle':
				this.container.setStyle('top', (Window.getScrollTop()+(Window.getHeight()/2))+'px');
				break;
			case 'bottom':
				this.container.setStyle('top', (Window.getScrollTop()+Window.getHeight()-this.boxHeight+tb-25)+'px');
				break;
		}
		if (this.options.horizontal == 'center') {
			this.container.setStyle('left', '50%');
		} else {
			this.container.setStyle(this.options.horizontal, lr+'px');
		}
	},
	
	close: function(fn) {
		if (typeof(fn) == 'function') {var fnRet=fn(); if(fnRet==false){return false;}}
		for (var i = 1; i <= this.options.buttons; i++) {
			this['button'+i].onclick = null;
		}
		if ($type(this.fx1) == 'object') {
			this.fx1.cancel();
		}
		this.fx2.cancel();
		if (this.options.overlay && this.overlay.getStyle('opacity') == 0.8) {
			new Fx.Style(this.overlay, 'opacity', {duration:250}).start(0.8, 0);
		}
		new Fx.Style(this.container, 'opacity', {duration:250,
			onComplete: function() {
				window.removeEvent('scroll', this.eventPosition).removeEvent('resize', this.eventPosition);
				if (this.options.overlay) {
					this.overlay.dispose();
				}
				this.container.dispose();
				if (this.iframe) {
					this.iframe.dispose();
				}
			}.bind(this)
		}).start(1, 0);
	}
});

MooPrompt.implement(new Chain);