var markerCategories = new Array();
var markers = new Array();
var mapLoading;
var map;

//init page
jQuery(function(){ 
	initCustomForms();
	initDropsNav();
	slideNews();
	initSlideshow();
	initClearInputs();
	initMegaMenu();
    mapReady();
});

jQuery(window).load(function(){
	initSlideBox();
    //jQuery.ajaxSetup({cache:false});
    getMapListingsAjax();
    jQuery('.inner-holder .checkboxAreaChecked').each(function() {
            showMarkers(jQuery(this).attr("id").replace("category_", ""));
       });
    if (!is_single) {
        jQuery('a.open-btn').trigger('click');
    }
});

function transferMap (initMap) {
    map = initMap;
}

function calcRoute(markerID, location) {
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map); 
                           
    var start = jQuery(".dirStart").val();
    var end = location;
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            //jQuery(".main-content").html(response.routes[0].legs[0].steps[0].instructions);
            directionsDisplay.setDirections(response);
        }
    });
}
                    
function mapReady() {
    var hoverClass = 'hover';
    
    
    
    jQuery(".check-content .col .row").hover(function(){
        jQuery(this).addClass(hoverClass);
        jQuery(this).find(".slide-block").animate({left:"335px"},{queue:false,duration:250}).fadeIn(250);
    },function(){
        jQuery(this).removeClass(hoverClass); 
        jQuery(this).find(".slide-block").animate({left:"375px"},{queue:false,duration:250}).fadeOut(250);      
    });   
    
    jQuery(".checkboxArea").click(function() {
       //All areas
       if (jQuery(this).hasClass("allareas")) {
            if (jQuery(this).hasClass("checkboxAreaChecked")) {
                jQuery(this).removeClass("checkboxAreaChecked");
                jQuery(".allarea").each(function() {
                    jQuery(this).removeClass("checkboxAreaChecked");
                    hideMarkersRegion(jQuery(this).attr("id").replace("area_", ""));;    
                });
           } else {
                jQuery(this).addClass("checkboxAreaChecked");
                jQuery(".allarea").each(function() {
                    jQuery(this).addClass("checkboxAreaChecked");
                    showMarkersRegion(jQuery(this).attr("id").replace("area_", ""));;    
                });
           } 
       //One area 
       } else if (jQuery(this).hasClass("allarea")) {
            if (jQuery(this).hasClass("checkboxAreaChecked")) {
                jQuery(this).removeClass("checkboxAreaChecked");
                jQuery(".allareas").removeClass("checkboxAreaChecked");
                hideMarkersRegion(jQuery(this).attr("id").replace("area_", ""));;    
           } else {
                jQuery(this).addClass("checkboxAreaChecked");
                showMarkersRegion(jQuery(this).attr("id").replace("area_", ""));;    
           }    
       //All of the categories and subcategories
       } else  if (jQuery(this).hasClass("allcategories")) {
            if (jQuery(this).hasClass("checkboxAreaChecked")) {
                jQuery(this).removeClass("checkboxAreaChecked");
                //Get child categories
                jQuery(".allcategory").each(function() {
                    jQuery(this).removeClass("checkboxAreaChecked");
                    //Get children checkboxes
                    jQuery(this).parent().find(".inner-holder .inside-check").each(function() {
                        jQuery(this).removeClass("checkboxAreaChecked");
                        hideMarkers(jQuery(this).attr("id").replace("category_", ""));
                    });    
                });
                
            //If not checked
            } else {
                jQuery(this).addClass("checkboxAreaChecked");
                //Get child categories
                jQuery(".allcategory").each(function() {
                    jQuery(this).addClass("checkboxAreaChecked");
                    //Get children checkboxes
                    jQuery(this).parent().find(".inner-holder .inside-check").each(function() {
                        jQuery(this).addClass("checkboxAreaChecked");
                        showMarkers(jQuery(this).attr("id").replace("category_", ""));    
                    });    
                });
            }    
       //All sub categories
       } else if (jQuery(this).hasClass("allcategory")) {
           //If checked
            if (jQuery(this).hasClass("checkboxAreaChecked")) {
                jQuery(this).removeClass("checkboxAreaChecked");
                jQuery(".allcategories").removeClass("checkboxAreaChecked");
                //Get children checkboxes
                jQuery(this).parent().find(".inner-holder .inside-check").each(function() {
                    jQuery(this).removeClass("checkboxAreaChecked");
                    hideMarkers(jQuery(this).attr("id").replace("category_", ""));
                });
            //If not checked
            } else {
                jQuery(this).addClass("checkboxAreaChecked");
                //Get children checkboxes
                jQuery(this).parent().find(".inner-holder .inside-check").each(function() {
                    jQuery(this).addClass("checkboxAreaChecked");
                    showMarkers(jQuery(this).attr("id").replace("category_", ""));    
                });
            }
       } else {
            //Single non-parent category
           if (jQuery(this).hasClass("checkboxAreaChecked")) {
                jQuery(this).removeClass("checkboxAreaChecked");
                jQuery(".allcategories").removeClass("checkboxAreaChecked");
                hideMarkers(jQuery(this).attr("id").replace("category_", ""));
           } else {
                jQuery(this).addClass("checkboxAreaChecked");
                showMarkers(jQuery(this).attr("id").replace("category_", ""));
           }
       }
       
       getMapListingsAjax();
        
        
    });
    
    
}

