//
// GLOBAL VARIABLES
//
var external_site_title = "";
//
// RUN NOW
//

window.addEvent('domready', function() {
	if ($('bgselector')) switchPreviewBackground($('bgselector').value);
});


//
// FUNCTIONS
//

function toggleSNicon(val) {

	if (val == 1) {
		var snel = new Element('a', {
			href: '/index.php/home/post/Free_Poster',
			'class': 'myClass',
			'target': '_blank',
			html: '<img class="snicon" src="/images/smiling_nazi_icon.png" border="0" title="Smiling Nazi Award" alt="Smiling Nazi Award">'
		});
		snel.inject($('postpreview'), 'top');
	}
	else {
		$$('.snicon').getParent('a').dispose();
		$$('.snicon').dispose();
	}

}

function openExternalLink(title, url) {

	external_site_title = title;

	var html = '<iframe onload="externalLoaded();" src="' + url + '" frameborder="0" width="980" height="500"></iframe>';

	var title = '<div id=\"ext_site_title\"><img src="/images/wait_small.gif" border="0"> Please wait for the site to load ... (we are not responsible for the content of external sites)</div>'
	
	ccShowModalWindow(title, html, 1000);

}

function externalLoaded() {
	$('ext_site_title').innerHTML = external_site_title;
}

// COLOR FUNCTIONS

function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}

function complementColor(color) {

	color = color.replace("#", "");

	var red = parseInt(h2d(color.substring(0,2)));
	var green = parseInt(h2d(color.substring(2,4)));
	var blue = parseInt(h2d(color.substring(4,6)));

	if (red + green + blue >= 384) {
		return "#000000";
	}
	else {
		return "#FFFFFF";
	}
	
}

function darkenColor(color, percent) {

	color = color.replace("#", "");

	var red = h2d(color.substring(0,2));
	var green = h2d(color.substring(2,4));
	var blue = h2d(color.substring(4,6));

	red = d2h(parseInt(red - ((red / 100) * percent)));
	green = d2h(parseInt(green - ((green / 100) * percent)));
	blue = d2h(parseInt(blue - ((blue / 100) * percent)));

	if (red.length < 2) red = "0" + red;
	if (green.length < 2) green = "0" + green;
	if (blue.length < 2) blue = "0" + blue;

	newcolor = "#" + red + green + blue;

	if (newcolor.length == 7) {
		return newcolor;
	} else {
	    alert("error in color darken: " + newcolor);
	}
}

function lightenColor(color, percent) {

	color = color.replace("#", "");

	var red = h2d(color.substring(0,2));
	var green = h2d(color.substring(2,4));
	var blue = h2d(color.substring(4,6));

	red = d2h(parseInt(red + ((red / 100) * percent)));
	green = d2h(parseInt(green + ((green / 100) * percent)));
	blue = d2h(parseInt(blue + ((blue / 100) * percent)));

	if (red.length < 2) red = "0" + red;
	if (green.length < 2) green = "0" + green;
	if (blue.length < 2) blue = "0" + blue;

	newcolor = "#" + red + green + blue;

	if (newcolor.length == 7) {
		return newcolor;
	} else {
	    alert("error in color lighten: " + newcolor);
	}
}


// Modal Window functions require mootools javascript library

var g_RunOnClose = null;
var modalSpeed = 250;

// CONFIRM DIALOG

function confirmThis(txt, color, action) {

	html = ' \
		<div> \
		<div style="margin-bottom:10px;">' + txt + '</div>\
		<table width="100%" style="background:' + darkenColor(color, 20) + ';padding:3px;"><tr> \
		<td width="50%" align="left"><button type="button" style="color:darkgreen; width:150px;" onClick="ccHideModalWindow(); ' + action + '"><img class="icon" src="/images/icons/accept.png" /> CONFIRM</button></td> \
		<td width="50%" align="right"><button type="button" style="color:darkred; width:150px;" onClick="ccHideModalWindow();"><img class="icon" src="/images/icons/stop.png" /> CANCEL</button></td> \
		</tr></table> \
		</div>';

	ccShowModalWindow('', html, 400, '', '', true, color);
	
	return false;
		
}

