var element_y;
var swiffy;
var cur_groupid;
var group_sortable = new Array();
var lightbox;
var content;
var docreatesortables = true;
var curSection;
var colors = new Array('green','blue','yellow','magenta','red','gray','tan');
var curColor = 0;

window.addEvent('domready', function()
{	
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);
	if ((version >= 5.5) && (document.body.filters)) 
	{
	   for(var i=0; i<document.images.length; i++)
	   {
	      var img = document.images[i]
	      var imgName = img.src.toUpperCase()
	      if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	      {
	         var imgID = (img.id) ? "id='" + img.id + "' " : ""
	         var imgClass = (img.className) ? "class='" + img.className + "' " : ""
	         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
	         var imgStyle = "display:inline-block;" + img.style.cssText 
	         if (img.align == "left") imgStyle = "float:left;" + imgStyle
	         if (img.align == "right") imgStyle = "float:right;" + imgStyle
	         if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
	         var strNewHTML = "<span " + imgID + imgClass + imgTitle
	         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
	         img.outerHTML = strNewHTML
	         i = i-1
	      }
	   }
	}
	checkFooter();
});

window.addEvent('resize', function(){
	checkFooter();
});

function faqsweep(url) {
	var g = new Array();
	for(var i=0; i<$$('.faqfooterman').length; i++) {
	}
	(function() { $$('.faqfooterman')[0].src = url; }).delay(0);
	(function() { $$('.faqfooterman')[1].src = url; }).delay(50);
	(function() { $$('.faqfooterman')[2].src = url; }).delay(100);
	(function() { $$('.faqfooterman')[3].src = url; }).delay(150);
	(function() { $$('.faqfooterman')[4].src = url; }).delay(200);
	(function() { $$('.faqfooterman')[5].src = url; }).delay(250);
	(function() { $$('.faqfooterman')[6].src = url; }).delay(300);
	(function() { $$('.faqfooterman')[7].src = url; }).delay(350);
	(function() { $$('.faqfooterman')[8].src = url; }).delay(400);
	(function() { $$('.faqfooterman')[9].src = url; }).delay(450);
	(function() { $$('.faqfooterman')[10].src = url; }).delay(500);
}

function checkFooter() {
	if(!$('footer')) return;
	$('footer').setStyle('display','none');
	var posy = window.getScrollSize().y;
	$('footer').setStyle('display','block');
	$('footer').setStyle('top', posy - 90 + 'px');
	
	$('footer').setStyle('left',(window.getSize().x / 2) - 440 + 'px');
}

function handReturn() {
	$('reasonbubble').setStyle('display','none');
}

function handOver(which,text) {
	
	
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);
	
	if((version >= 5.5) && (document.body.filters)) {
		var l = which.getBoundingClientRect().left;
		var t = which.getBoundingClientRect().top;
		var dl = window.getScrollSize().x;
	}else{
		var l = which.getPosition().x;
		var t = which.getPosition().y;
		var dl = window.getScrollSize().x;
	}
	
	
	if(!curSection) curSection = which;
	$('reasonbubble-reason1').innerHTML = text;
	$('reasonbubble-reason2').innerHTML = text;
	$('reasonbubble').setStyle('display','block');
	
	if(l > dl / 2) {
		$('reasonbubble').setStyle('left',(l-265) + 'px');
		$('reasonbubble').setStyle('top',(t-105) + 'px');
		$('reasonbubble1').setStyle('display','none');
		$('reasonbubble2').setStyle('display','block');
		$('reasonbubble-reason1').setStyle('display','none');
		$('reasonbubble-reason2').setStyle('display','block');
	}else{
		$('reasonbubble').setStyle('left',(l+65) + 'px');
		$('reasonbubble').setStyle('top',(t-100) + 'px');
		$('reasonbubble1').setStyle('display','block');
		$('reasonbubble2').setStyle('display','none');
		$('reasonbubble-reason1').setStyle('display','block');
		$('reasonbubble-reason2').setStyle('display','none');
	}
}

function uploaddone(data) {
	$('file_id').value = data;
	//lightbox.refresh();
}


function checkSetWidths() {
	for ( var i=0; i<$$('.admin_thumbs').length; i++ )
		checkWidth($$('.admin_thumbs')[i]);
}

function loadLightbox() {
	lightbox = new Element('div', {
		'class': 'lightbox'
	});
	content = new Element('div', {
		'class': 'content',
		'text': '' 
	});
	
	lightbox.addEvent('click', function() { killLightbox(); });
	
	$('body_container').adopt(lightbox);
	window.addEvent('resize',function() { centerItem(content); lightbox.setStyle('height',window.getScrollSize().y+'px'); });
	window.addEvent('scroll',function() { centerItem(content); });
	lightbox.setStyle('height',window.getScrollSize().y+'px');
}

function editImage(image_id) {
	loadLightbox();
	new Request({
		data: { image_id: image_id },
		url: base_url + 'ajax/image/edit/',
		onComplete: function(response) { 
			$('body_container').adopt(content);
			content.innerHTML = response;
			centerItem(content);
		}
	}).send();
}

