$(function(){
	initGallery();	
	scrollBar();
	clearInputs();
	initCircleSlider();
	initDatepicker();
	validateSearch();
	
	
	if($(".line .hold .box")){
	
		$(".img-hold a").click(function(){
			return false;
		});
		
		$(".box").hover(function(){
			em_elem = $(this).find("em");	
					
			boringtitle = em_elem.text();			
			funtitle = em_elem.attr("title");
			
			em_elem.text(funtitle);
			em_elem.attr("title", boringtitle);
			
		}, function(){

			em_elem.text(boringtitle);
			em_elem.attr("title", funtitle);
			
		});
	}
	
	if($(".btn-view-all")){
		$(".btn-view-all").click(function(){
			$(".pop-up").fadeIn(300);
			return false;
		});
	}
	
	if($(".btn-view-less")){
		$(".btn-view-less").click(function(){
			$(".pop-up").fadeOut(300);
			return false;
		});
	}
	
	
	$(".user-menu li").hover(function(){
		if($(this).hasClass("active")){return false};	
			if ( $.browser.msie ) { $(this).children("img.p_nav_bg").show(); return false;}	
			$(this).children("img.p_nav_bg").fadeIn(200);
		}, function(){
			if($(this).hasClass("active")){return false};	
			if ( $.browser.msie ) { $(this).children("img.p_nav_bg").hide(); return false;}	
			$(this).children("img.p_nav_bg").fadeOut(200);
		}
	);
	
	$(".sidebar .box2 ul li").click(function(){
		$(this).siblings("li").removeClass("active");
		$(this).addClass("active");
	});
	
	function preloadImages(id) {
	    var c = new Array();
	    $(id+' img').each( function(j) {
	        c[j] = new Image();
	        c[j].src = this.src;
	
	        if ( $.browser.msie ) {
	            this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='"+ this.src +"')"; 
	        }
	    });

	}
	
	preloadImages('.user-menu li');
	
});

function initDatepicker(){
	var holder = $('div.datepicker-box');
	if(holder.length){
		var datepicker = holder.datepicker({
			dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
			firstDay:1,
			onChangeMonthYear: function(year, month, inst) {
				setTimeout(function(){
					setPrevNext(month);
				},10)
			}
		});
		
		var date = datepicker.datepicker('getDate');
		var month = date.getMonth();
		function setPrevNext(month){
			var prev = month-1;
			if (prev < 1) prev = 12;
			var next = month+1;
			if (next > 12) next = 1;
			var prev = setNameMonth(prev);
			var next = setNameMonth(next);
			
			$('a.ui-datepicker-next span').text(next);
			$('a.ui-datepicker-prev span').text(prev);
		}
		function setNameMonth(ind) {
			var name;
			
			switch(ind){
				case 1: name = 'Jan'; break;
				case 2: name = 'Feb'; break;
				case 3: name = 'Mar'; break;
				case 4: name = 'Apr'; break;
				case 5: name = 'May'; break;
				case 6: name = 'Jun'; break;
				case 7: name = 'Jul'; break;
				case 8: name = 'Aug'; break;
				case 9: name = 'Sep'; break;
				case 10: name = 'Oct'; break;
				case 11: name = 'Nov'; break;
				case 12: name = 'Dec'; break;
			}
			return name;
		}
		setPrevNext(month+1);
	}
}

function initCircleSlider(){
	var holder = $('div.slideshow2');
	var activeClass = 'box-active';
	var boxes = $('div.box',holder);
	$('div.circle-slider',holder).tinycircleslider({
		snaptodots: true,
		radius: 160,
		hidedots:false,
		callback: function(element, index){
			boxes.removeClass(activeClass);
			boxes.eq(index).addClass(activeClass);	
		}
	});
	
	$('.more-box .next-button').each(function(){
		$(this).click(function(e){
			e.preventDefault();
			var num = $(this).parent().parent().index();
			$('.dot-'+num).click();
		});
	});
	
	$('.more-box .prev-button').each(function(){
		$(this).click(function(e){
			e.preventDefault();
			var num = $(this).parent().parent().index()-2;
			$('.dot-'+num).click();
		});
	});
	
	$('.more-box .restart-button').each(function(){
		$(this).click(function(e){
			e.preventDefault();
			var num = 1;
			$('.dot-'+num).click();
		});
	});
}

function initGallery(){
	$('div.slideshow').gallery({
		duration: 500,
		listOfSlides: '.slides > li',
		switcher:'.switcher>li',
		effect:true
	});
}

// search validation
function validateSearch() {
	$('.search-form').submit(function() {
		var s = $('#s').val()
		if (s == 'enter a search term') s = '';
		if (!s) {
			$('#s').focus();
			return false;
		}
	});
}