// MUTLI-PURPOSE MODAL WINDOW

function ccShowModalWindow(title, data, width, givefocus, runonclose, sysmodal, color) {
	g_RunOnClose = runonclose;
	if (!color) color = 'white';
	if (title != '') {
		html = ' \
			<table border="0" cellspacing="0" cellpadding="2" width="100%" style="background:' + color + '; border:2px solid black;"> \
				<tr> \
					<td style="background:black; border-bottom:1px solid #999999;"> \
						<table border="0" cellspacing="0" cellpadding="0" width="100%"> \
							<tr> \
								<td width="100%" style="color:white;font-weight:bold; padding:0 2px 2px 2px;">' + title + '</td> \
								<td><div style="cursor:pointer;" onclick="ccHideModalWindow();"><img class="icon" src="/images/icons/close.png" /></div></td> \
							</tr> \
						</table> \
					</td> \
				</tr> \
				<tr> \
					<td style="padding:5px 5px 5px 5px; color:' + complementColor(color) + ';">' + data + '</td> \
				</tr> \
			</table>';
	}
	else {
		html = ' \
			<table border="0" cellspacing="0" cellpadding="2" width="100%" style="background:' + color + '; border:2px solid black;"> \
				<tr> \
					<td style="padding:5px 5px 5px 5px; color:' + complementColor(color) + ';">' + data + '</td> \
				</tr> \
			</table>';
	}
	makeOverlay(sysmodal);
	makeModalBox.pass([width, html, givefocus]).delay(modalSpeed);
}

function makeModalBox(mwidth, mtext, mfocus) {
	var size = window.getSize();
	var scroll = window.getScroll();
	var xcenter = (size.x / 2) + scroll.x;
	var ycenter = (size.y / 2) + scroll.y;
	var modalBox = new Element('div', {
	    'id': 'modalBox',
	    'html': mtext,
	    'styles': {
	        'display': 'block',
	        'position': 'absolute',
	        'z-index': '9999',
	        'width': mwidth,
	        'opacity': '0'
	    }
	});
	modalBox.inject(document.body);
	var elsize = $('modalBox').getSize();
	var putleft = xcenter - (elsize.x / 2);
	var puttop = ycenter - (elsize.y / 2);
	$('modalBox').setStyle('top',puttop);
	$('modalBox').setStyle('left',putleft);
	$('modalBox').set('tween', {duration: modalSpeed});
	$('modalBox').tween('opacity', '1');
	if (mfocus) {
		var focusSelect = function(){ $(mfocus).focus(); };
		focusSelect.delay(modalSpeed*2);
	}
}

function makeOverlay(sysmodal){
	var size = window.getScrollSize();
	var overlay = new Element('div', {
	    'id': 'overlay',
	    'html': '',
	    'styles': {
	        'display': 'block',
	        'position': 'absolute',
	        'z-index': '9990',
	        'background': 'black',
	        'height': size.y,
	        'width': size.x,
	        'top': '0',
	        'left': '0',
	        'opacity': '0'
	    }
	});
	overlay.inject(document.body);
	$('overlay').set('tween', {duration: modalSpeed});
	$('overlay').tween('opacity', '0.5');
	if (!sysmodal) $('overlay').addEvent('click', ccHideModalWindow);
	$$('embed').setStyle('visibility', 'hidden');
}

function ccHideModalWindow() {
	if ($('overlay') && $('modalBox'))
	{
		if (g_RunOnClose && g_RunOnClose != '')
		{
			eval(g_RunOnClose);
		}
		g_RunOnClose = null;
		$('overlay').fade('out');
		disposeOverlay.delay(500);
		$('modalBox').fade('out');
		disposeBox.delay(500);
		$$('embed').setStyle('visibility', 'visible');
	}
}

function disposeOverlay(el_overlay) {
	if ($('overlay')) $('overlay').dispose();
}

function disposeBox(el_modalbox) {
	if ($('modalBox')) $('modalBox').dispose();
}