function getMapListingsAjax() {
    
    jQuery(".map-listings").block({css: { border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff',height:"600px",width:"100%",  }}); 
            
    var selectedRegions = new Array();
       jQuery('.region-checkboxes .checkboxAreaChecked').each(function() {
            selectedRegions.push(jQuery(this).attr("id").replace("area_", ""));
       });
       
       var selectedCategories = new Array();
       jQuery('.inner-holder .checkboxAreaChecked').each(function() {
            selectedCategories.push(jQuery(this).attr("id").replace("category_", ""));
       });
       
       
       //jQuery.ajaxSetup({cache:false});
       
        jQuery.post("/wp-admin/admin-ajax.php", {action : "process_map_ajax", 'regions[]': selectedRegions, 'categories[]': selectedCategories}, function(data){
            jQuery(".map-listings").html(data);
            jQuery(".map-listings").unblock();
        }, "html");
        
    
    
}


function showMarkers(categoryID) {
        if (markerCategories[categoryID] instanceof Array) {
            jQuery.each(markerCategories[categoryID], function(indexRegion, regionArray) {
                    if (jQuery("#area_" + indexRegion).hasClass("checkboxAreaChecked")) {
                        
                        jQuery.each(this, function(index, marker) {
                            this.setVisible(true);    
                        });    
                    }
                });
        }

}

function hideMarkers(categoryID) {
        if (markerCategories[categoryID] instanceof Array) {
            jQuery.each(markerCategories[categoryID], function(indexRegion, regionArray) {
                    if (jQuery("#area_" + indexRegion).hasClass("checkboxAreaChecked")) {
                        
                        jQuery.each(this, function(index, marker) {
                            this.setVisible(false);    
                        });    
                    }
                });
        }
}

function showMarkersRegion(areaID) {
        jQuery.each(markerCategories, function(index, regionArray) {
            if (markerCategories[index] instanceof Array && markerCategories[index][areaID] instanceof Array && jQuery("#category_" + index).hasClass("checkboxAreaChecked")) {
                jQuery.each(markerCategories[index][areaID], function() {
                    this.setVisible(true);
                });
            }
        });
}

function hideMarkersRegion(areaID) {
        jQuery.each(markerCategories, function(index, regionArray) {
            if (markerCategories[index] instanceof Array && markerCategories[index][areaID] instanceof Array) {
                jQuery.each(markerCategories[index][areaID], function() {
                    this.setVisible(false);
                });
            }
        });
}

//init slide search box
function initSlideBox(){
	var speed = 500;
	var activeClass = 'active';
	var holders = jQuery('.check-area');
	holders.each(function(){
		var holder = jQuery(this);
		var btnOpen = holder.find('a.open-btn');
		var slide = holder.find('.slide-box');
		var form = slide.find('>form');
		slide.show();
		form.css('height',form.height());
		slide.hide();
		btnOpen.click(function(){
			if(!holder.hasClass(activeClass)){
				holder.addClass(activeClass);
				slide.slideDown(speed);
			}
			else{
				holder.removeClass(activeClass);
				slide.slideUp(speed);
			}
			return false;
		});
	});
}

//init drops nav
function initDropsNav(){
	var speed = 300;
	var holders = jQuery('#nav');
	holders.each(function(){
		var holder = jQuery(this);
		var items = holder.children();
		var drops = items.find('.drop');
		drops.hide();
		items.each(function(){
			var item = jQuery(this);
			var drop = item.find('>.drop');
			if(drop.length){
				item.hover(function(){
					drops.hide();
					drop.fadeIn(speed);
				},function(){
					drop.fadeOut(speed);
				});
				var items2 = drop.find('>ul>li');
				items2.each(function(){
					var item2 = jQuery(this);
					var drop2 = item2.find('>.drop');
					if(drop2.length){
						item2.hover(function(){
							drop2.fadeIn(speed);
						},function(){
							drop2.fadeOut(speed);
						});
					}
				});
			}
		});
		
	});
}

//init mega menu
function initMegaMenu(){
	var speed = 500;
	var activeDrop1 = 'active-drop';
	var holders = jQuery('.mega-nav');
	holders.each(function(){
		var holder = jQuery(this);
		var drop1 = holder.find('.mega-drop1');
		if(drop1.length){
			var origHeight = drop1.height();
			drop1.css('marginTop',-drop1.outerHeight());
			holder.hover(function(){
				drop1.stop().animate({marginTop:0},{queue:false,duration:speed,complete:function(){drop1.parent().addClass(activeDrop1);}})
			},function(){
				if(drop1.height() > origHeight){
					drop1.css('height',origHeight);
				}
				drop1.parent().removeClass(activeDrop1);
				drop1.stop().animate({marginTop:-drop1.outerHeight()},{queue:false,duration:speed,complete:function(){}})
			});
			
			var items = drop1.find('>ul>li');
			items.each(function(){
				var item = jQuery(this);
				var drop2 = item.find('.mega-drop2');
				var parent = drop2.parent();
				parent.show();
				drop2.css('marginLeft',-drop2.outerWidth());
				parent.hide();
				
				item.hover(function(){
					parent.show();
					if(drop2.outerHeight() > drop1.height()){
						drop1.css('height',drop2.outerHeight());
					}
					drop2.stop().animate({marginLeft:0},{queue:false,duration:speed});
				},function(){
					drop2.stop().animate({marginLeft:-drop2.outerWidth()},{queue:false,duration:speed,complete:function(){parent.hide();}});
				});
			});
		}
	});
}

// main page slideshow
function initSlideshow(){
	jQuery('.visual').fadeGallery({
		slideElements:'.slide-holder > ul > li',
		btnPrev:'a.prev',
		btnNext:'a.next',
		pauseOnHover:false,
		autoRotation:true,
		switchTime:7000,
		duration:750
	});
}

//init clear inputs
function initClearInputs(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: false,
		addClassFocus: "focus",
		filterClass: "default"
	});
}

//init open close
function initOpenClose(){
	var speed = 400;
	jQuery('.check-area').each(function(){
		var hold = jQuery(this);
		var openBtn = hold.find('a.open-btn');
		var openBox = hold.find('.check-holder');
		var animation;
		var activeClass = 'active';
		
		openBtn.click(function(){
			
			if(!animation){
				animation = true;
				if(!hold.hasClass(activeClass)){
					
					hold.addClass(activeClass);
					openBox.slideDown(speed, function(){
						animation = false;
					});
				}else{
					hold.removeClass(activeClass);
					openBox.slideUp(speed, function(){
						animation = false;
					});
				}
			}
			return false;
		});
	});
}

//init twitter slider
function twitterSlider(){
	var animSpeed = 1000;
	var timeSwitch = 5000;
	jQuery('.twitter-content').each(function(){
		var slider = jQuery(this);
		var sliderHolder = slider.find('.twitter-slide');
		var items = sliderHolder.find('.twitter-post');
		var currentIndex = 0, prevIndex;
		var maxHeight = 0;
		items.each(function(){
			if(jQuery(this).outerHeight(true) > maxHeight) {
				maxHeight = jQuery(this).outerHeight(true);
			}
		});
		sliderHolder.css({height: items.eq(currentIndex).outerHeight(true)});
		
		items.css({bottom:maxHeight});
		items.eq(currentIndex).css({bottom:0});
		
		function switchSlide(){
			items.eq(prevIndex).stop().animate({bottom:-maxHeight}, {
				duration: animSpeed,
				complete: function(){
					jQuery(this).css({bottom:maxHeight})
				}
			});
			items.eq(currentIndex).css({bottom:maxHeight}).stop().animate({bottom:0}, animSpeed);
			changeHeight();
			autoRotation();
		}
		
		function changeHeight() {
			var h =items.eq(currentIndex).outerHeight(true);
			sliderHolder.stop().animate({height:h}, animSpeed);
		}

		function switchSlideNext(){
			direction = 0;
			prevIndex = currentIndex;
			if(currentIndex < items.length-1) currentIndex++;
			else currentIndex = 0; 
			switchSlide();
		}
		
		function autoRotation(){
			setTimeout(switchSlideNext, timeSwitch + animSpeed);
		}
		
		autoRotation();
	})
}

//init slide news
function slideNews(){
	var animSpeed = 1000;
	var timeSwitch = 5000;
	jQuery('.events').each(function(){
		var slider = jQuery(this);
		var list = slider.find('.events-conteiner');
		var prevButton = slider.find('a.next');
		var nextButton = slider.find('a.prev');
		var items = list.find('li');
		var currentIndex = 0, prevIndex, direction, t1, animation;
		var maxWidth = 0;
		
		items.each(function(){
			if(jQuery(this).outerWidth(true) > maxWidth) {
				maxWidth = jQuery(this).outerWidth(true);
			}
		});
		list.css({height: items.eq(currentIndex).outerHeight(true)})
		
		items.css({left:-maxWidth});
		items.eq(currentIndex).css({left:0});
		
		function switchSlide() {
			if (direction == 0){
				items.eq(prevIndex).stop().animate({left:-maxWidth}, {
					duration: animSpeed,
					complete: function(){
						jQuery(this).css({left:maxWidth});
						animation = false;
					}
				});
				items.eq(currentIndex).css({left:maxWidth}).stop().animate({left:0}, animSpeed);
				changeHeight();
			} else {
				items.eq(prevIndex).stop().animate({left:maxWidth}, {
					duration: animSpeed,
					complete: function(){
						jQuery(this).css({left:-maxWidth});
						animation = false;
					}
				});
				items.eq(currentIndex).css({left:-maxWidth}).stop().animate({left:0}, animSpeed);
				changeHeight();
				autoRotation();
			}
		}
		
		function changeHeight() {
			var h =items.eq(currentIndex).outerHeight(true);
			list.stop().animate({height:h}, animSpeed);
		}

		function switchSlideNext() {
			direction = 0;
			prevIndex = currentIndex;
			if(currentIndex > 0) currentIndex--;
			else currentIndex = items.length-1; 
			switchSlide();
		}
		
		function switchSlidePrev() {
			direction = 1;
			prevIndex = currentIndex;
			if(currentIndex < items.length-1) currentIndex++;
			else currentIndex = 0; 
			switchSlide();
		}
		
		prevButton.click(function(){
			if(!animation){
				animation = true;
				if(t1) clearTimeout(t1);
				switchSlidePrev();
			}
			return false;
		});
		nextButton.click(function(){
			if(!animation){
				animation = true;
				if(t1) clearTimeout(t1);
				switchSlideNext();
			}
			return false;
		});
		
		function autoRotation(){
			if(t1) clearTimeout(t1);
			t1 = setTimeout(switchSlidePrev, timeSwitch + animSpeed);
		}
		autoRotation();
	})
}

// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
	var _options = jQuery.extend({
		slideElements:'div.slideset > div',
		pagerLinks:'div.pager a',
		btnNext:'a.next',
		btnPrev:'a.prev',
		btnPlayPause:'a.play-pause',
		btnPlay:'a.play',
		btnPause:'a.pause',
		pausedClass:'paused',
		disabledClass: 'disabled',
		playClass:'playing',
		activeClass:'active',
		loadingClass:'ajax-loading',
		loadedClass:'slide-loaded',
		dynamicImageLoad:false,
		dynamicImageLoadAttr:'alt',
		currentNum:false,
		allNum:false,
		startSlide:null,
		noCircle:false,
		pauseOnHover:true,
		autoRotation:false,
		autoHeight:false,
		onBeforeFade:false,
		onAfterFade:false,
		onChange:false,
		disableWhileAnimating:false,
		switchTime:3000,
		duration:650,
		event:'click'
	},_options);

	return this.each(function(){
		// gallery options
		if(this.slideshowInit) return; else this.slideshowInit;
		var _this = jQuery(this);
		var _slides = jQuery(_options.slideElements, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
		var _btnPause = jQuery(_options.btnPause, _this);
		var _btnPlay = jQuery(_options.btnPlay, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _dynamicImageLoad = _options.dynamicImageLoad;
		var _dynamicImageLoadAttr = _options.dynamicImageLoadAttr;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _loadingClass = _options.loadingClass;
		var _loadedClass = _options.loadedClass;
		var _disabledClass = _options.disabledClass;
		var _pausedClass = _options.pausedClass;
		var _playClass = _options.playClass;
		var _autoHeight = _options.autoHeight;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
		var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
		var _startSlide = _options.startSlide;
		var _noCycle = _options.noCircle;
		var _onChange = _options.onChange;
		var _onBeforeFade = _options.onBeforeFade;
		var _onAfterFade = _options.onAfterFade;
		var _disableWhileAnimating = _options.disableWhileAnimating;

		// gallery init
		var _anim = false;
		var _hover = false;
		var _prevIndex = 0;
		var _currentIndex = 0;
		var _slideCount = _slides.length;
		var _timer;
		if(_slideCount < 2) return;

		_prevIndex = _slides.index(_slides.filter('.'+_activeClass));
		if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
		else _currentIndex = _prevIndex;
		if(_startSlide != null) {
			if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
			else _prevIndex = _currentIndex = parseInt(_startSlide);
		}
		_slides.hide().eq(_currentIndex).show();
		if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
		else _this.removeClass(_playClass).addClass(_pausedClass);

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				nextSlide();
				return false;
			});
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentIndex != _ind) {
						if(_disableWhileAnimating && _anim) return;
						_prevIndex = _currentIndex;
						_currentIndex = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// play pause section
		if(_btnPlayPause.length) {
			_btnPlayPause.bind(_controlEvent,function(){
				if(_this.hasClass(_pausedClass)) {
					_this.removeClass(_pausedClass).addClass(_playClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_autoRotation = false;
					if(_timer) clearTimeout(_timer);
					_this.removeClass(_playClass).addClass(_pausedClass);
				}
				return false;
			});
		}
		if(_btnPlay.length) {
			_btnPlay.bind(_controlEvent,function(){
				_this.removeClass(_pausedClass).addClass(_playClass);
				_autoRotation = true;
				autoSlide();
				return false;
			});
		}
		if(_btnPause.length) {
			_btnPause.bind(_controlEvent,function(){
				_autoRotation = false;
				if(_timer) clearTimeout(_timer);
				_this.removeClass(_playClass).addClass(_pausedClass);
				return false;
			});
		}

		// dynamic image loading (swap from ATTRIBUTE)
		function loadSlide(slide) {
			if(!slide.hasClass(_loadingClass) && !slide.hasClass(_loadedClass)) {
				var images = slide.find(_dynamicImageLoad) // pass selector here
				var imagesCount = images.length;
				if(imagesCount) {
					slide.addClass(_loadingClass);
					images.each(function(){
						var img = this;
						img.onload = function(){
							img.loaded = true;
							img.onload = null;
							setTimeout(reCalc,_duration);
						}
						img.setAttribute('src', img.getAttribute(_dynamicImageLoadAttr));
						img.setAttribute(_dynamicImageLoadAttr,'');
					}).css({opacity:0});

					function reCalc() {
						var cnt = 0;
						images.each(function(){
							if(this.loaded) cnt++;
						});
						if(cnt == imagesCount) {
							slide.removeClass(_loadingClass);
							images.animate({opacity:1},{duration:_duration,complete:function(){
								if(jQuery.browser.msie && jQuery.browser.version < 9) jQuery(this).css({opacity:'auto'})
							}});
							slide.addClass(_loadedClass)
						}
					}
				}
			}
		}

		// gallery animation
		function prevSlide() {
			if(_disableWhileAnimating && _anim) return;
			_prevIndex = _currentIndex;
			if(_currentIndex > 0) _currentIndex--;
			else {
				if(_noCycle) return;
				else _currentIndex = _slideCount-1;
			}
			switchSlide();
		}
		function nextSlide() {
			if(_disableWhileAnimating && _anim) return;
			_prevIndex = _currentIndex;
			if(_currentIndex < _slideCount-1) _currentIndex++;
			else {
				if(_noCycle) return;
				else _currentIndex = 0;
			}
			switchSlide();
		}
		function refreshStatus() {
			if(_dynamicImageLoad) loadSlide(_slides.eq(_currentIndex));
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
			if(_currentNum) _currentNum.text(_currentIndex+1);
			if(_allNum) _allNum.text(_slideCount);
			_slides.eq(_prevIndex).removeClass(_activeClass);
			_slides.eq(_currentIndex).addClass(_activeClass);
			if(_noCycle) {
				if(_btnPrev.length) {
					if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
					else _btnPrev.removeClass(_disabledClass);
				}
				if(_btnNext.length) {
					if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
					else _btnNext.removeClass(_disabledClass);
				}
			}
			if(typeof _onChange === 'function') {
				_onChange(_this, _slides, _prevIndex, _currentIndex);
			}
		}
		function switchSlide() {
			_anim = true;
			if(typeof _onBeforeFade === 'function') _onBeforeFade(_this, _slides, _prevIndex, _currentIndex);
			/* if(jQuery.browser.msie && jQuery.browser.version < 9){
				_slides.eq(_prevIndex).hide();
				_slides.eq(_currentIndex).show();
			}else{ */
				_slides.eq(_prevIndex).stop().animate({opacity:0}, {queue:false, duration:_duration, complete: function(){
					jQuery(this).css({opacity:1, display: 'none'})
					_anim = false;
				}});
				_slides.eq(_currentIndex).css({opacity:0, display: 'block'}).stop().animate({opacity:1}, {queue:false, duration:_duration, complete: function(){
					if(typeof _onAfterFade === 'function') _onAfterFade(_this, _slides, _prevIndex, _currentIndex);
				}});
			/* } */
			if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		refreshStatus();
		autoSlide();
	});
}

//add class module
function addClass (_options){
	var _tagName = _options.tagName;
	var _tagClass = _options.tagClass;
	var _classAdd = _options.classAdd;
	var _addToParent = false || _options.addToParent;
	var _el = document.getElementsByTagName(_tagName);
	if (_el) {
		for (var i=0; i < _el.length; i++) {
			if (_el[i].className.indexOf(_tagClass) != -1) {
				_el[i].onclick = function() {
					if (_addToParent) {
						if (this.parentNode.className.indexOf(_classAdd) == -1) {
							this.parentNode.className += ' '+_classAdd;
						} else {
							this.parentNode.className = this.parentNode.className.replace(_classAdd,'');
						}
					} else {
						if (this.className.indexOf(_classAdd) == -1) {
							this.className += ' '+_classAdd;
						} else {
							this.className = this.className.replace(_classAdd,'');
						}
					}
					return false;
				}
			}
		}
	}
}

//clear form fields module
function clearFormFields(o){
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filterClass) o.filterClass = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass) == -1) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass) == -1) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}

