/* =========================================

	Positive Theme - Js Functions

============================================*/
$(document).ready(function () {

    $("body").removeClass('wait-js');
	

    // Get JS Options
    var thm_ajax_url = $("meta[name=theme_ajax_url]").attr('content');
    var navigation_delay = parseInt($("meta[name=navigation_delay]").attr('content')) || 300;


    // Trigger: animated_content
    $('#wide-content, #withsidebar-content').bind('animated_content', function () {
        match_page_height();
        make_shadows();

    });

    // Navigation Menu
    $('ul#navigation-menu-items').superfish({
        hoverClass: 'navigation-menu-hover',
        delay: navigation_delay,
        animation: {
            opacity: 'show',
            height: 'show'
        },
        speed: 'fast',
        autoArrows: false,
        dropShadows: false,
        disableHI: true,
        onBeforeShow: function () {
            $(".megaMenu").children(".sub-menu").find(".sub-menu").show().css('visibility', 'visible');
        },
        onHide: function () {
            $(".megaMenu").children(".sub-menu").find(".sub-menu").show().css('visibility', 'visible');
        }
    });

    // Center Sub Menus
    /*$('ul#navigation-menu-items > li').not('.megaMenu').each(function () {
        el = $(this);
        if (el.has("ul")) {
            var width = $(this).width();
            var sub_el = el.children("ul");
            var spaces = (sub_el.width() - width) / 2;

            if (spaces) sub_el.css({
                marginLeft: "-" + spaces + "px"
            });
        }
    });*/
	
	$('ul#navigation-menu-items > li.megaMenu').each(function () {
        el = $(this);
		
		el.find('> .sub-menu > li > a').removeAttr('href').addClass('megeMenuTitle');
		/*el.find('> .sub-menu > li > a').replaceWith(function() {
		  return '<span class="a">'+$(this).html()+'</span>';
		});*/

    });

    // Left Side
    $('.min-container-hover-me').live('mouseover mouseout', function (event) {
        if (event.type == 'mouseover') {
            var el = $(this);
            el.animate({
                'left': '-60px'
            });

            if ($.browser.msie) {
                var parel = el.parent('.hover-me-fix');
                parel.find('.shadows').animate({
                    'left': '-60px'
                });
            }

        } else {
            var el = $(this);
            el.animate({
                'left': '-20px'
            });

            if ($.browser.msie) {
                var parel = el.parent('.hover-me-fix');
                parel.find('.shadows').animate({
                    'left': '-20px'
                });
            }
        }
    });


    $(".slides").slides({
        preload: true,
        preloadImage: '/img/loading.gif',
        play: 0,
        pause: 2500,
        hoverPause: true,
        autoHeight: true,
        animationComplete: function () {
            $('#withsidebar-content').trigger('animated_content');
        }
    });



    // Match Container Heights
    match_page_height();

    // Box Shadow For IE
    make_shadows();



    // Some CSS Fixing
    $('.left-side').each(function () {

        var el = $(this);
        var pos = el.position();
        var id = el.parents('.blog-posts-list').attr('id');

        el.clone().prependTo('#content-containers').addClass('min-container').css({
            'top': pos.top,
            'visibility': 'visible'
        }).attr('rel', id).wrap('<div class="hover-me-fix"></div>');
        el.remove();
    });

    $('#wide-content, #withsidebar-content').bind('animated_content', function () {

        $('.left-side').each(function () {

            var el = $(this);
            var parent_el = $('#' + el.attr('rel'));
            if (typeof parent_el == 'undefined') {
                throw new Error(parent_el + "Element Cannot Found");
                return false;
            }

            var pos = parent_el.find('.blog-title').position();
            el.animate({
                top: pos.top
            });

        });

    });

    if ($.isFunction($.fn.tipsy)) {

        $('.tooltip').tipsy({
            gravity: $.fn.tipsy.autoNS,
            fade: true,
            offset: 20
        });

    }

    // Sharing
    $('.sharethis').toggle(

		function () {
			$(this).addClass("active");
			var el = $(this).parents('.left-side');
			var parent_el = $('#' + el.attr('rel'));
			if (typeof parent_el == 'undefined') {
				throw new Error(parent_el + ": Element Cannot Found");
				return false;
			}
	
			parent_el.find('.blog-post-header-action').animate({
				width: 0
			}, {
				duration: 500,
				specialEasing: {
					width: 'easeInOut'
				}
			}, function () {
				make_shadows();
		});

    },

		function () {
			$(this).removeClass("active");
			var el = $(this).parents('.left-side');
			var parent_el = $('#' + el.attr('rel'));
			if (typeof parent_el == 'undefined') {
				throw new Error(parent_el + "Element Cannot Found");
				return false;
			}
	
			parent_el.find('.blog-post-header-action').animate({
				width: 560
			}, {
				duration: 500,
				specialEasing: {
					width: 'easeInOut'
				}
			}, function () {
				make_shadows();
		});

    }

    );

    // Blog Posts Pagination
    $('#blog-pagination').click(

    function () {
        var el = $(this).parents('.blog-pagination-summary');
        if (typeof el == 'undefined') {
            throw new Error(el + ": Element Cannot Found");
            return false;
        }
        el.slideUp();

        $('.blog-pagination').hoverIntent({
            sensitivity: 1,
            interval: 100,
            over: function () {},
            timeout: 1500,
            out: function () {
                el.slideDown();
            }
        });
    }

    );

    // Blog Post Shortcode Hover Effects
    if ( $('.shortcode_minimal_blog_container_style_2').length > 0 ) {
        
        $('.shortcode_minimal_blog_container_style_2 > .blog-thumbnail').hoverIntent({
            sensitivity: 1,
            interval: 100,
            over: function () { $(this).find('a > span').stop(1,1).fadeTo(300,0); },
            timeout: 100,
            out: function ()  { $(this).find('a > span').stop(1,1).fadeTo(300,1); }
        });

    }


    $('.widget_subposts > ul > li, #sidebar .widget_nav_menu > div > ul > li').each(function () {

        if ($(this).find("ul").length > 0) {

            $(this).hoverIntent({
                sensitivity: 1,
                interval: 100,
                over: function () {
                    $(this).find("> ul").slideDown(function () {
                        $('#withsidebar-content').trigger('animated_content');
                    });
                },
                timeout: 1000,
                out: function () {
                    $(this).find("> ul").slideUp(function () {
                        $('#withsidebar-content').trigger('animated_content');
                    });
                }
            }).append("<span class=\"subpost-arrow\"><span class=\"the-arrow\"></span></span>");

        }

    });


    $('.portfolio').each(function () {
        $(this).CloudPortfolio();
    });
    $('.carousel').each(function () {
        $(this).CloudCarousel();
    });
    $('.tabs').each(function () {
        $(this).CloudTabs();
    });
    $('.toggle').each(function () {
        $(this).CloudToggle();
    });
	
    $(".gallery-icon").each(function(){
		var el = $(this);
		el.find('> a').attr('rel', 'prettyPhoto['+ el.attr('data-group') +']');
	});
	
	
	
    $("a[rel^='prettyPhoto']").runPrettyPhoto();
	
    $("img[class*='wp-image']").parent('a').each(function(){
		$(this).runPrettyPhoto();
	});

	
    $('img.load').CloudLoadImages({});


    /*************************************/


    $('.cloudfw_page').click(function () {

        var xhr;
        var time_ = !$.browser.msie ? 300 : 1;
        var gimg = $(this).attr('href');
        var pid = $(this).attr('data-post-id');
        var main_content = $('#content-containers');
        main_content_width = main_content.width();
        main_content_height = main_content.outerHeight(true);
        window_width = $(window).width();
        calc_margin = ((window_width - main_content_width) / 2 + main_content_width);
        main_content_mleft = ((window_width - main_content_width) / 2);

        if ($('body').hasClass('runInAjax'))
            return false;

        if(xhr && xhr.readystate != 4){
            xhr.abort();
        }


        $('#cloudfw-loading').fadeIn();
        $('#slider').hide();
        $('body').addClass('runInAjax');

        $.scrollTo($('#content'), {
            duration: 500,
            offset: {
                top: -50
            },
            onAfter: function () {

                main_content.after('\
            		<div id="test" style="display: none;"><div id="content-containers" class="the-page">\
            			<div id="wide-container" class="make-shadow global-radius">\
            					<div id="wide-content" class="tete content global-radius">\
            						<div id="close-container">\
            							<a class="back-to-page" href="#close">Close</a>\
            						</div>\
                                    <div class="cf"></div>\
            					</div>\
            				</div>\
            			</div>\
            		</div>\
                    <div class="cf"></div>\
    			');

                new_el = $('#test');

                new_el.css({
                    position: 'absolute',
                    top: 0,
                    left: 0
                }).hide();

                xhr = $.ajax({
                    url: thm_ajax_url,
                    cache: false,
                    data: ({
                        p: pid,
                        action: 'cloudfw_show_post'
                    }),
                    success: function (data) {
                        $('body').removeClass('runInAjax');
                        $('#cloudfw-loading').fadeOut();
                        $('.tete', new_el).prepend(data);



                        main_content.fadeOut(time_, function () {});
                        new_el.fadeIn(time_, function () {
                            new_el.css({
                                position: ''
                            });
                            $('#wide-content').trigger('animated_content');
                        });


                        new_el.find('img').CloudLoadImages({
                            after_loading: function () {
                                $('#content').css({
                                    'min-height': new_el.outerHeight()
                                });
                                $('#wide-content').trigger('animated_content');
                            }
                        });


                        new_el.find('.portfolio').each(function () {
                            $(this).CloudPortfolio();
                        });
                        new_el.find('.carousel').each(function () {
                            $(this).CloudCarousel();
                        });
                        new_el.find('.tabs').each(function () {
                            $(this).CloudTabs();
                        });
                        new_el.find('.toggle').each(function () {
                            $(this).CloudToggle();
                        });
											
						$("a[rel^='prettyPhoto']").each(function(){ 
							$(this).runPrettyPhoto();
						});
						
						$("img[class*='wp-image']").parent('a').each(function(){
							$(this).runPrettyPhoto();
						});
	
                        $('#content').css({
                            'min-height': $('.tete',new_el).outerHeight()
                        });
                        $('#wide-content').trigger('animated_content');


                    } //end-success

                }); //ajax-end
                $('#wide-content').trigger('animated_content');

                $('#close-container a').bind("click", function () {
                    $('#slider').show();
                    $('#content').animate({
                        'min-height': main_content_height
                    });

                    new_el.fadeOut(time_, function () {
                        new_el.remove();
                    });
                    main_content.fadeIn({
                        marginLeft: 0
                    }, time_);

                    $('#content').css({
                        'min-height': 'auto'
                    });
                    $('#wide-content').trigger('animated_content');
                    return false;

                });


            }
        });


        return false;

    });



    /*************************************/


    var timeout = setTimeout(function () {
        $('#withsidebar-content').trigger('animated_content');
    }, 5000);


    var debug = $('#debugger');

    $(".slider-scroll .slides_control").find('a,img').live(($.support.selectstart ? "selectstart" : "mousedown"), function (event) {
        event.preventDefault();
    });

    $(".slider-scroll .slides_control").live('mousedown', function () {
        allAElements = $(this).find('a');
        allAElements.unbind("click");
        var linksDisable = false;

        if ($(this).is(':animated')) return false;

        var onclick = false;

        first_pos = 0;
        last_pos = 0;

        $(this).bind('mouseleave', function () {
            $(this).stop(true).animate({
                left: default_slides_control_left
            }, {
                duration: 500,
                easing: "easeOutElastic"
            }, function () {
                onclick = true;
            }).css('cursor', 'default').unbind('mousemove').unbind('mouseup').unbind('mouseleave')
            allAElements.css('cursor', '').unbind("click");
        });

        $(this).css('cursor', 'move').bind('mousemove', function (e) {

            if (!first_pos > 0) last_pos = first_pos = e.pageX;

            cor_x = e.pageX;

            if (first_pos > 0) {

                if (last_pos > cor_x) {
                    diff = (last_pos - cor_x);
                    total_diff = (first_pos - cor_x);

                    $(this).css('left', function (index) {
                        return (parseFloat($(this).css('left')) - diff);
                    });
                    last_pos = cor_x;
                    if (total_diff > 200) {
                        mouseup_slider();
                        onclick = true;
                    }

                    $("#y_", debug).text((first_pos - cor_x));
                } else {
                    diff = (cor_x - last_pos);
                    total_diff = (cor_x - first_pos);

                    $(this).css('left', function (index) {
                        return (parseFloat($(this).css('left')) + diff);
                    });
                    last_pos = cor_x;
                    if (total_diff > 200) {
                        mouseup_slider();
                        onclick = true;
                    }

                    $("#y_", debug).text((cor_x - first_pos));
                }



            }


            if (linksDisable === false && total_diff > 5) {
                allAElements.css('cursor', 'move').bind("click", function (event) {
                    event.preventDefault();
                    linksDisable = true;
                });

                $('#slider').trigger('pause_');
            }


            $("#x_", debug).text("" + first_pos + ", " + cor_x);

        });


        $(".slider-scroll .slides_control").mouseup(function () {

            if (onclick === false) mouseup_slider($(this));

        });

    });

    function mouseup_slider(element) {
        //if(element.is(':animated')) return false;
        if (first_pos > 0) {

            if (first_pos > cor_x) {
                $('#slider').trigger('next_');
                first_pos = 0;
                last_pos = 0;
            } else {
                $('#slider').trigger('prev_');
                first_pos = 0;
                last_pos = 0;
            }
        }
		$(".slider-scroll .slides_control").css('cursor', 'default').unbind('mousemove').unbind('mouseup').unbind('mouseleave')
        allAElements.css('cursor', '').unbind("click");
    }

});