/* MOOQUEE
 * Created By - Robert Inglin
 * Homepage   - http://robert.ingl.in/mooquee
 * License    - MIT License Agreement

Copyright (c) 2008 Robert Inglin

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
 */

Mooquee = new Class({
	Implements: [Options],

	options: {
		element: 'mooquee',
		cssitem: 'mooquee_item',
		firstitem:0,
		direction:'up', //up down left or right
		pause: 1, //seconds (keep pause equal or higher to duration to allow time for items to reset)
		duration: 1, //number of seconds to move marquee items
		overflow:'hidden', //if your item flows over how do you want to handle it. Auto(scroll) or Hidden work best...
		startOnLoad:true 
	},
	initialize: function(options){
		this.setOptions(options);
		this.itemFXs = [];
		this.started = false;
		this.currentitem = this.options.firstitem;
		this.loop = true;
		
		window.addEvent('domready', function() {
			//get all mooqueeItems
			this.items = $$('#' + this.options.element + ' .' + this.options.cssitem);
			this.totalitems = this.items.length;
			if($(this.options.element).style.overflow != 'hidden')
				$(this.options.element).style.overflow = 'hidden';
			if($(this.options.element).style.position != 'relative')
				$(this.options.element).style.position = 'relative';

			this.setMooqueeFXs();
			this.setDirection(this.options.direction);// has setMooqueeItems in it

			if(this.options.startOnLoad)
				this.mooveAll.delay(this.options.pause*1000 ,this);
		}.bind(this));
		
		
	},
	setMooqueeItems: function(){
		this.resetting =true;
		var i=0;
		
		this.items.each(function (element){
			if($(element).style.position != 'absolute')
				$(element).style.position = 'absolute';
			$(element).style.width = $(this.options.element).clientWidth + 'px';
			$(element).style.overflow = this.options.overflow;
			
			if(i == this.currentitem)
				startingposition =0;
			else
				startingposition = this.pixels;
			
			this.itemFXs[i].set(this.style,startingposition);
			this.itemFXs[i].set(this.antistyle,0);
			i++;
		}.bind(this));
		this.resetting =false;
	},
	setMooqueeFXs: function(){
		var i=0;
		this.items.each(function (element){
			this.itemFXs[i] = new Fx.Tween(element,{duration:(this.options.duration*1000)});
			i++;
		}.bind(this));
	},
	mooveAll: function(){

		this.previousitem = this.currentitem;
		
		if((this.currentitem + 1) == this.totalitems)
			this.currentitem = 0;
		else
			this.currentitem = this.currentitem + 1;
			
		this.moove(this.previousitem)
		this.moove(this.currentitem);

	},
	moove: function(itemnumber){
		if(itemnumber == this.previousitem)
			this.itemFXs[itemnumber].start(this.style,this.antipixels).chain(function(){
				if(!this.resetting)this.itemFXs[itemnumber].set(this.style,this.pixels);
			}.bind(this));
		else
			this.itemFXs[itemnumber].start(this.style,0).chain(function(){
				if(this.loop == true)
					this.loopTimer = this.mooveAll.delay(this.options.pause*1000 ,this);
			}.bind(this));
		
	},
	setDirection: function(newDirection){
		switch(newDirection){
				case 'up':
					this.style = 'top';
					this.antistyle = 'left'
					this.pixels = $(this.options.element).clientHeight;
					this.antipixels = this.pixels * -1;
				break;
				case 'down':
					this.style = 'top';
					this.antistyle = 'left';
					this.antipixels = $(this.options.element).clientHeight;
					this.pixels = this.antipixels * -1;
				break;
				case 'left':
					this.style = 'left';
					this.antistyle = 'top';
					this.pixels = $(this.options.element).clientWidth;
					this.antipixels = this.pixels * -1;
				break;
				case 'right':
					this.style = 'left';
					this.antistyle = 'top';
					this.antipixels = $(this.options.element).clientWidth;
					this.pixels = this.antipixels * -1;
				break;						
		}
		this.setMooqueeItems();
	}
});

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}
