/**
 *    Template Functions
 *    URL: @Robocont
 *    Description: Template specific functions and calls
 */

"use strict";


$(document).ready( function(){
	$(document).on('click', '.slider-nav a', function () {
		var t = $(this);
		var	c = t.attr("data-class")
		$(".slider-nav li").removeClass("active")
		t.closest("li").addClass("active")
		$(".slider").removeClass("st0").removeClass("st1").removeClass("st2").removeClass("st3").removeClass("st4");
		$(".slider").addClass(c)
	})	
	
	$(document).on('click', '.open_sub_menu', function () {
		$(this).closest(".main_links_li").siblings().find(".sub_links_main_page").fadeOut()
		$(this).siblings(".sub_links_main_page").fadeIn()
	})
	
	$(document).mouseup(function (e){
		var container = $(".main_links_wrapper");

		if (!container.is(e.target) && container.has(e.target).length === 0){
			$(".sub_links_main_page").fadeOut()
		}
	});
	

	$('.slider').bind('mousewheel', function(e){
		
		if($(".slider").hasClass("scrolled")){
			return false;
		}else {
			$(".slider").addClass("scrolled");
			setTimeout(function(){
				$(".slider").removeClass("scrolled");
			},1700);
			if(e.originalEvent.wheelDelta < 0) {
				var a = $(".slider-nav li.active")
					
				if(a.length>0){
					var aN = a.closest("li").next();
					if(aN.length>0){
						aN.find("a").trigger("click")
					}else {
						return false;
					}
				}else {
					$(".slider-nav li:first-child").find("a").trigger("click")
				}
			}else {
				var a = $(".slider-nav li.active")
					
				if(a.length>0){
					var aN = a.closest("li").prev();
					if(aN.length>0){
						aN.find("a").trigger("click")
					}else {
						$(".slider").removeClass("st1").removeClass("st2").removeClass("st3").removeClass("st4").removeClass("st0");
						$(".slider").addClass("st0");
						$(".slider-nav li.active").removeClass("active")
					}
				}else {
					$(".slider-nav li:first-child").find("a").trigger("click")
				}
			}

			return false;
		}
		
	});
	
});


// $(window).on("resize",function(){
// 	dashboard_items()
// });

// 	sibling	


// Delete cart item
$(document).on('click', '.membership li a', function () {
    var nextdiv = $(this).next('.more-membership');
    nextdiv.addClass("active");
    return false;
});


$(document).on('click', '.more-membership .closex', function () {
    $('.more-membership').removeClass("active");
    return false;

});




// Add to cart

$(document).on('click', 'ul.directions li ul li', function () {
    $(this).addClass('active');
});

$(document).on('mouseleave', 'ul.directions li ul li > ul ', function () {
    $("ul.directions li ul li").removeClass('active');
});


/*/*********************************************
 Popup functions
 *********************/


// Singup function

$(document).on('click', '.signupbtn', function () {
    $('.signup').slideDown();
    $('.signin,.forget').slideUp();
});


// Singin function

$(document).on('click', '.signinbtn', function () {
    $('.signin').slideDown();
    $('.forget,.signup').slideUp();
});


// Forget function

$(document).on('click', '.forgetpassbtn', function () {
    $('.signin,.signup').slideUp();
    $('.forget').slideDown();
});


// Message function

function message(message) {
    $('.ajax-inject .message').fadeIn("slow").delay(500).fadeOut("slow").text(message);
}


// Focus

$(document).on('focus', 'div.input input', function () {
    $(this).parent().addClass('active');
});


$(document).on('focusout', 'div.input input', function () {
    $(this).parent().removeClass('active');
});


$(document).on('click', '.add', function () {
    var type = $(this).attr('href'),
        box = $('.box.' + type).eq(0).clone()
    box.find('input, select').val('').removeAttr('checked')
    box.find('textarea').html('')
    box.find('strong').html('')
    box.addClass('clone')
    $(this).before(box)
    return false;
});


/*/*********************************************
 Ajax popup call function
 *********************/


$('.ajax-link').on('click', function () {
    var ajax_link = '.ajax-link';     							   // Menu Ajax li
    var ajax_inject = '.ajax-inject';							   // Ajax inject div (Pop ups)
    var page = $(this).attr('href');							   // Page link
    $(ajax_inject).addClass('active');
    $("body").addClass('popup');

    $.ajax({
        type: "POST",
        url: page,
        dataType: 'html',
        cache: false,
        success: function (data) {

            $(ajax_inject).html(data);
        }
    });

    return false;

});


