/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 */

(function($) {

$.event.special.mousewheel = {
	setup: function() {
		var handler = $.event.special.mousewheel.handler;
		
		// Fix pageX, pageY, clientX and clientY for mozilla
		if ( $.browser.mozilla )
			$(this).bind('mousemove.mousewheel', function(event) {
				$.data(this, 'mwcursorposdata', {
					pageX: event.pageX,
					pageY: event.pageY,
					clientX: event.clientX,
					clientY: event.clientY
				});
			});
		if ( this.addEventListener )
			this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		var handler = $.event.special.mousewheel.handler;
		
		$(this).unbind('mousemove.mousewheel');
		
		if ( this.removeEventListener )
			this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = function(){};
		
		$.removeData(this, 'mwcursorposdata');
	},
	
	handler: function(event) {
		var args = Array.prototype.slice.call( arguments, 1 );
		
		event = $.event.fix(event || window.event);
		// Get correct pageX, pageY, clientX and clientY for mozilla
		$.extend( event, $.data(this, 'mwcursorposdata') || {} );
		var delta = 0, returnValue = true;
		
		if ( event.wheelDelta ) delta = event.wheelDelta/120;
		if ( event.detail     ) delta = -event.detail/3;
//		if ( $.browser.opera  ) delta = -event.wheelDelta;
		
		event.data  = event.data || {};
		event.type  = "mousewheel";
		
		// Add delta to the front of the arguments
		args.unshift(delta);
		// Add event to the front of the arguments
		args.unshift(event);

		return $.event.handle.apply(this, args);
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});

})(jQuery);