// custom forms script
var _selectHeight = 23;
var all_selects = false;
var active_select = null;
var selectText = "please select";

function initCustomForms(){
	getElements();
	separateElements();
	//replaceRadios();
	//replaceCheckboxes();
	//replaceSelects();

	// hide drop when scrolling or resizing window
	if (window.addEventListener) {
		window.addEventListener("scroll", hideActiveSelectDrop, false);
		window.addEventListener("resize", hideActiveSelectDrop, false);
	}
	else if (window.attachEvent) {
		window.attachEvent("onscroll", hideActiveSelectDrop);
		window.attachEvent("onresize", hideActiveSelectDrop);
	}
}

function refreshCustomForms() {
	// remove prevously created elements
	if(window.inputs) {
		for(var i = 0; i < checkboxes.length; i++) {
			if(checkboxes[i].checked) {checkboxes[i]._ca.className = "checkboxAreaChecked";}
			else {checkboxes[i]._ca.className = "checkboxArea";}
		}
		for(var i = 0; i < radios.length; i++) {
			if(radios[i].checked) {radios[i]._ra.className = "radioAreaChecked";}
			else {radios[i]._ra.className = "radioArea";}
		}
		for(var i = 0; i < selects.length; i++) {
			var newText = document.createElement('div');
			if (selects[i].options[selects[i].selectedIndex].title.indexOf('image') != -1) {
				newText.innerHTML = '<img src="'+selects[i].options[selects[i].selectedIndex].title+'" alt="" />';
				newText.innerHTML += '<span>'+selects[i].options[selects[i].selectedIndex].text+'</span>';
			} else {
				newText.innerHTML = selects[i].options[selects[i].selectedIndex].text;
			}
			document.getElementById("mySelectText"+i).innerHTML = newText.innerHTML;
		}
	}
}