//clear inputs
function clearInputs(){
	$('input:text, input:password, textarea').each(function(){
		var _el = $(this);
		var _val = _el.val();
		_el.bind('focus', function(){
			if(this.value == _val) this.value = '';
			$(this).css('font-style','normal');
		}).bind('blur', function(){
			if(this.value == '') this.value = _val;
			$(this).css('font-style','italic');
		});
	});
}

function scrollBar(){
	var bar = $('.bar');
	var main = $("#main");
	var footer = $("#footer");
	var fixedClass = 'fixed-bar';
	var mainFixClass = "fixed-main";
	var footerFixed = "isFixed";
	var barTop = bar.offset().top - 38;
	var isHome = $("body").hasClass("home");
		
	if ($(this).scrollTop() >= barTop) bar.addClass(fixedClass);
	if ($(this).scrollTop() < barTop) bar.removeClass(fixedClass);
	$(window).scroll(function(){
		if ($(this).scrollTop() >= barTop) {
				bar.addClass(fixedClass);
				if(isHome){
					main.addClass(mainFixClass);
					footer.addClass(footerFixed);
				}
		}
		if ($(this).scrollTop() < barTop  ) {
			bar.removeClass(fixedClass);
			main.removeClass(mainFixClass);
		}
	});
}

;(function($) {
	$.fn.gallery = function(options) { return new Gallery(this.get(0), options); };
	
	function Gallery(context, options) { this.init(context, options); };
	
	Gallery.prototype = {
		options:{},
		init: function (context, options){
			this.options = $.extend({
				duration: 700,
				slideElement: 1,
				autoRotation: false,
				effect: false,
				listOfSlides: 'ul > li',
				switcher: false,
				disableBtn: false,
				nextBtn: 'a.link-next, a.btn-next, a.next',
				prevBtn: 'a.link-prev, a.btn-prev, a.prev',
				circle: true,
				direction: false,
				event: 'click',
				IE: false
			}, options || {});
			var _el = $(context).find(this.options.listOfSlides);
			if (this.options.effect) this.list = _el;
			else this.list = _el.parent();
			if (this.options.switcher) this.switcher = $(context).find(this.options.switcher);
			this.nextBtn = $(context).find(this.options.nextBtn);
			this.prevBtn = $(context).find(this.options.prevBtn);
			this.count = _el.index(_el.filter(':last'));
			
			if (this.options.switcher) this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
			else this.active = _el.index(_el.filter('.active:eq(0)'));
			if (this.active < 0) this.active = 0;
			this.last = this.active;
			
			this.woh = _el.outerWidth(true);
			if (!this.options.direction) this.installDirections(this.list.parent().width());
			else {
				this.woh = _el.outerHeight(true);
				this.installDirections(this.list.parent().height());
			}
			
			if (!this.options.effect) {
				this.rew = this.count - this.wrapHolderW + 1;
				if (!this.options.direction) this.list.css({marginLeft: -(this.woh * this.active)});
				else this.list.css({marginTop: -(this.woh * this.active)});
			}
			else {
				this.rew = this.count;
				this.list.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
				if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			}
			
			if (this.options.disableBtn) {
				if (this.count < this.wrapHolderW) this.nextBtn.addClass(this.options.disableBtn);
				if (this.active == 0) this.prevBtn.addClass(this.options.disableBtn);
			}
			
			this.initEvent(this, this.nextBtn, this.prevBtn, true);
			this.initEvent(this, this.prevBtn, this.nextBtn, false);
			
			if (this.options.autoRotation) this.runTimer(this);
			
			if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
		},
		installDirections: function(temp){
			this.wrapHolderW = Math.floor(temp / this.woh);
			if (((this.wrapHolderW - 1) * this.woh + this.woh / 2) > temp) this.wrapHolderWwrapHolderW--;
		},
		fadeElement: function(){
			if ($.browser.msie && this.options.IE){
				this.list.eq(this.last).css({opacity:0});
				this.list.removeClass('active').eq(this.active).addClass('active').css({opacity:'auto'});
			}
			else{
				this.list.eq(this.last).animate({opacity:0}, {queue:false, duration: this.options.duration});
				this.list.removeClass('active').eq(this.active).addClass('active').animate({
					opacity:1
				}, {queue:false, duration: this.options.duration, complete: function(){
					$(this).css('opacity','auto');
				}});
			}
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			this.last = this.active;
		},
		scrollElement: function(){
			if (!this.options.direction) this.list.animate({marginLeft: -(this.woh * this.active)}, {queue:false, duration: this.options.duration});
			else this.list.animate({marginTop: -(this.woh * this.active)}, {queue:false, duration: this.options.duration});
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
		},
		runTimer: function($this){
			if($this._t) clearTimeout($this._t);
			$this._t = setInterval(function(){
				$this.toPrepare($this, true);
			}, this.options.autoRotation);
		},
		initEventSwitcher: function($this, el){
			el.bind($this.options.event, function(){
				$this.active = $this.switcher.index($(this));
				if($this._t) clearTimeout($this._t);
				if (!$this.options.effect) $this.scrollElement();
				else $this.fadeElement();
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		initEvent: function($this, addEventEl, addDisClass, dir){
			addEventEl.bind($this.options.event, function(){
				if($this._t) clearTimeout($this._t);
				if ($this.options.disableBtn &&($this.count > $this.wrapHolderW)) addDisClass.removeClass($this.options.disableBtn);
				$this.toPrepare($this, dir);
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		toPrepare: function($this, side){
			if (($this.active == $this.rew) && $this.options.circle && side) $this.active = -$this.options.slideElement;
			if (($this.active == 0) && $this.options.circle && !side) $this.active = $this.rew + $this.options.slideElement;
			for (var i = 0; i < $this.options.slideElement; i++){
				if (side) {
					if ($this.active + 1 > $this.rew) {
						if ($this.options.disableBtn && ($this.count > $this.wrapHolderW)) $this.nextBtn.addClass($this.options.disableBtn);
					}
					else $this.active++;
				}
				else{
					if ($this.active - 1 < 0) {
						if ($this.options.disableBtn && ($this.count > $this.wrapHolderW)) $this.prevBtn.addClass($this.options.disableBtn);
					}
					else $this.active--;
				}
			};
			if ($this.active == $this.rew && side) if ($this.options.disableBtn &&($this.count > $this.wrapHolderW)) $this.nextBtn.addClass($this.options.disableBtn);
			if ($this.active == 0 && !side) if ($this.options.disableBtn &&($this.count > $this.wrapHolderW)) $this.prevBtn.addClass($this.options.disableBtn);
			if (!$this.options.effect) $this.scrollElement();
			else $this.fadeElement();
		},
		stop: function(){
			if (this._t) clearTimeout(this._t);
		},
		play: function(){
			if (this._t) clearTimeout(this._t);
			if (this.options.autoRotation) this.runTimer(this);
		}
	}
}(jQuery));


;
(function ($) {
    $.fn.tinycircleslider = function (options) {
        var defaults = {
            interval: false,
            intervaltime: 500,
            snaptodots: false,
            hidedots: true,
            radius: 140,
            lightbox: false,
            callback: null
        };
        var options = $.extend(defaults, options);
        var oCircle = $(this);
        var oCircleX = oCircle.outerWidth();
        var oCircleY = oCircle.outerHeight();
        var oThumb = $('.thumb', oCircle)[0];
        var oThumbX = $(oThumb).outerWidth();
        var oThumbY = $(oThumb).outerHeight();
        var oOverview = $('.overview', oCircle);
        var oDot = {};
        var oTimer, oTimer2, oTimer3;
        var oChildren = oOverview.children();
        var oLinks = $('a', oChildren);
        var iPageX = $(oChildren[0]).outerWidth(true);
        var iChildsLength = oChildren.length,
            iOrginalAngle = 0,
            iCounter = 0,
            iCurrent = 0,
            iFramerate = 1;
        return this.each(function () {
            initialize();
        });

        function initialize() {
            setCircular();
            oOverview[0].style.width = iPageX * oChildren.length + 'px';
            if (options.snaptodots) {
                setDots()
            };
            gotoSlide(0);
            iOrginalAngle = 1;
            setEvents();
            if (options.interval) {
                setTimer(true)
            }
        };

        function setEvents() {
            oThumb.onmousedown = start;
            oThumb.ontouchstart = function (oEvent) {
                oEvent.preventDefault();
                oThumb.onmousedown = null;
                start(oEvent);
                return false;
            }
            if (oLinks.length > 0) {
                oCircle.css({
                    'cursor': 'pointer'
                }).click(function (oEvent) {
                    if ($(oEvent.target).hasClass('overlay')) {
                        if (options.lightbox) {
                            $(oLinks[iCurrent]).trigger('click');
                        } else {
                            location.href = oLinks[iCurrent].href;
                        }
                    }
                    return false;
                });
            }
            if (options.snaptodots) {
                oDot.click(function () {
                    if (iCounter == 0) gotoSlide($(this).text() - 1)
                });
            }
        };

        function start(oEvent) {
            clearTimeout(oTimer3);
            $(document).mousemove(drag);
            document.ontouchmove = function (oEvent) {
                $(document).unbind('mousemove');
                drag(oEvent);
            };
            document.onmouseup = oThumb.onmouseup = end;
            oThumb.ontouchend = document.ontouchend = function (oEvent) {
                document.onmouseup = oThumb.onmouseup = null;
                end(oEvent);
            }
            if (options.snaptodots && options.hidedots) {
                oDot.stop(true, true).fadeIn('slow');
            }
            return false;
        };

        function end(oEvent) {
            $(document).unbind('mousemove');
            document.ontouchmove = document.ontouchend = document.onmouseup = oThumb.onmouseup = oThumb.ontouchend = null;
            clearTimeout(oTimer2);
            if (options.snaptodots) {
                if (options.hidedots) {
                    oDot.stop(true, true).fadeOut('slow');
                }
                calculateMove();
            };
            if (options.interval) {
                setTimer();
            }
            return false;
        };

        function setCircular() {
            oOverview.append($(oChildren[0]).clone());
            oChildren = oOverview.children();
        };

        function setTimer(bFirst) {
            oTimer3 = setTimeout(function () {
                gotoSlide(iChildsLength * Math.random(), true)
            }, (bFirst ? 50 : options.intervaltime));
        };

        function setDots() {
            oDot = $('.dot', oCircle);
            var posX, posY;
            var oDotX = oDot.outerWidth(),
                oDotY = oDot.outerHeight();
            var iLength = (oChildren.length - 1);
            var angle = (360 / iLength) * (Math.PI / 180);
            for (var i = 1; i <= iLength; i++) {
                posY = Math.round(-Math.cos(i * angle - angle) * options.radius + (oCircleY / 2 - oDotY / 2));
                posX = Math.round(Math.sin(i * angle - angle) * options.radius + (oCircleX / 2 - oDotX / 2));
                oDot.clone().addClass('dot-' + i).css({
                    left: posX,
                    top: posY
                }).html('<span>' + i + '</span>').insertAfter(oDot);
            }
            oDot.remove();
            oDot = $('.dot', oCircle);
        };

        function gotoSlide(iNum, bTimed) {
            var angle = Math.ceil(iNum) * (360 / iChildsLength) * (Math.PI / 180);
            iFramerate = Math.max(1, Math.round(Math.abs((angle * 100) - (iOrginalAngle * 100)) / 10));
            var iRatio = ((angle * 100) - (iOrginalAngle * 100)) / iFramerate;
            stepMove(iRatio, bTimed);
        };

        function drag(oEvent) {
            oEvent.preventDefault();
            if (typeof(oEvent.touches) != 'undefined' && oEvent.touches.length == 1) {
                var oEvent = oEvent.touches[0];
            }
            var oPos = {
                x: oEvent.pageX - oCircle.offset().left - (oCircleX / 2),
                y: oEvent.pageY - oCircle.offset().top - (oCircleY / 2)
            }
            iOrginalAngle = Math.atan2(oPos.x, -oPos.y);
            setCSS(iOrginalAngle);
            return false;
        };

        function calculateMove() {
            var iDropped = (iOrginalAngle * 180 / Math.PI) / (360 / iChildsLength) * 100;
            var iDot = Math.round((iOrginalAngle * 180 / Math.PI) / (360 / iChildsLength)) * 100;
            iFramerate = Math.max(1, Math.round(Math.abs(iDot - iDropped) / 10));
            var iStep = ((iOrginalAngle * iDot / iDropped * 100) - (iOrginalAngle * 100)) / iFramerate;
            oTimer2 = setTimeout(function () {
                stepMove(iStep, false);
            }, 100);
        };

        function stepMove(iStep, bInterval) {
            iCounter++
            var angle = iOrginalAngle + ((iCounter * iStep) / 100);
            setCSS(angle, iCounter == iFramerate);
            if (iCounter < iFramerate) {
                oTimer2 = setTimeout(function () {
                    stepMove(iStep, bInterval);
                }, 50);
            } else {
                iCounter = 0;
                iOrginalAngle = angle;
                if (bInterval) {
                    setTimer();
                }
            }
        };

        function setCSS(angle, bFireCallback) {
            var iDegrees = Math.round(angle * 180 / Math.PI);
            iDegrees = iDegrees < 0 ? iDegrees + 360 : iDegrees;
            oOverview[0].style.left = -(iDegrees / 360 * ((iPageX * (iChildsLength)))) + 'px';
            oThumb.style.top = Math.round(-Math.cos(angle) * options.radius + (oCircleY / 2 - oThumbY / 2)) + 'px';
            oThumb.style.left = Math.round(Math.sin(angle) * options.radius + (oCircleX / 2 - oThumbX / 2)) + 'px';
            iCurrent = (Math.min(iChildsLength - 1, Math.round(iDegrees / 360 * iChildsLength)));
            if (typeof options.callback == 'function' && bFireCallback) options.callback.call(this, oChildren[iCurrent], iCurrent);
        };
    };
})(jQuery);