function setupUpload(url,args) {
	swiffy = new FancyUpload2($('demo-status'), $('demo-list'), {
			'instantStart': true,
			'url': url,
			'fieldName': 'photoupload',
			'allowDuplicates': true,
			'path': base_url + '/assets/swf/Swiff.Uploader.swf',
			'onLoad': function() {
				addMoreImages();
			},
			'onAllComplete': function() {
				lightbox.hide();
				if(args.onComplete)
				args.onComplete();
			},
			'onCancel': function() {
				lightbox.hide();
			}
	});
}

function addMoreImages() {
	swiffy.browse({'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'});
}

function form_submit(form,response_container,args) {
	if(response_container)
	response_container.value = "saving...";
	new Request({
		url: form.action,
		data: form,
		method: form.method ? form.method : 'post',
		onComplete: function(response) { 
			//window.location.reload();
			if(response_container)
			response_container.value = 'saved';
			if(args && args.onComplete) args.onComplete();
		}
	}).send();
}

function addGroup(group_id) {
	if(!group_id) group_id = false;
	loadLightbox();
	new Request({
		data: { group_id: group_id },
		url: base_url + 'ajax/group/edit/',
		onComplete: function(response) { 
			$('body_container').adopt(content);
			content.innerHTML = response;
			centerItem(content);
		}
	}).send();
}

function submitForm(which) {
	var myHTMLRequest = new Request.HTML({url: which.action, onComplete: function() { window.location.reload(); } }).post(which);
}

function killLightbox() {
	content.destroy(); 
	lightbox.destroy();
}

function centerItem(content) {
	content.setStyle('top',(window.getScroll().y + (document.getSize().y / 2)-(content.getSize().y/2))+'px');
	content.setStyle('left',((document.getSize().x / 2)-(content.getSize().x/2))+'px');
}

function loadImageGroup(group_id) {
	new Request({
		data: { group_id: group_id },
		url: base_url + 'ajax/group/admin_thumbs/'+group_id,
		onComplete: function(response) { 
			$('group_'+group_id+'_container').innerHTML = response;
			createSortable();
			for(var i=0; i<$$('.admin_thumbs').length; i++) { 
				checkWidth($$('.admin_thumbs')[i]);
			}
		}
	}).send();
}

function createSortable() {	
	var me = new Sortables('.admin_thumbs', {
		opacity:.25,
		clone: true,
		revert: true,
		constrain: false,
		onSort: function(r) {
			for(var i=0; i<$$('.admin_thumbs').length; i++) { 
				checkWidth($$('.admin_thumbs')[i]);
			}
		},
		initialize: function(){
			for(var i=0; i<$$('.admin_thumbs_container').length; i++) { 
				this.scroller = new Scroller($$('.admin_thumbs_container')[i], { area:100, velocity:0.15, onChange: function(x, y){
					this.element.scrollTo(x, 0);
				} });
				this.addEvent('onStart', function(e){ e.setStyle('z-index','1000'); this.scroller.start(); });
				this.addEvent('onComplete', function(){ this.scroller.stop(); });
			}
		},
		onComplete: function(r) {
			new Request({
				url: base_url + 'ajax/admin/save_order/3',
				data: { items: me.serialize(false,function(element, index){
					return element.getProperty('id') + element.getParent().getProperty('id').replace('_admin_thumbs','').replace('group','').replace('item','').replace('children','') + index;
				    return element.getParent().getProperty('id').replace('_admin_thumbs','').replace('group','') + element.getProperty('id').replace('imagetogroup','') + '_' + index;
				}) }
			}).send();
		}
	});
	
	var me2 = new Sortables('.sections', {
		opacity: .25,
		clone: true,
		revert: true,
		constrain: false,
		handle: 'h1',
		onComplete: function(r) {
			new Request({
				url: base_url + 'ajax/admin/save_order/3',
				data: { items: me2.serialize(false,function(element, index){
					return element.getProperty('id') + '_0_' + index;
				    return element.getParent().getProperty('id').replace('_admin_thumbs','').replace('group','') + '_' + element.getProperty('id').replace('imagetogroup','') + '_' + index;
				}) }
			}).send();
		}
	});
}

function checkWidth(obj) {
	var total = 20;
	var kids = obj.getChildren();
	for(var i=0; i<kids.length; i++) { 
		total += kids[i].getSize().x + 8;
	}
	var big = document.getSize().x - 80;
	total = total > big ? total : big;
	obj.setStyle('width',total);
}

function delete_obj(args) {
	if(!confirm("Are you absolutely sure you'd like to delete this?")) return;
	new Request({
		url: base_url + 'ajax/misc/delete',
		data: args,
		method: 'post',
		onComplete: function(response) { 
			args.node.destroy();
			if(args.onComplete)
			args.onComplete();
		}
	}).send();
}