// getting all the required elements
function getElements() {
	// remove prevously created elements
	if(window.inputs) {
		for(var i = 0; i < inputs.length; i++) {
			inputs[i].className = inputs[i].className.replace('outtaHere','');
			if(inputs[i]._ca) inputs[i]._ca.parentNode.removeChild(inputs[i]._ca);
			else if(inputs[i]._ra) inputs[i]._ra.parentNode.removeChild(inputs[i]._ra);
		}
		for(i = 0; i < selects.length; i++) {
			selects[i].replaced = null;
			selects[i].className = selects[i].className.replace('outtaHere','');
			selects[i]._optionsDiv._parent.parentNode.removeChild(selects[i]._optionsDiv._parent);
			selects[i]._optionsDiv.parentNode.removeChild(selects[i]._optionsDiv);
		}
	}

	// reset state
	inputs = new Array();
	selects = new Array();
	labels = new Array();
	radios = new Array();
	radioLabels = new Array();
	checkboxes = new Array();
	checkboxLabels = new Array();
	for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
		if(document.forms[nf].className.indexOf("default") < 0) {
			for(var nfi = 0; nfi < document.forms[nf].getElementsByTagName("input").length; nfi++) {inputs.push(document.forms[nf].getElementsByTagName("input")[nfi]);}
			for(var nfl = 0; nfl < document.forms[nf].getElementsByTagName("label").length; nfl++) {labels.push(document.forms[nf].getElementsByTagName("label")[nfl]);}
			for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName("select").length; nfs++) {selects.push(document.forms[nf].getElementsByTagName("select")[nfs]);}
		}
	}
}