/* Copyright (c) 2006 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };
	
	return this.each(
		function()
		{
			var $this = $(this);
			// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
			$this.css('overflow', 'hidden');
			var paneEle = this;
			
			if ($(this).parent().is('.jScrollPaneContainer')) {
				var currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				var paneWidth = $c.innerWidth();
				var paneHeight = $c.outerHeight();
				var trackHeight = paneHeight;
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown', $c).remove();
				$this.css({'top':0});
			} else {
				var currentScrollPosition = 0;
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				var paneWidth = $this.innerWidth();
				var paneHeight = $this.innerHeight();
				var trackHeight = paneHeight;
				var $container = $('<div></div>')
					.attr({'className':'jScrollPaneContainer'})
					.css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					);
				if (settings.enableKeyboardNavigation) {
					$container.attr(
						'tabindex', 
						settings.tabIndex
					);
				}
				$this.wrap($container);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);
				
			}
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];
				
				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load readystatechange', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
								$this.jScrollPane(s2); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

			var cssToApply = {
				'height':'auto',
				'width': realPaneWidth + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;

			if (percentInView < .99) {
				var $container = $this.parent();
				$container.append(
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div><div></div></div>')
						)
					)
				);
				
				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				
				var currentArrowDirection;
				var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
				var currentArrowInc;
				var whileArrowButtonDown = function() 
				{
					if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
						positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
					}
					currentArrowInc++;
				};

				if (settings.enableKeyboardNavigation) {
					$container.bind(
						'keydown.jscrollpane',
						function(e) 
						{
							switch (e.keyCode) {
								case 38: //up
									currentArrowDirection = -1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 40: //down
									currentArrowDirection = 1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 33: // page up
								case 34: // page down
									// TODO
									return false;
								default:
							}
						}
					).bind(
						'keyup.jscrollpane',
						function(e) 
						{
							if (e.keyCode == 38 || e.keyCode == 40) {
								for (var i = 0; i < currentArrowTimerArr.length; i++) {
									clearInterval(currentArrowTimerArr[i]);
								}
								return false;
							}
						}
					);
				}

				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowInterval;

					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowUp', 'tabindex':-1})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowDown', 'tabindex':-1})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
					if (settings.arrowSize) {
						trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
						$track
							.css({'height': trackHeight+'px', top:settings.arrowSize+'px'})
					} else {
						var topArrowHeight = $upArrow.height();
						settings.arrowSize = topArrowHeight;
						trackHeight = paneHeight - topArrowHeight - $downArrow.height();
						$track
							.css({'height': trackHeight+'px', top:topArrowHeight+'px'})
					}
				}
				
				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
					return false;
				};
				
				$track.bind('mousedown', onTrackClick);
				
				$container.bind(
					'mousewheel',
					function (event, delta) {
						delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						$e = $(pos, $this);
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					$container.scrollTop(0);
					ceaseAnimation();
					var maxScroll = contentHeight - paneHeight;
					pos = pos > maxScroll ? maxScroll : pos;
					$this.data('jScrollPaneMaxScroll', maxScroll);
					var destDragPosition = pos/maxScroll * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
						}
						
						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				
				if (location.hash) {
					setTimeout(function() {scrollTo(location.hash);}, $.browser.safari ? 100 : 0);
				}
				
				// use event delegation to listen for all clicks on links and hijack them if they are links to
				// anchors within our content...
				$(document).bind(
					'click',
					function(e)
					{
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h && h.substr(0, 1) == '#' && h.length > 1) {
								setTimeout(function() {scrollTo(h, !settings.animateToInternalLinks);}, $.browser.safari ? 100 : 0);
							}
						}
					}
				); 
				
				// Deal with dragging and selecting text to make the scrollpane scroll...
				function onSelectScrollMouseDown(e)
				{
				   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
				   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
				  
				}
				
				var textDragDistanceAway;
				var textSelectionInterval;
				
				function onTextSelectionInterval()
				{
					direction = textDragDistanceAway < 0 ? -1 : 1;
					$this[0].scrollBy(textDragDistanceAway / 2);
				}

				function clearTextSelectionInterval()
				{
					if (textSelectionInterval) {
						clearInterval(textSelectionInterval);
						textSelectionInterval = undefined;
					}
				}
				
				function onTextSelectionScrollMouseMove(e)
				{
					var offset = $this.parent().offset().top;
					var maxOffset = offset + paneHeight;
					var mouseOffset = getPos(e, 'Y');
					textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
					if (textDragDistanceAway == 0) {
						clearTextSelectionInterval();
					} else {
						if (!textSelectionInterval) {
							textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
						}
					}
				}

				function onSelectScrollMouseUp(e)
				{
				   $(document)
					  .unbind('mousemove.jScrollPaneDragging')
					  .unbind('mouseup.jScrollPaneDragging');
				   clearTextSelectionInterval();
				}

				$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

				
				$.jScrollPane.active.push($this[0]);
				
			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				$this[0].scrollTo = $this[0].scrollBy = function() {};
				// clean up listeners
				$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
			}
			
		}
	)
};

$.fn.jScrollPaneRemove = function()
{
	$(this).each(function()
	{
		$this = $(this);
		var $c = $this.parent();
		if ($c.is('.jScrollPaneContainer')) {
			$this.css(
				{
					'top':'',
					'height':'',
					'width':'',
					'padding':'',
					'overflow':'',
					'position':''
				}
			);
			$c.after($this).remove();
		}
	});
}

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	tabIndex : 0,
	enableKeyboardNavigation: true,
	animateToInternalLinks: false
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);

$('.scroll-pane').jScrollPane({
	showArrows:true,
	scrollbarWidth:25,
	scrollbarMargin:0
});

var _forms = $('form');
var inputs = new Array();
var selects = new Array();
var labels = new Array();
var radios = new Array();
var radioLabels = new Array();
var checkboxes = new Array();
var checkboxLabels = new Array();
var selectText = "Select";
var _selectHeight = 21;
var __sAll = false;
var openedSelect = null;

function customForms() {
	getFormElements();
	getFormRelations();
	customRadios();
	replaceCheckboxes();
	replaceSelects();
}

// find all form elements will be replaced
function getFormElements() {
	$('form').each(function(){
		$(this).find('input').each(function(){
			if(!$(this).hasClass('customizedElement')) inputs.push($(this));
		});
		$(this).find('label').each(function(){
			try{
				if($('#' + $(this).attr('for'))){
					if(!$('#' + $(this).attr('for')).hasClass('customizedElement')) labels.push($(this));
				}
			} catch(__err) {}
		});
		$(this).find('select').each(function(){
			if(!$(this).hasClass('customizedElement')) selects.push($(this));
		});
	});
}

// find all relations by for attributes
function getFormRelations() {
	var __r = 0;
	var __c = 0;
	var __rl = 0;
	var __cl = 0;
	radios = [];
	radioLabels = [];
	checkboxes = [];
	checkboxLabels = [];
	for(var __i=0;__i<inputs.length;__i++) {
		if(inputs[__i].attr('type')=='radio') {
			radios[__r]=inputs[__i];
			++__r;
			for(var __l=0;__l<labels.length;__l++) {
				if((inputs[__i].attr('id')) && labels[__l].attr('for') == inputs[__i].attr('id')) {
					radioLabels[__rl] = labels[__l];++__rl;
				}
			}
		}
		if(inputs[__i].attr('type')=='checkbox') {
			checkboxes[__c]=inputs[__i];
			++__c;
			for(var __l=0;__l<labels.length;__l++) {
				if((inputs[__i].attr('id')) && labels[__l].attr('for') == inputs[__i].attr('id')) {
					checkboxLabels[__cl] = labels[__l];++__cl;
				}
			}
		}
	}
}

// RADIOS
//customize radio buttons
function customRadios() {
	for (var __r = 0; __r < radios.length; __r++) {
		if(!radios[__r].hasClass('customizedElement')){
			radios[__r].addClass('customizedElement');
			var replacedRadiobutton = $('<div></div>');
			if(radios[__r].attr('checked')==true) {
				replacedRadiobutton.addClass('customRadioChecked');
			} else {
				replacedRadiobutton.addClass('customRadio');
			}
			replacedRadiobutton.attr('id','customRadio'+__r);
			radios[__r].parent().prepend(replacedRadiobutton);
			radios[__r]._custom = replacedRadiobutton;
			replacedRadiobutton.click(function(){
				var _clickIndex = $(this).attr('id').replace('customRadio','');
				toggleRadio(_clickIndex);
			});
			if (radioLabels[__r]) {
				radioLabels[__r].click(function(){
					if($(this).parent().find('.customRadio').attr('id')) {
						checkRadio($(this).parent().find('.customRadio').attr('id').replace('customRadio',''));
					}
					if($(this).parent().find('.customRadioChecked').attr('id')) {
						checkRadio($(this).parent().find('.customRadioChecked').attr('id').replace('customRadio',''));
					}
				});
			}
		}
	}
	return true;
}

//check radio button
function checkRadio(__index) {
	var customAppr = radios[__index]._custom;
	for(var __r = 0;__r < radios.length;__r++) {
		if(radios[__r]._custom || radios[__r]._custom!='undefined'){
			if((radios[__r]._custom.hasClass('customRadioChecked')) && radios[__r]._custom.attr('name')==customAppr.attr('name')) {
				radios[__r]._custom.attr('class','customRadio');
			}
		}
	}
	customAppr.attr('class','customRadioChecked');
}

//toggle radio buttons
function toggleRadio(__index) {
    for(var __r = 0; __r < radios.length; __r++) {
        if(radios[__r].attr('name') == radios[__index].attr('name')) {
			radios[__r].attr('checked',false).removeClass('checked');
		}
        radios[__index].attr('checked',true).addClass('checked');
        checkRadio(__index);
    }
}

// CHECKBOXES
//customize checkboxes
function replaceCheckboxes() {
	for (var __c=0;__c<checkboxes.length;__c++) {
        if(!checkboxes[__c].hasClass('customizedElement')){
            checkboxes[__c].addClass('customizedElement')
            var replacedCheckbox = $('<div></div>');
            if(checkboxes[__c].attr('checked')==true) replacedCheckbox.addClass('customCheckboxChecked')
			else replacedCheckbox.addClass('customCheckbox');
			replacedCheckbox.attr('id','customCheckbox'+__c);
			checkboxes[__c].parent().prepend(replacedCheckbox);
			checkboxes[__c]._custom = replacedCheckbox;
			replacedCheckbox.click(function(){
				var _clickIndex = $(this).attr('id').replace('customCheckbox','');
				retoggleCheckbox(_clickIndex);
			});
			if (checkboxLabels[__c]) checkboxLabels[__c].click(function(){
                if($(this).parent().find('.customCheckbox').attr('id')) {
					toggleCheckbox($(this).parent().find('.customCheckbox').attr('id').replace('customCheckbox',''));
				}
				if($(this).parent().find('.customCheckboxChecked').attr('id')) {
					toggleCheckbox($(this).parent().find('.customCheckboxChecked').attr('id').replace('customCheckbox',''));
				}
			});
            checkboxes[__c].onkeydown = checkBySpace;
        }
    }
	return true;
}

//checking checkboxes
function checkCheckbox(__index, __state) {
	var customAppr = checkboxes[__index]._custom;
	if(__state==true) {
		customAppr.attr('class','customCheckboxChecked');
		customAppr.attr('checked',true);
	}
	if(__state==false) {
		customAppr.attr('class','customCheckbox');
		customAppr.attr('checked',false);
	}
}

//changing checkboxes
function toggleCheckbox(__index) {
	if(checkboxes[__index].attr('checked') == true) checkCheckbox(__index, false)
    else checkCheckbox(__index, true);
}

//rechanging checkboxes
function retoggleCheckbox(__index) {
	var _state = false;
	if(checkboxes[__index].attr('checked') == true) _state = false;
	else _state = true;
	checkboxes[__index].attr('checked',_state);
	checkCheckbox(__index, _state);
}

//check event
function checkBySpace(e) {
	if (!e) var e = window.event;
	if(e.keyCode == 32) {
        for (var __c = 0; __c < checkboxes.length; __c++) {
            if(this == checkboxes[__c]) changeCheckboxes(__c);
        }
    }
}

// SELECTS
// customize selects
function replaceSelects() {
	for(var __s=0;__s<selects.length;__s++) {
        if (!selects[__s].hasClass('customizedElement') && selects[__s].width()){
            selects[__s]._ind = __s;
            var replacedSelect = $('\
                <div class="customSelect">\
                    <span class="bg-select-left"></span>\
                    <span style="display: none;" class="disabled"></span>\
                    <span class="bg-select-center" id="customSelectText' + __s + '">' + selectText + '</span>\
                    <a href="javascript:displayOptions(\'' + __s + '\')" class="selectButton"></a>\
                </div>');
            //selects[__s]._disabled = selects[__s].find('span.bg-select-disabled');
            var _selectWidth = selects[__s].width();
            replacedSelect.css('width',_selectWidth);
            replacedSelect.addClass(selects[__s].attr('class'));
            replacedSelect.attr('id','customSelect'+__s);
            selects[__s].addClass('customizedElement');
            selects[__s].parent().prepend(replacedSelect);
            
            var replacedOptions = $('<div id="customOptions' + __s + '"></div>');
            var replacedOptionsUl = $('<ul></ul>');
            replacedOptions.append(replacedOptionsUl);
            replacedOptions.css('width',parseInt(_selectWidth)-2);
            selects[__s]._options = replacedOptionsUl;
            replacedOptions._parent = replacedSelect;
            replaceOptions(selects[__s]);
            $('body').append(replacedOptions);
            replacedOptions.html('<div class="select-holder"><div class="select-t"><div>&nbsp;</div></div><div class="scroll-pane">'+replacedOptions.html()+'</div><div class="select-bt"><div>&nbsp;</div></div></div>')
			replacedOptions.addClass('customOptionsHidden');
        }
        __sAll = true;
	}
}

// customize select options
function replaceOptions(__select) {
	__select._options.html('');
	var _opts = '';
	__select.find('option').each(function(__s){
		if($(this).parent().attr('id')){
			_opts += '<li><a href="javascript:displayOptions(\'' +__select._ind+ '\'); customSelectEvent(\'' + $(this).parent().attr("id") + '\',' + __s + ',' + __select._ind + ');">' + $(this).text() + '</a></li>';
			if($(this).attr('selected')) customSelectEvent($(this).parent().attr('id'),__s,__select._ind);
		}else{
			_opts += '<li><a href="javascript:displayOptions(\'' +__select._ind+ '\'); customSelectEvent(\'\',' + __s + ',' + __select._ind + ');">' + $(this).text() + '</a></li>';
			if($(this).attr('selected')) customSelectEvent('',__s,__select._ind);
		}
	});
	__select._options.html(_opts);

    /*
	if (__select.disabled) __select._disabled.show();
	else __select._disabled.hide();
	*/
}

