//Dynamically load LAB.js
(function (global, oDOC, handler) {
    var head = oDOC.head || oDOC.getElementsByTagName("head");

    function LABjsLoaded() {

		addthis_share = {
			templates: {
				twitter: '{{title}} {{url}} via @Egotastic'
			}
		}

        var initScripts = [], scriptsPath = "http://" + self.location.host + "/wp-content/themes/egotasticsubtheme/scripts/";
                
        initScripts["jcarousellite"] = scriptsPath + "jcarousellite_1.0.1.min.js";
        initScripts["jcarousel"] = scriptsPath + "jquery.jcarousel.min.js";
        initScripts["addthis"] = "http://s7.addthis.com/js/250/addthis_widget.js#username=celebuzz";
        //initScripts["intellitxt"] = "http://egotastic.us.intellitxt.com/intellitxt/front.asp?ipid=23815";
        initScripts["twitter"] = "http://platform.twitter.com/widgets.js";
		initScripts["topnav"] = 'http://cdn.buzznet.com/assets/cb/cssjs/drawCelebNav.js';
		
        $LAB
  
        .script(
         initScripts["jcarousellite"], 
         initScripts["jcarousel"],
         initScripts["addthis"],  
         initScripts["twitter"]
         )
		
		
        .wait(function () {
            jQuery(document).ready(function ($) {

                // Bring in carousel 
               showCarousel();
					
				$('.image-gallery-thumb').hover(function(){
				 $(this).find('.activestate').fadeIn();
				},function(){
				 
				 if($(this).hasClass('current')){return false;}
				 
				 $(this).find('.activestate').fadeOut();
				 });
				
                //bring in social sharing
                $('.atblock').fadeIn();
                $('.entry-utility').fadeIn();
                $('.teasershare').fadeIn();

                $('.allstrtab').click(function () {
                    $(this).addClass('actvtab');
                    $('.h5tab').removeClass('actvtab');
                    $('#thehot5').fadeOut();
                    $('#recent-allstars').fadeIn();
                });

                $('.h5tab').click(function () {
                    $(this).addClass('actvtab');
                    $('.allstrtab').removeClass('actvtab');
                    $('#recent-allstars').fadeOut();
                    $('#thehot5').fadeIn();
                });            

            });
        })
    }

    // loading code borrowed directly from LABjs itself
    setTimeout(function () {
        if ("item" in head) { // check if ref is still a live node list
            if (!head[0]) { // append_to node not yet ready
                setTimeout(arguments.callee, 25);
                return;
            }
            head = head[0]; // reassign from live node list ref to pure node ref -- avoids nasty IE bug where changes to DOM invalidate live node lists
        }
        var scriptElem = oDOC.createElement("script"),
            scriptdone = false;
        scriptElem.onload = scriptElem.onreadystatechange = function () {
            if ((scriptElem.readyState && scriptElem.readyState !== "complete" && scriptElem.readyState !== "loaded") || scriptdone) {
                return false;
            }
            scriptElem.onload = scriptElem.onreadystatechange = null;
            scriptdone = true;
            LABjsLoaded();
        };
        scriptElem.src = "http://" + self.location.host + "/wp-content/themes/egotasticsubtheme/scripts/LAB.min.js";
        head.insertBefore(scriptElem, head.firstChild);
    }, 0);

    // required: shim for FF <= 3.5 not having document.readyState
    if (oDOC.readyState == null && oDOC.addEventListener) {
        oDOC.readyState = "loading";
        oDOC.addEventListener("DOMContentLoaded", handler = function () {
            oDOC.removeEventListener("DOMContentLoaded", handler, false);
            oDOC.readyState = "complete";
        }, false);
    }
})(window, document);


/* Functions */
//Lookup for the AJAX pages... (celebs)
var findObject;

function lookup(inputString, type) {

    findObject = {
        celebSuggest: jQuery("#celeb-suggest"),
        navBelow: jQuery('#nav-below'),
        foundContent: jQuery("#content"),
        clearSearch: jQuery('#clr-srch'),
        searchStr: inputString,
        ajaxurl: 'http://' + self.location.host + '/wp-content/themes/egotasticsubtheme/ajax-process.php'
    }

    if (inputString.length == 0) {
        findObject.celebSuggest.fadeOut();
        findObject.foundContent.fadeIn();
        findObject.navBelow.fadeIn();
    } else {
        findObject.foundContent.fadeOut();
        findObject.navBelow.fadeOut();
        findObject.celebSuggest.fadeIn();

        findObject.searchText = 'q=' + findObject.searchStr + '&action=find_' + type + '&anticache=' + Math.random();

        //send to ajax so we can find in db...
        jQuery.get(findObject.ajaxurl, findObject.searchText,

        function (data) {
            if (data.length > 0) {
                findObject.celebSuggest.html(data + '<span id="clr-srch" onClick="clearFindSearch()">x clear search</span>');
                findObject.clearSearch.fadeIn();
				var se = findObject.celebSuggest.find('.holdr-first:eq(0)');
				findObject.celebSuggest.height( data.match(/holdr\-first/ig).length * ( se.height() + parseInt( se.css('padding-bottom').replace('px', ''), 10) ) );
            }
        });
    }
}