// separating all the elements in their respective arrays
function separateElements() {
	var r = 0; var c = 0; var t = 0; var rl = 0; var cl = 0; var tl = 0; var b = 0;
	for (var q = 0; q < inputs.length; q++) {
		if(inputs[q].type == "radio") {
			radios[r] = inputs[q]; ++r;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && labels[w].htmlFor == inputs[q].id)
				{
					radioLabels[rl] = labels[w];
					++rl;
				}
			}
		}
		if(inputs[q].type == "checkbox") {
			checkboxes[c] = inputs[q]; ++c;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && (labels[w].htmlFor == inputs[q].id))
				{
					checkboxLabels[cl] = labels[w];
					++cl;
				}
			}
		}
	}
}

//replacing radio buttons
function replaceRadios() {
	for (var q = 0; q < radios.length; q++) {
		radios[q].className += " outtaHere";
		var radioArea = document.createElement("div");
		if(radios[q].checked) {
			radioArea.className = "radioAreaChecked";
		}
		else
		{
			radioArea.className = "radioArea";
		}
		radioArea.id = "myRadio" + q;
		radios[q].parentNode.insertBefore(radioArea, radios[q]);
		radios[q]._ra = radioArea;

		radioArea.onclick = new Function('rechangeRadios('+q+')');
		if (radioLabels[q]) {
			if(radios[q].checked) {
				radioLabels[q].className += "radioAreaCheckedLabel";
			}
			radioLabels[q].onclick = new Function('rechangeRadios('+q+')');
		}
	}
	return true;
}