function makeScrollbar(content,checkContent,scrollbar,handle,horizontal,ignoreMouse){
	
	if(checkContent.getScrollSize().x < scrollbar.getSize().x) {
		handle.setStyle('display','none');
		return;
	}
	
	handle.setStyle('display','block');

	var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))
	var slider = new Slider(scrollbar, handle, {	
		steps: steps,
		mode: (horizontal?'horizontal':'vertical'),
		onChange: function(step){
			// Scrolls the content element in x or y direction.
			var x = (horizontal?step:0);
			var y = (horizontal?0:step);
			content.scrollTo(x,y);
		}
	}).set(0);
	if( !(ignoreMouse) ){
		// Scroll the content element when the mousewheel is used within the 
		// content or the scrollbar element.
		$$(content, scrollbar).addEvent('mousewheel', function(e){	
			e = new Event(e).stop();
			var step = slider.step - e.wheel * 30;	
			slider.set(step);					
		});
	}
	// Stops the handle dragging process when the mouse leaves the document body.
	//$(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
}

function refreshItem(who,args) {
	loadURL(who.get('url'),who,args);
}

function loadURL(url,div,args) {
	div.set('url',url);
	new Request({
		url: url,
		data: args,
		onComplete: function(response) { 
			div.innerHTML = response;
			if(args && args.onComplete)
			args.onComplete();
		}
	}).send();
}

var LightBox = new Class({

	options: {/*
		onSort: $empty,
		onStart: $empty,
		onComplete: $empty,*/
		snap: 4,
		opacity: 1
	},

	initialize: function(){
		this.kids = 0;
		this.bgs = new Array();
		this.contents = new Array();
		this.args_recall = new Array();
	},
	
	loadURL: function(url,args)
	{
		if(!args || !args.use_current)
		this.show(args);
		
		var textareas = $$('.tinymce_input');
		for(var i=0; i<textareas.length; i++) {
			tinyMCE.execCommand('mceRemoveControl', true, 'tinymce_input_'+i);
		}
		
		var me = this;
		var content = me.contents[me.contents.length-1];
		content.set('url',url);
		
		new Request({
			url: url,
			data: args,
			method: 'post',
			onComplete: function(response) { 
				content.set('html',response);
				me.centerItem(content);
				if(args && args.onComplete) args.onComplete();
				
				var textareas = $$('.tinymce_input');
				var ref;
				for(var i=0; i<textareas.length; i++) {
					ref = tinyMCE.execCommand('mceAddControl', true, 'tinymce_input_'+i);
				}
				//ref.focus();
			}
		}).send();
	},
	
	show: function(args) {
		var me = this;
		
		this.kids++;
		
		var bg = new Element('div', {
			'class': 'lightbox'
		});
		this.bgs.push(bg);
		
		var content = new Element('div', {
			'class': 'content'	
		});
		this.contents.push(content);
		
		var loading = new Element('img', {
			'src': base_url + 'assets/images/loading.gif'	
		});
		
		this.args_recall.push(args);
		
		bg.addEvent('click', function() { me.hide(); });

		document.body.adopt(bg);
		content.adopt(loading);
		document.body.adopt(content);
		
		this.centerItem(content);
		
		window.addEvent('resize',function() { me.centerItem(content); bg.setStyle('height',window.getScrollSize().y+'px'); });
		//window.addEvent('scroll',function() { me.centerItem(content); });
		bg.setStyle('height',window.getScrollSize().y+'px');
		bg.setStyle('width','100%');
		
		me.center();
	},
	
	hide: function(args){
		var textareas = $$('.tinymce_input');
		for(var i=0; i<textareas.length; i++) {
			tinyMCE.execCommand('mceRemoveControl', true, 'tinymce_input_'+i);
		}
		
		if(!args) args = this.args_recall[this.args_recall.length-1];
		if(args && args.onHide) args.onHide();
		
		var me = this;
		me.contents[me.contents.length-1].destroy();
		me.bgs[me.bgs.length-1].destroy();
		me.bgs.pop();
		me.contents.pop();
		me.args_recall.pop();
		
		var textareas_now = $$('.tinymce_input');
		for(var i=0; i<textareas_now.length; i++) {
			tinyMCE.execCommand('mceAddControl', true, 'tinymce_input_'+i);
		}
	},
	
	refresh: function(args) {
		var who = this.contents[this.contents.length-1];
		if(!args) args = this.args_recall[this.args_recall.length-1];
		new Request({
			url: who.get('url'),
			data: args,
			onComplete: function(response) { 
				who.innerHTML = response;
				if(args && args.onComplete) args.onComplete();
				lightbox.center();
			}
		}).send();
	},
	
	centerItem: function(content) {
		var top = ((window.getScroll().y + (window.getSize().y / 2)-(content.getSize().y/2)));
		if(top < 20) top = 20;
		content.setStyle('top',top+'px');
		content.setStyle('left',((window.getSize().x / 2)-(content.getSize().x/2))+'px');
	},
	
	center: function() {
		this.centerItem(this.contents[this.contents.length-1]);
	}

});