// option check function
function customSelectEvent(_selectId,_optionId,_selectIndex) {
	customAppr = selects[_selectIndex];
	customAppr.find('option').each(function(optionId){
		if(optionId==_optionId) {$(this).attr('selected',true);}
		else $(this).attr('selected',false);
	});
	_customSelectText = $('#customSelectText' + _selectIndex);
	var _customSelectTextNew;
	_customSelectTextNew = customAppr.find('option').eq(_optionId).text();
	_customSelectText.html(_customSelectTextNew);
	if (customAppr.change && __sAll){
		eval(customAppr.change());
	}
	hideOptions();
}

//show options
function displayOptions(___selectId) {
		var _customOptions = $('#customOptions' + ___selectId);
		var _customSelect = $('#customSelect'+___selectId);
		if (openedSelect && openedSelect != _customOptions) {
			openedSelect.removeClass('customOptionsHidden');
			openedSelect.addClass('customOptions');
			openedSelect.css('height','auto');
		}
		if(_customOptions.hasClass('customOptionsHidden')) {
			_customOptions.css({
				'left':'-9999px',
				'top':getTopPosition(_customSelect) + _selectHeight + 'px'
			});
			hideOptions();
			_customOptions.removeClass('customOptionsHidden');
			_customOptions.addClass('customOptions')
			.addClass('customOptionsActive');
			_customSelect.addClass('customSelectActive');
			_customOptions.css('left',getLeftPosition(_customSelect) + 'px')
			openedSelect = _customOptions;
			
			//if(document.documentElement) document.documentElement.onclick = hideOptions
			//else window.onclick = hideOptions;
			$(document).click(function(e){
				if($(e.target).parents('div.customSelect').length == 0 && $(e.target).parents('div.customOptions').length == 0){
					hideOptions();
				}
			});

		} else if(_customOptions.hasClass('customOptions')) {
			_customOptions.css('height','auto');
			_customOptions.removeClass('customOptions');
			_customOptions.addClass('customOptionsHidden');
			hideOptions(); //hide
		}
}

// hide options
function hideOptions(){
	if(openedSelect){
		$('.customOptions').each(function(){
			$(this).removeClass('customOptions');
			$(this).addClass('customOptionsHidden');
		});
		$('.customSelectActive').each(function(){
			$(this).removeClass('customSelectActive');
		});
		openedSelect = false;
		//$(document).unbind('click');
	}
}

// options Y position
function getTopPosition(_obj) {
	var _topPosition = 0;
	var __offset = _obj.offset();
	_topPosition = __offset.top;
	return _topPosition;
}

// options X position
function getLeftPosition(_obj) {
	var _leftPosition = 0;
	var __offset = _obj.offset();
	_leftPosition = __offset.left;
	return _leftPosition;
}

$(window).load(function(){
    customForms();
	$('.customOptionsHidden').each(function(){
		$(this).removeClass('customOptionsHidden');
		$(this).addClass('customOptions');

		if(parseInt($(this).find('div').eq(3).height())>120) {
			$(this).find('div').eq(3).css('height','120px');
		}

		$(this).find('.scroll-pane').jScrollPane({
			showArrows:true,
			scrollbarWidth:16,
			scrollbarMargin:0
		});
		$(this).removeClass('customOptions');
		$(this).addClass('customOptionsHidden');
	});
});