//checking radios
function checkRadios(who) {
	var what = radios[who]._ra;
	for(var q = 0; q < radios.length; q++) {
		if((radios[q]._ra.className == "radioAreaChecked") && (radios[q]._ra.nextSibling.name == radios[who].name))
		{
			radios[q]._ra.className = "radioArea";
		}
	}
	what.className = "radioAreaChecked";
}

//changing radios
function changeRadios(who) {
	if(radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name) {
				radios[q].checked = false;
			} 
			radios[who].checked = true; 
			checkRadios(who);
		}
	}
}

//rechanging radios
function rechangeRadios(who) {
	if(!radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name) {
				radios[q].checked = false; 
			}
			if(radioLabels[q]) {
				radioLabels[q].className = radioLabels[q].className.replace("radioAreaCheckedLabel","");
			}
		}
		radios[who].checked = true; 
		if(radioLabels[who] && radioLabels[who].className.indexOf("radioAreaCheckedLabel") < 0) {
			radioLabels[who].className += " radioAreaCheckedLabel";
		}
		checkRadios(who);
		
		if(window.jQuery && window.jQuery.fn) {
			jQuery(radios[who]).trigger('change');
		}
	}
}

//replacing checkboxes
function replaceCheckboxes() {
	for (var q = 0; q < checkboxes.length; q++) {
		checkboxes[q].className += " outtaHere";
		var checkboxArea = document.createElement("div");
		if(checkboxes[q].checked) {
			checkboxArea.className = "checkboxAreaChecked";
			if(checkboxLabels[q]) {
				checkboxLabels[q].className += " checkboxAreaCheckedLabel"
			}
		}
		else {
			checkboxArea.className = "checkboxArea";
		}
		checkboxArea.id = "myCheckbox" + q;
		checkboxes[q].parentNode.insertBefore(checkboxArea, checkboxes[q]);
		checkboxes[q]._ca = checkboxArea;
		checkboxArea.onclick = new Function('rechangeCheckboxes('+q+')');
		if (checkboxLabels[q]) {
			checkboxLabels[q].onclick = new Function('changeCheckboxes('+q+')');
		}
		checkboxes[q].onkeydown = checkEvent;
	}
	return true;
}

