var $ = jQuery;

var Wishbone = (function($) {
	"use strict";
	var winsize = $(window).width();
	return {
		init: function() {
			this.wishbone_centerlogo();
			this.wishbone_megamenutab();
			this.wishbone_stickymenu();
			this.wishbone_m_carousel();
			this.wishbone_carousel();
			this.wishbone_wideslider();
			this.wishbone_gridhero();
			this.wishbone_twocolslider();
			this.wishbone_onecolslider();
			this.wishbone_postshare();
			this.wishbone_postlove();
			this.wishbone_stickysidebar();
			this.wishbone_masonry_loop();
			this.wishbone_simplegrid_loop();
			this.wishbone_ajaxloadmore();
			this.wishbone_article();
			this.wishbone_footer();
			this.wishbone_backtotop();
			this.wishbone_m_header();
		}, // end init

		wishbone_centerlogo: function() {
			if( $('.zlleftmenu').length ){
				var menuitems = $(".zlleftmenu > li").length,
					halfmenu = menuitems / 2,
					finalhalf = Math.ceil(halfmenu);
				$('.wishbone_mainmenu > li').slice( finalhalf,menuitems ).appendTo('.zlrightmenu');
			}
			$(window).bind("load", function(){
				$('.wishbone_mainmenu.zlleftmenu, .wishbone_mainmenu.zlrightmenu').show();
			});
		},

		wishbone_megamenutab: function(){
			$( document ).ready( function(){
				if( $('.mega-cat-sub-categories').length ){
					$('.mega-cat-wrapper').each(function(){
						var thismegawrapper = $(this);
						thismegawrapper.find('.mega-cat-sub-categories').each(function(){
							var thissubcat = $(this);
							thissubcat.find('li:first-child').addClass('active');

							thissubcat.find('>li').hover(function(e){
								e.preventDefault();
								var tabid = $(this).find('a').attr('href');
								$(this).addClass('active');
								$(this).siblings().removeClass('active');
								thismegawrapper.find('.mega-cat-content').find(tabid).stop().show(0, function(){
									$(this).addClass('tab-active');
								}).siblings().hide(0).removeClass('tab-active');
								console.log(tabid);
							});
						});
					});
				}

				if( $('.mega-menu-block').length ){
					$('.mega-menu-block').each(function(){
						var thistab = $(this);
						thistab.find('.mega-cat-content-tab:first-child').show().addClass('tab-active');
					});
				}

			});
		},

		wishbone_stickymenu: function(){
			if( $('body').hasClass('stickymenuenabled') ) {
			 	$("#wishbone_mainheader").find('.stickytarget').sticky({topSpacing:0});
			}
		},

		wishbone_m_carousel: function() {
			if( $('.wishbone_m_carousel').length ){
				$('.wishbone_m_carousel').owlCarousel({
					nav: false,
					center: true,
				    items:1,
				    loop:true,
					autoHeight: true,
					margin: 0,
				});
			}
		},

		wishbone_carousel: function() {
			if( $('.wishbone_heroslider').length ){
				var direction = $('html').attr('dir');
				if( 'rtl' == direction ){
					var rtlstatus = true;
				} else {
					var rtlstatus = false;
				}

				$('.wishbone_heroslider').owlCarousel({
					nav: true,
					mouseDrag: false,
					center: true,
				    items:2,
				    loop:true,
				    margin:165,
				    rtl: rtlstatus
				});

				$(window).bind("load", function(){
					$('.wishbone_herosliderwrapper').addClass('finallyshowup');
				});
			}
		},

		wishbone_wideslider: function() {
			if( $('.wishbone_wideslider').length ){
				var thumb = $('.wishbone_wideslider');
				thumb.owlCarousel({
					nav: false,
					mouseDrag: false,
					touchDrag: false,
				    items: 1,
				    loop: false,
				    animateOut: 'fadeOut',
  					animateIn: 'fadeIn'
				});
			}
			if( $('.wishbone_ws_detailsslider').length ){
				var detail = $('.wishbone_ws_detailsslider');
				detail.owlCarousel({
					nav: false,
					mouseDrag: false,
					touchDrag: false,
					autoHeight: true,
				    items: 1,
				    loop: false,
				    animateOut: 'fadeOut',
  					animateIn: 'fadeIn'
				});
			}

			$('.wishbone_ws_thumbswrapper > .wishbone_ws_slide_trigger:first-child').addClass('active');
			$('.wishbone_ws_thumbswrapper > .wishbone_ws_slide_trigger').click(function(){
				var thumbid = $(this).attr('data-targetid');
				$(this).addClass('active').siblings().removeClass('active');
				thumb.trigger('to.owl.carousel', [thumbid, 500]);
				detail.trigger('to.owl.carousel', [thumbid, 500]);
			});

			$(window).bind("load", function() {
			   $('.wishbone_widesliderwrapper').addClass('finallyshowup');
			});

		},

		wishbone_gridhero: function() {
			if( $('.wishbone_gridherowrapper').length ){
				$(window).bind("load", function(){
					$('.wishbone_gridherowrapper').addClass('finallyshowup');
				});
			}
		},

		wishbone_twocolslider: function() {
			if( $('.wishbone_twocol_slider').length ){
				var direction = $('html').attr('dir');
				if( 'rtl' == direction ){
					var rtlstatus = true;
				} else {
					var rtlstatus = false;
				}
				$('.wishbone_twocol_slider').owlCarousel({
					nav: true,
					mouseDrag: false,
				    items: 2,
				    slideBy: 1,
				    dotsEach: 2,
				    margin:25,
				    navText: ['', ''],
				    rewind: true,
				    rtl: rtlstatus
				});

				$(window).bind("load", function(){
					$('.wishbone_twocol_sliderwrapper').addClass('finallyshowup');
				});
			}
		},

		wishbone_onecolslider: function() {
			if( $('.wishbone_onecol_slider').length ){
				$('.wishbone_onecol_slider').each(function(){
					var direction = $('html').attr('dir');
					if( 'rtl' == direction ){
						var rtlstatus = true;
					} else {
						var rtlstatus = false;
					}
					$(this).owlCarousel({
						nav: true,
						mouseDrag: false,
					    items: 1,
					    slideBy: 1,
					    dotsEach: 2,
					    margin:25,
					    navText: ['', ''],
					    rewind: true,
					    rtl: rtlstatus
					});

					$(window).bind("load", function(){
						$('.wishbone_onecol_slider').addClass('finallyshowup');
					});
				});
				
			}
		},

		wishbone_postshare: function() {
			if( $('.wishbone_postloop:not(.alreadyloaded)').length ){
				$('.wishbone_postloop:not(.alreadyloaded)').each(function(){
					var sharetrigger = $(this).find('.wishbone_sharetrigger'),
						shareiconwrap = $(this).find('.wishbone_postsharer'),
						closer = $(this).find('.wishbone_share_close');

					/* Share triggered */
					sharetrigger.click(function(e){
						e.preventDefault();
						shareiconwrap.velocity({
							translateY: [0, "100%"],
						}, {
							duration: 200,
							easing: "linear",
							display: "block"
						});
						shareiconwrap.find('a').each(function(t){
							$(this).velocity({
							    translateY: [0, "25px"],
							    opacity: [1,0]
							}, {
							    duration: 850,
							    delay: t * 55,
							    easing: "spring"
							});
						});
					});

					closer.click(function(){
						shareiconwrap.velocity("reverse");
						shareiconwrap.find('a').each(function(t){
							$(this).velocity("reverse");
						});
					});
				});
			}
		},

		wishbone_postlove: function() {
			if( $('.sl-button').length ){
				$(document).on('click', '.sl-button', function() {
					var button = $(this);
					var post_id = button.attr('data-post-id');
					var security = button.attr('data-nonce');
					var iscomment = button.attr('data-iscomment');
					var allbuttons;
					if (iscomment === '1') { /* Comments can have same id */
						allbuttons = $('.sl-comment-button-' + post_id);
					} else {
						allbuttons = $('.sl-button-' + post_id);
					}
					var loader = allbuttons.next('.sl-loader');
					if (post_id !== '') {
						$.ajax({
							type: 'POST',
							url: simpleLikes.ajaxurl,
							data: {
								action: 'wishbone_process_simple_like',
								post_id: post_id,
								nonce: security,
								is_comment: iscomment
							},
							beforeSend: function() {
								loader.html();
							},
							success: function(response) {
								var icon = response.icon;
								var count = response.count;
								allbuttons.html(icon + count);
								if (response.status === 'unliked') {
									var like_text = simpleLikes.like;
									allbuttons.prop('title', like_text);
									allbuttons.removeClass('liked');
								} else {
									var unlike_text = simpleLikes.unlike;
									allbuttons.prop('title', unlike_text);
									allbuttons.addClass('liked');
								}
								loader.empty();
							}
						});
					}
					return false;
				});
			}
		},

		wishbone_stickysidebar: function() {
			var windowwidth = $(window).width();
			if( windowwidth >= 1024 ){
				if( $('.wishbone_sticky').length ){
					$('.wishbone_maincontainer').imagesLoaded().always( function( instance ) {
						if( $('body').hasClass('stickymenuenabled') ) {
							var offsettoppx = $('.stickytarget').outerHeight();
						} else {
							var offsettoppx = 0;
						}
					    $(".wishbone_sticky").stick_in_parent({
							parent: $('.wishbone_maincontainer, .fw-container'),
							offset_top: offsettoppx
						});
					});
					$(window).bind("load", function() {
					   	$(document.body).trigger("sticky_kit:recalc");
					});
				}

			}
		},

		wishbone_masonry_loop: function() {
			if( $('.wishbone_msn_posts').length ){
				var $grid = $('.wishbone_msn_posts');

				$grid.isotope({
					itemSelector: '.wishbone_masonry_item',
					percentPosition: true,
					masonry: {
						// use outer width of grid-sizer for columnWidth
						columnWidth: '.grid-sizer',
						gutter: 25
					}
				});
				$grid.imagesLoaded().always( function( instance ) {
				    $grid.isotope('layout');
				});
				$(window).bind("load", function() {
				   $grid.isotope('layout');
				});

				// Stretch pagination next prev to right lil bit
				$('.nextprev').addClass('wishbone_stretchright');
			}
		},

		wishbone_simplegrid_loop: function() {
			if( $('.wishbone_simgrid_posts').length ){

				var $grid = $('.wishbone_simgrid_posts');

				$grid.isotope({
					itemSelector: '.wishbone_simgrid_item',
					percentPosition: true,
					masonry: {
						// use outer width of grid-sizer for columnWidth
						columnWidth: '.grid-sizer',
						gutter: 25
					}
				});

				$grid.imagesLoaded().always( function( instance ) {
				    $grid.isotope('layout');
				});

				$(window).bind("load", function() {
				   $grid.isotope('layout');
				});

				// Stretch pagination next prev to right lil bit
				$('.nextprev').addClass('wishbone_stretchright');
			}
		},

		wishbone_ajaxloadmore: function() {
			$('.wishbone_loadmorebutton').click(function(e){
				e.preventDefault();
				var button = $(this),
					looptype = button.attr('data-looptype'),
					perpage = button.attr('data-perpage'),
					targetoffset = button.attr('data-targetoffset'),
					currentpaged = button.attr('data-currentpaged'),
					year = button.attr('data-year'),
					month = button.attr('data-month'),
					day = button.attr('data-day'),
					author = button.attr('data-author'),
					search = button.attr('data-search'),
					tag_id = button.attr('data-tag'),
					maxpages = button.attr('data-maxpages');

				if(button.hasAttr('data-cat')) {
			        var cat = button.attr('data-cat');
			    }

				// Prevent operation in the last page
				if( maxpages == currentpaged ){
					return false;
				}

				jQuery.ajax({
					type: 'POST',
					url: jp.ajaxURL,
					data: {
						"action": "wishbone_loadmore",
						"looptype": looptype,
						"perpage": perpage,
						"currentpaged": currentpaged,
						"cat": cat,
						"targetoffset": targetoffset,
						"loadmore": jp.loadmore,
						"loading": jp.loading,
						"caughtup": jp.caughtup,
						"year": year,
						"month": month,
						"day": day,
						"search": search,
						"tag_id": tag_id,
						"author": author,
					},
					dataType: 'json',
					beforeSend: function(data) {
						button.text(jp.loading);
						$('.wishbone_blogwrapper').find('article:not(.alreadyloaded)').addClass('alreadyloaded');
					},
					success: function(data) {

						// INSERT DATA DEPENDS ON LOOP TYPE, masonry and simple grid will trigger isotope effect.
						if( 'default' == looptype ){

							$(data['html']).insertBefore(button);

						} else if( 'masonry' == looptype ){

						    var $items = $(data['html']);
						    $('.wishbone_msn_posts').append( $items ).imagesLoaded().always().isotope( 'appended', $items ).wait(1000).isotope('layout');

						} else if( 'simplegrid' == looptype ){

						    var $items = $(data['html']);
						    $('.wishbone_simgrid_posts').append( $items ).imagesLoaded().always().isotope( 'appended', $items ).wait(1000).isotope('layout');

						} else if( 'simplelist' == looptype ){

							var $items = $(data['html']);
							$items.insertBefore(button);

						} else {

							$(data['html']).insertBefore(button);

						}

						// Update the button
						var newcurrentpaged = parseInt(currentpaged) + 1;
						button.attr('data-currentpaged', newcurrentpaged);

						// In the last page, make the button unclickable
						if( maxpages == newcurrentpaged ){
							button.text(jp.caughtup).addClass('isdead');
						} else {
							button.text(jp.loadmore);
						}

						// Trigger back post share button
						Wishbone.wishbone_postshare();

						// Trigger back prettySocial
						$('.wishbone_postloop').not('.alreadyloaded').each(function(){
							$(this).find('.prettySocial').prettySocial();
						});

						// Recalculate the sticky sidebar
						$(document.body).trigger("sticky_kit:recalc");

					},
					error: function(data){
						button.text('ERROR!');
					}
				});
			});
		},

		wishbone_article: function() {

			/* Give parallax effect */
			if( $(window).width() >= 900 ){
				$.stellar({
					horizontalScrolling: false
				});
			}

			/* Wrap everything except figure, blockquote and image */
			$('.wishbone_widearticle_content > *').not('figure').not('img').not('blockquote').not('canvas').not('script').each( function(){
				$(this).wrap('<div class="wishbone_single_excerpt"></div>');
			});

			$('.wishbone_widearticleheader').each(function(){
				var background = $(this).attr('data-background');
				$('.wishbone_widearticleheader').css({"background-image": "url("+background+")"});
			});

			/* Selection Sharer */
			$('.wishbone_typography p:not(.wishbone_articleauthorinfo p)').selectionSharer();

			/* SHORTLINK Click */
			$('.wishbone_shortlinkbox').each(function() {
				$(this).click(function() {
					$(this).selectText();
				});
			});

			// Remove pseudo elements if an anchor contains image
			$('img:not(.wishbone_widget img):not(.widget_flickr_image_gallery img)').each(function(){
				$(this).parent('a[href]').filter(function() {
				  	return /(jpg|gif|png)$/.test($(this).attr('href'));
				}).addClass('nopseudo');
			});

			// if anchor targets are an image format, zoom it with magnificPopup
			$('.wishbone_maincontainer a[href]').filter(function() {
			  	return /(jpg|gif|png)$/.test($(this).attr('href'))
			}).not('.imgPinWrap a').magnificPopup({
				type: 'image',
				closeOnContentClick: true,
				closeBtnInside: false,
				fixedContentPos: true,
				mainClass: 'mfp-no-margins mfp-with-zoom mfp-fade',
				image: {
					verticalFit: true
				},
				zoom: {
					enabled: true,
					duration: 300 // don't foget to change the duration also in CSS
				},
				gallery:{
				    enabled:true,
				    preload: [0,2]
				}
	        }).addClass('wishbone_iszoomable');

	        // if anchor targets are an image format, zoom it with magnificPopup
			$('.widget_flickr_image_gallery a[href]').filter(function() {
			  	return /(jpg|gif|png)$/.test($(this).attr('href'))
			}).magnificPopup({
				type: 'image',
				closeOnContentClick: true,
				closeBtnInside: false,
				fixedContentPos: true,
				mainClass: 'mfp-no-margins mfp-with-zoom mfp-fade',
				image: {
					verticalFit: true
				},
				zoom: {
					enabled: true,
					duration: 300 // don't foget to change the duration also in CSS
				},
				gallery:{
				    enabled:true,
				    preload: [0,2]
				}
	        }).addClass('wishbone_iszoomable');

			// Post gallery
			$('.post-gallery').owlCarousel({
				nav: false,
				center: false,
				items:1,
				loop: false,
				margin: 0,
			});

	        // Comment Readmore
		    $('.comment-content').each(function(){
		        $(this).shorten({
					moreText: jp.readmore,
					lessText: jp.less,
					showChars: 349,
				});
			});

			// RSS Widget
			$('.rssSummary').each(function(){
				$(this).shorten({
					moreText: jp.readmore,
					lessText: jp.less,
					showChars: 100,
				});
			});

			// Add loaded class
			$(window).bind("load", function(){
				$('.wishbone_widearticle_content').addClass('loaded');

				$('.wishbone_typography').find('img').each(function(){
					$(this).not('.wishbone_authorwriterava img').imgPin();
				});

				$('.wishbone_typography').find('img').each(function(){
					$(this).parents('.imgPinWrap').addClass('haspinbutton');
					if( $(this).hasClass('alignleft') ){
						$(this).parents('.imgPinWrap').css('float', 'left');
					} else if( $(this).hasClass('alignright') ) {
						$(this).parents('.imgPinWrap').css('float', 'right');
					} else if( $(this).hasClass('aligncenter') ) {
						$(this).parents('.imgPinWrap').css({
					      "float": "none",
					      "width": "auto",
					      "display": "inline-block",
					      "text-align": "center",
					    });
						$(this).parents('.imgPinWrap').wrap('<div class="text-center"></div>');
					}
				});
			});

			// Pretty Social
			$('.prettySocial').prettySocial();
		},

		wishbone_footer: function() {
			$("iframe").parent().fitVids();
		},

		wishbone_backtotop: function() {
			if ($('.wishbone_backtotop').length) {
			    var scrollTrigger = 100, // px
			        backToTop = function () {
			            var scrollTop = $(window).scrollTop();
			            if (scrollTop > scrollTrigger) {
			               $('.wishbone_backtotop').addClass('show');
			            } else {
			               $('.wishbone_backtotop').removeClass('show');
			            }
			        };
			    backToTop();
			    $(window).on('scroll', function () {
			        backToTop();
			    });
			    $('.wishbone_backtotop').on('click', function (e) {
			        e.preventDefault();
			        $('html,body').animate({
			            scrollTop: 0
			        }, 300);
			    });
			}
		},

		wishbone_m_header: function() {
			if( $('.wishbone_m_menuitems').length ){
				$('.wishbone_m_menuitems > li.menu-item-has-children > a').each(function() {
					var thisanchor = $(this),
						anchorparent = $(this).parent(); // .headermobile_menu > li
					thisanchor.append('<span class="wishbone_m_menuexpand normal"></span>');
					thisanchor.find('span').funcToggle('click', function() {
						anchorparent.find('> ul').velocity("slideDown", {
							duration: 850,
							easing: "spring"
						});
					}, function() {
						anchorparent.find('> ul').velocity("slideUp", {
							duration: 300,
							easing: "easeInOutQuart"
						});
					});
				});
			}

			$('.wishbone_m_menutrigger').funcToggle('click', function() {
				$('.wishbone_m_menuitems').velocity("slideDown", {
					duration: 850,
					easing: "spring"
				});
			}, function() {
				$('.wishbone_m_menuitems').velocity("slideUp", {
					duration: 300,
					easing: "easeInOutQuart"
				});
			});

			$('.wishbone_m_srctrigger').funcToggle('click', function() {
				$('.wishbone_m_searchwrapper').velocity("slideDown", {
					duration: 300,
					easing: "easeInOutQuart"
				});
			}, function() {
				$('.wishbone_m_searchwrapper').velocity("slideUp", {
					duration: 300,
					easing: "easeInOutQuart"
				});
			});

		}

	}; // End return {}
})(jQuery);

jQuery(document).ready(function($){
	"use strict";
	$('body').addClass('body');
	Wishbone.init();

	$(window).smartresize(function(){
		var resizedwidth = $(this).width();
		if( resizedwidth >= 1024 ){
			setTimeout(function() {
				Wishbone.wishbone_stickysidebar();
			}, 1000);
		}

	});
});

jQuery(document).foundation();