function clearFindSearch() {

    findObject.celebSuggest.fadeOut();
    findObject.clearSearch.fadeOut();
    findObject.foundContent.fadeIn();
    findObject.navBelow.fadeIn();
    var txtBox = jQuery('#gallerindex-head #searchform .textbox');

    txtBox.val('search celebrities');
}

				//Moving this definition into the DOM ready event for Chrome / Safari
				//
                function showCarousel() {

                    //fade in now that the document is ready
                    var galBlock = jQuery('#image-gallery-slider');
                    var galContainer = jQuery('#image-gallery-container');
                    var index = parseInt(jQuery('#image-gallery-slider .image-gallery-list li.current a img').attr('name'));
					var actv = jQuery('.current .activestate');
                    var total = parseInt(jQuery('#image-gallery-slider ul li').length);
                    var galNext = jQuery('#image-gallery-container .next');
                    var galPrev = jQuery('#image-gallery-container .prev');
                     galBlock.fadeIn();
                     galContainer.removeClass('loading');

                    //Trigger carousel
                   var  slider = jQuery('#image-gallery-slider ul');
           
                    if(slider.length){ 

                     galContainer.jcarousel( {
        			 	"scroll" : 3,
        			 	"start" : index,
        			 	"offset" : 1,
        			 	"initCallback" : sldrExternalCntrl, //set controls
        			 	"size" : total,
        			 	"visible" : 4,
        			 	"itemFallbackDimension" : 100
                     });	
                    } 
				   
				   function sldrExternalCntrl(slider, state){                 
                   
                   jQuery( '#image-gallery-container span.prev' ).bind('click', function() {
        			slider.prev();
        			return false;
    			   });

                   jQuery( '#image-gallery-container span.next' ).bind('click', function() {
        			slider.next();
        			return false;
    			   });
    			 }  
                  actv.show();

                    /* carousel 2 (all stars) */
                   var allstrBlock = jQuery('#gf-most-pop .car-window');
                   allstrBlock.fadeIn( );
                   
         
                   
                   if( allstrBlock.length ){
                             
                    allstrBlock.jCarouselLite({
                        visible: 4,
                        btnNext: '#gf-most-pop .arrw.next',
                        btnPrev: '#gf-most-pop .arrw.prev',
                        scroll: 4
                    });
                   
                  }
                }


/* Chartbeat */
var _sf_async_config={uid:25328,domain:"egotastic.com"};
(function(){
function loadChartbeat() {window._sf_endpt=(new Date()).getTime();var e = document.createElement('script');e.setAttribute('language', 'javascript');e.setAttribute('type', 'text/javascript');e.setAttribute('src', (("https:" == document.location.protocol) ? "https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/" : "http://static.chartbeat.com/") + "js/chartbeat.js");document.body.appendChild(e);}
var oldonload = window.onload;
window.onload = (typeof window.onload != 'function') ?
loadChartbeat : function() {oldonload();loadChartbeat();};
})();


jQuery( document ).ready(function( $ ){
	// It is fix for the last child thumb until it will numbered classes in ice plugin for cbme-double-thumb-wrapper elements.
	$( 'div.cbme-thumbs-wrapper' ).each(function( index, element ) {
		var clears = $( element ).find( 'div.cbme-double-thumb-wrapper' );
		if( clears.length == 4 )
			clears.last().attr( 'style', 'background: none !important' );
	});
	$( '.cbme-image-wrapper-400x300-overlay' ).each(function( index, element ) {
		var clears = $( element ).parent().parent().find( '.cbme-double-thumb-wrapper' );
		if ( clears.length == 3 )
			clears.last().attr( 'style', 'background: none !important' );
	});
	
	// It's fix for the last row for the hot 5 widget
	$( '#thehot5 > ul' ).last().find("li").last().addClass('sidebar-item-last').find("a").addClass('hwrap-last');
	
	// IE fix for links chilren
	if ( $.browser.msie ) {
		// Fix for IE7, link became clickable and it provides it's own url
		$("#recent-allstars, #thehot5").find(".hwrap").children().click(function(event) {
			document.location.href = $( event.currentTarget ).parent().attr("href");
		});
	}
	
	// Fix AddThis popup for IE 7
	if ( $.browser.msie && $.browser.version < 8.0 )
	{
		$( '.addthis-all' ).find( ".addthis_button_compact" ).bind('mouseover', function() {
			var addThis = $('#at15s');
			var addThisOffset = addThis.offset();
			addThis.css('left', (addThisOffset.left - 200) + "px").css('top', (addThisOffset.top - 10) + "px");
		});
	}

	//Fix more linck
	$( '.more-link' ).parent().css('margin-bottom', '8px');
	$( '.more-link' ).parent().prev().css('margin-bottom', '8px');
	/*
	var thumbnail_grid_img = $( '.category-all-stars .cbme-gallery-wrapper-thumbnailgrid .cbme-image-wrapper-600x450-overlay a img' );
	if(thumbnail_grid_img.length) {
		var thumbnail_grid_img_wraper_height = $('.category-all-stars .cbme-gallery-wrapper-thumbnailgrid .cbme-image-wrapper-600x450-overlay').height();
		var thumbnail_grid_img_height = thumbnail_grid_img.height();
		if (thumbnail_grid_img_height < thumbnail_grid_img_wraper_height) {
			var thumbnail_grid_img_top_offset = Math.ceil((thumbnail_grid_img_wraper_height - thumbnail_grid_img_height) / 2);
			thumbnail_grid_img.css('padding-top',thumbnail_grid_img_top_offset + 'px');
		}
	}
	*/

	if ( $.browser.msie && $.browser.version < 8.0 ) {
		$("span#gallary_main_img_crop_span").click(function(event) {
			document.location.href = $( event.currentTarget ).parent().attr("href");
		});
	}
});