//checking checkboxes
function checkCheckboxes(who, action) {
	var what = checkboxes[who]._ca;
	if(action == true) {
		what.className = "checkboxAreaChecked";
		what.checked = true;
	}
	if(action == false) {
		what.className = "checkboxArea";
		what.checked = false;
	}
	if(checkboxLabels[who]) {
		if(checkboxes[who].checked) {
			if(checkboxLabels[who].className.indexOf("checkboxAreaCheckedLabel") < 0) {
				checkboxLabels[who].className += " checkboxAreaCheckedLabel";
			}
		} else {
			checkboxLabels[who].className = checkboxLabels[who].className.replace("checkboxAreaCheckedLabel", "");
		}
	}
	
}

//changing checkboxes
function changeCheckboxes(who) {
	setTimeout(function(){
		if(checkboxes[who].checked) {
			checkCheckboxes(who, true);
		} else {
			checkCheckboxes(who, false);
		}
	},10);
}

// rechanging checkboxes
function rechangeCheckboxes(who) {
	var tester = false;
	if(checkboxes[who].checked == true) {
		tester = false;
	}
	else {
		tester = true;
	}
	checkboxes[who].checked = tester;
	checkCheckboxes(who, tester);
	if(window.jQuery && window.jQuery.fn) {
		jQuery(checkboxes[who]).trigger('change');
	}
}

// check event
function checkEvent(e) {
	if (!e) var e = window.event;
	if(e.keyCode == 32) {for (var q = 0; q < checkboxes.length; q++) {if(this == checkboxes[q]) {changeCheckboxes(q);}}} //check if space is pressed
}

// replace selects
function replaceSelects() {
	for(var q = 0; q < selects.length; q++) {
		if (!selects[q].replaced && selects[q].offsetWidth) {
			selects[q]._number = q;
			//create and build div structure
			var selectArea = document.createElement("div");
			var left = document.createElement("span");
			left.className = "left";
			selectArea.appendChild(left);

			var disabled = document.createElement("span");
			disabled.className = "disabled";
			selectArea.appendChild(disabled);

			selects[q]._disabled = disabled;
			var center = document.createElement("span");
			var button = document.createElement("a");
			var text = document.createTextNode(selectText);
			center.id = "mySelectText"+q;

			var stWidth = selects[q].offsetWidth;
			selectArea.style.width = stWidth + "px";
			if (selects[q].parentNode.className.indexOf("type2") != -1){
				button.href = "javascript:showOptions("+q+",true)";
			} else {
				button.href = "javascript:showOptions("+q+",false)";
			}
			button.className = "selectButton";
			selectArea.className = "selectArea";
			selectArea.className += " " + selects[q].className;
			selectArea.id = "sarea"+q;
			center.className = "center";
			center.appendChild(text);
			selectArea.appendChild(center);
			selectArea.appendChild(button);

			//insert select div
			selects[q].parentNode.insertBefore(selectArea, selects[q]);
			//build & place options div

			var optionsDiv = document.createElement("div");
			var optionsList = document.createElement("ul");
			var optionsListHolder = document.createElement("div");
			
			optionsListHolder.className = "select-center";
			optionsListHolder.innerHTML =  "<div class='select-center-right'></div>";
			optionsDiv.innerHTML += "<div class='select-top'><div class='select-top-left'></div><div class='select-top-right'></div></div>";
			
			optionsListHolder.appendChild(optionsList);
			optionsDiv.appendChild(optionsListHolder);
			
			selects[q]._optionsDiv = optionsDiv;
			selects[q]._options = optionsList;

			optionsDiv.style.width = stWidth + "px";
			optionsDiv._parent = selectArea;

			optionsDiv.className = "optionsDivInvisible";
			optionsDiv.id = "optionsDiv"+q;

			if(selects[q].className.length) {
				optionsDiv.className += ' drop-'+selects[q].className;
			}

			populateSelectOptions(selects[q]);
			optionsDiv.innerHTML += "<div class='select-bottom'><div class='select-bottom-left'></div><div class='select-bottom-right'></div></div>";
			document.body.appendChild(optionsDiv);
			selects[q].replaced = true;
			
			//hide the select field
			if(selects[q].className.indexOf('default') != -1) {
				selectArea.style.display = 'none';
			} else {
				selects[q].className += " outtaHere";
			}
		}
		all_selects = true;
	}
}

//collecting select options
function populateSelectOptions(me) {
	me._options.innerHTML = "";
	for(var w = 0; w < me.options.length; w++) {
		var optionHolder = document.createElement('li');
		var optionLink = document.createElement('a');
		var optionTxt;
		if (me.options[w].title.indexOf('image') != -1) {
			optionTxt = document.createElement('img');
			optionSpan = document.createElement('span');
			optionTxt.src = me.options[w].title;
			optionSpan = document.createTextNode(me.options[w].text);
		} else {
			optionTxt = document.createTextNode(me.options[w].text);
		}
		
		// hidden default option
		if(me.options[w].className.indexOf('default') != -1) {
			optionHolder.style.display = 'none'
		}
		
		optionLink.href = "javascript:showOptions("+me._number+"); selectMe('"+me.id+"',"+w+","+me._number+");";
		if (me.options[w].title.indexOf('image') != -1) {
			optionLink.appendChild(optionTxt);
			optionLink.appendChild(optionSpan);
		} else {
			optionLink.appendChild(optionTxt);
		}
		optionHolder.appendChild(optionLink);
		me._options.appendChild(optionHolder);
		//check for pre-selected items
		if(me.options[w].selected) {
			selectMe(me.id,w,me._number,true);
		}
	}
	if (me.disabled) {
		me._disabled.style.display = "block";
	} else {
		me._disabled.style.display = "none";
	}
}