/*/*********************************************
 Header & search auto fix position
 *********************/


$(window).on("scroll", function () {
    var page_top = $('.page_top').height() - $('body > .search').height();
    var menuautobg = $(window).height() - 100;
    var scrolltop = $(window).scrollTop();

    if (scrolltop >= page_top) {
        $('body.searchfixed.menu-fix .search .fixing').addClass("active");
    }
    if (scrolltop < page_top) {
        $('body.searchfixed.menu-fix .search .fixing').removeClass('active');
    }

    if (scrolltop >= menuautobg) {
        $('body.menu-auto-bg').addClass("scrolltop");
    }
    if (scrolltop < menuautobg) {
        $('body.menu-auto-bg').removeClass('scrolltop');
    }
});


/*/*********************************************
 Page Slider
 *********************/


$(window).on("load", function () {
    var activeclass = 'active';
    var slid_time = '3000';

    var UlNavLi = '.pageslider .nav li';

    var sliders = {
        SliderClass: '.pageslider',
        activeclass: 'active',
        SlidTime: '3000',
        SlidInterval: '5000',
        current: 1
    };


    for (var x = 1; x <= $(sliders.SliderClass).length; x++) {
        var id = $(sliders.SliderClass).eq(x - 1).attr('id');
        var autoloop = $('#' + id).hasClass('auto-loop');
        var carousel = $('#' + id).hasClass('carousel');
        if (carousel == true) {
            PageSliderCarousel(id, autoloop);
        }
        else {
            PageSlider(id, autoloop);
        }
    }


    //Carousel version

    function PageSliderCarousel(id, autoloop) {
        var current = 1;
        var PageSlider = $('#' + id),
            PgsThumbs = $('.slid', PageSlider),
            PgsNav = $('ul.nav', PageSlider),
            SliderContainer = $('.sliders', PageSlider),
            next = $('.next', PageSlider),
            last = $('.last', PageSlider),
            SliderWidth = PageSlider.width(),
            CountSlid = PgsThumbs.length;
        PgsThumbs.width(SliderWidth);
        SliderContainer.width(SliderWidth * CountSlid);

        $(window).on("resize", function () {
            SliderWidth = PageSlider.width();
            PgsThumbs.width(SliderWidth);
            SliderContainer.width(SliderWidth * CountSlid);
            current = 0;
            Pgs();
        });

        // Adding navigation li

        PageSlider.append("<ul class='nav'></ul>");
        var Pgs_list = '';
        PgsThumbs.eq(1).addClass(sliders.activeclass);
        for (var i = 1; i <= CountSlid; i++) {
            var textli = PgsThumbs.eq(i - 1).html();
            $('ul.nav', PageSlider).append("<li>" + textli + "</li>");
        }

        var PgsList = $('.nav li', PageSlider);
        PgsList.eq(0).addClass(sliders.activeclass);

        // Click sider nav

        PgsList.on("click", function () {
            var currentLi = $(this).index();
            PgsThumbs.removeClass(sliders.activeclass);
            PgsList.removeClass(sliders.activeclass);
            PgsThumbs.eq(currentLi).addClass(sliders.activeclass);
            PgsList.eq(currentLi).addClass(sliders.activeclass);
            SliderContainer.animate({'left': '-' + SliderWidth * currentLi}, sliders.SlidTime, 'swing');
            current = currentLi++;

        });

        // Auto loop

        function PgsInit() {
            if (PgsThumbs.length > 0) {
                var PgsInterval = setInterval(Pgs, sliders.SlidInterval);

            }
        }

        // Slide function

        function Pgs() {
            if (current < PgsThumbs.length) {
                PgsThumbs.removeClass(sliders.activeclass);
                PgsList.removeClass(sliders.activeclass);
                PgsThumbs.eq(current).addClass(sliders.activeclass);
                PgsList.eq(current).addClass(sliders.activeclass);
                SliderContainer.animate({'left': '-' + SliderWidth * current}, sliders.SlidTime, 'swing');
                current++;
            }
            else {
                current = 1;
                PgsThumbs.removeClass(sliders.activeclass);
                PgsList.removeClass(sliders.activeclass);
                PgsThumbs.eq(0).addClass(sliders.activeclass);
                PgsList.eq(0).addClass(sliders.activeclass);
                SliderContainer.animate({'left': '0'}, sliders.SlidTime, 'swing');
            }
        }

        // Next slid

        next.on("click", function () {
            PgsThumbs.removeClass(sliders.activeclass);
            PgsList.removeClass(sliders.activeclass);
            PgsThumbs.eq(current).addClass(sliders.activeclass);
            PgsList.eq(current).addClass(sliders.activeclass);
            Pgs();
        });

        // Last Slid

        last.on("click", function () {
            current = sliders.current - 2;
            if (current < 0) {
                current = 0;
            }
            PgsThumbs.removeClass(sliders.activeclass);
            PgsList.removeClass(sliders.activeclass);
            PgsThumbs.eq(current).addClass(sliders.activeclass);
            PgsList.eq(current).addClass(sliders.activeclass);
            Pgs();
        });

        if (autoloop == true) {
            setTimeout(PgsInit, 0);
            window.clearTimeout(PgsInit);
        }
    }


    //Default version

    function PageSlider() {
        var current = 1;

        var PageSlider = $('#' + id),
            PgsThumbs = $('.slid', PageSlider),
            PgsNav = $('ul.nav', PageSlider),
            SliderContainer = $('.sliders', PageSlider),
            next = $('.next', PageSlider),
            last = $('.last', PageSlider),
            CountSlid = PgsThumbs.length;

        // Adding navigation li*

        PageSlider.append("<ul class='nav'></ul>");
        var Pgs_list = '';
        PgsThumbs.eq(0).addClass(sliders.activeclass);
        for (var i = 1; i <= CountSlid; i++) {
            $('ul.nav', PageSlider).append("<li></li>");
        }
        var PgsList = $('.nav li', PageSlider);
        PgsList.eq(0).addClass(sliders.activeclass);

        // Click sider nav

        PgsList.on("click", function () {
            var currentLi = $(this).index();
            PgsThumbs.removeClass(sliders.activeclass);
            PgsList.removeClass(sliders.activeclass);
            PgsThumbs.eq(currentLi).addClass(sliders.activeclass);
            PgsList.eq(currentLi).addClass(sliders.activeclass);
            current = currentLi++;

        });

        // Auto loop

        function PgsInit() {
            if (PgsThumbs.length > 1) {
                setInterval(Pgs, slid_time);
            }
        }

        // Slide function

        function Pgs() {
            if (current < PgsThumbs.length) {
                PgsThumbs.removeClass(sliders.activeclass);
                PgsList.removeClass(sliders.activeclass);
                PgsThumbs.eq(current).addClass(sliders.activeclass);
                PgsList.eq(current).addClass(sliders.activeclass);
                current++;
            }
            else {
                current = 0;
            }

        }

        // Next slid

        next.on("click", function () {
            current = current++;
            PgsThumbs.removeClass(sliders.activeclass);
            PgsList.removeClass(sliders.activeclass);
            PgsThumbs.eq(current).addClass(sliders.activeclass);
            PgsList.eq(current).addClass(sliders.activeclass);
            Pgs();
        });

        // Last Slid

        last.on("click", function () {
            current = current - 2;
            if (current < 0) {
                current = 0;
            }
            PgsThumbs.removeClass(sliders.activeclass);
            PgsList.removeClass(sliders.activeclass);
            PgsThumbs.eq(current).addClass(sliders.activeclass);
            PgsList.eq(current).addClass(sliders.activeclass);
            Pgs();
        });
        if (autoloop == true) {
            setTimeout(PgsInit, 0);
            window.clearTimeout(PgsInit);
        }

    }
});


$(document).on('submit', 'form', function (e) {
    e.preventDefault();
    var form = $(this),
        data = new FormData(this);
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: data,
        mimeType: "multipart/form-data",
        cache: false,
        processData: false,
        contentType: false,
        beforeSend: function () {
            var ierr = form.find('label.error,.nl-field.error');
            ierr.removeClass('error');
        },
        success: function (response) {
            console.log(response)
            try {
                var json = $.parseJSON(response),
                    error = false;
                $.each(json.errors, function (k, v) {
                    var input = form.find('[name=' + k + ']').closest('label');
                    if (!input.length) input = form.find('[name=' + k + ']').prev('.nl-field').first();
                    console.log(input)
                    input.addClass('error');
                    error = true;
                });
                if (!error) {
                    form.find('input[type=text]').val('');
                    form.find('.column').fadeOut(300, function () {
                        form.find('.form_success').fadeIn(300, function () {
                            setTimeout(function () {
                                form.find('.form_success').fadeOut(300, function () {
                                    form.find('.column').fadeIn(300);
                                });
                            }, 5000)
                        })
                    });
                }
            } catch (e) {
                console.log("Error: JSON parse");
            }
        }
    });
    return false;
});