//selecting me
function selectMe(selectFieldId,linkNo,selectNo,quiet) {
	selectField = selects[selectNo];
	for(var k = 0; k < selectField.options.length; k++) {
		if(k==linkNo) {
			selectField.options[k].selected = true;
		}
		else {
			selectField.options[k].selected = false;
		}
	}
	
	//show selected option
	textVar = document.getElementById("mySelectText"+selectNo);
	var newText;
	var optionSpan;
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		newText = document.createElement('img');
		newText.src = selectField.options[linkNo].title;
		optionSpan = document.createElement('span');
		optionSpan = document.createTextNode(selectField.options[linkNo].text);
	} else {
		newText = document.createTextNode(selectField.options[linkNo].text);
	}
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);
		textVar.appendChild(optionSpan);
	} else {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);
	}
	if (!quiet && all_selects) {
		if(typeof selectField.onchange === 'function') {
			selectField.onchange();
		}
		if(window.jQuery && window.jQuery.fn) {
			jQuery(selectField).trigger('change');
		}
	}
}

//showing options
function showOptions(g) {
	_elem = document.getElementById("optionsDiv"+g);
	var divArea = document.getElementById("sarea"+g);
	if (active_select && active_select != _elem) {
		active_select.className = active_select.className.replace('optionsDivVisible',' optionsDivInvisible');
		active_select.style.height = "auto";
	}
	if(_elem.className.indexOf("optionsDivInvisible") != -1) {
		_elem.style.left = "-9999px";
		_elem.style.top = findPosY(divArea) + _selectHeight + 'px';
		_elem.className = _elem.className.replace('optionsDivInvisible','');
		_elem.className += " optionsDivVisible";
		/*if (_elem.offsetHeight > 200)
		{
			_elem.style.height = "200px";
		}*/
		_elem.style.left = findPosX(divArea) + 'px';
		
		active_select = _elem;
		if(_elem._parent.className.indexOf('selectAreaActive') < 0) {
			_elem._parent.className += ' selectAreaActive';
		}
		
		if(document.documentElement) {
			document.documentElement.onclick = hideSelectOptions;
		} else {
			window.onclick = hideSelectOptions;
		}
	}
	else if(_elem.className.indexOf("optionsDivVisible") != -1) {
		hideActiveSelectDrop();
	}
	
	// for mouseout
	/*_elem.timer = false;
	_elem.onmouseover = function() {
		if (this.timer) clearTimeout(this.timer);
	}
	_elem.onmouseout = function() {
		var _this = this;
		this.timer = setTimeout(function(){
			_this.style.height = "auto";
			_this.className = _this.className.replace('optionsDivVisible','');
			if (_elem.className.indexOf('optionsDivInvisible') == -1)
				_this.className += " optionsDivInvisible";
		},200);
	}*/
}

function hideActiveSelectDrop() {
	if(active_select) {
		active_select.style.height = "auto";
		active_select.className = active_select.className.replace('optionsDivVisible', '');
		active_select.className = active_select.className.replace('optionsDivInvisible', '');
		active_select._parent.className = active_select._parent.className.replace('selectAreaActive','')
		active_select.className += " optionsDivInvisible";
		active_select = false;
	}
}

function hideSelectOptions(e) {
	if(active_select) {
		if(!e) e = window.event;
		var _target = (e.target || e.srcElement);
		if(!isElementBefore(_target,'selectArea') && !isElementBefore(_target,'optionsDiv')) {
			hideActiveSelectDrop();
			if(document.documentElement) {
				document.documentElement.onclick = function(){};
			}
			else {
				window.onclick = null;
			}
		}
	}
}

function isElementBefore(_el,_class) {
	var _parent = _el;
	do {
		_parent = _parent.parentNode;
	}
	while(_parent && _parent.className != null && _parent.className.indexOf(_class) == -1)
	return _parent.className && _parent.className.indexOf(_class) != -1;
}

function findPosY(obj) {
	if (obj.getBoundingClientRect) {
		var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
		var clientTop = document.documentElement.clientTop || document.body.clientTop || 0;
		return Math.round(obj.getBoundingClientRect().top + scrollTop - clientTop);
	} else {
		var posTop = 0;
		while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
		return posTop;
	}
}

function findPosX(obj) {
	if (obj.getBoundingClientRect) {
		var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
		var clientLeft = document.documentElement.clientLeft || document.body.clientLeft || 0;
		return Math.round(obj.getBoundingClientRect().left + scrollLeft - clientLeft);
	} else {
		var posLeft = 0;
		while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
		return posLeft;
	}
}
