/*kids site initializations
* This is run as a jQuery method and not on an element. It runs once per page load.
*
* Usage:
*   $.initKids({options});
*/
(function($){
    var defaults = { },
        methods = {
            init: function(options) {
                var settings = $.extend({}, defaults, options),
                    data = $(document).data('initKids'),
                    initers = {
                        initNav : function() {
                            //fadeTo is used as opposed to show/hide/display:none to allow subnav
                            //repositioning to work properly and for hoverIntent to work.
                            $('#kids_nav > li > div').fadeTo(0, 0).css('z-index','-1');
                            $('#kids_nav > .nav_selected > div').fadeTo(0, 1);
                            $('#kids_nav').data('activeNav', $('#kids_nav > .nav_selected'));

                            //Repositions subnavs. Application of Fitts's law

							//had to add the - 1 for the extra pixel appearing in IE
                            $('#kids_nav > li').each(function(){
                                var $this = $(this),
                                    $subNav = $this.find('ul'),
                                    subNavWidth = 0,
                                    navWidth = ($this.find('ul').eq(0).width()>0)?$this.find('ul').eq(0).width():0,
                                    parentNavPosition = $this.position().left,
                                    wiggleRoom;

                                $this.find('li').each(function(){
                                    subNavWidth += $(this).outerWidth(true);
                                });
                                wiggleRoom = (navWidth > subNavWidth) ? navWidth - subNavWidth - 1 : 0;

                                $subNav.find('li').eq(0).css('margin-left', ((parentNavPosition > wiggleRoom) ? wiggleRoom : parentNavPosition - 10));
                            });
                        },
                        // creates background styling for kids features modules, makes same size if appearing in pairs
                        initFeatures : function() {/*
                            $('.kids_features').parent('div').addClass('kids_features0');
                            $('.kids_features0').parent('div.primary').addClass('kids_features1');
                            $('.kids_features0').parent('div.primary').append('<div class="clear"></div>');
							$("#content_mainA .kids_features1").each(function(){
								if ($(this).children(".kids_features0").length == 2) {
									var featuresLeftHt = $(this).children(".kids_features0:nth-child(1)").height();
									var featuresRightHt = $(this).children(".kids_features0:nth-child(2)").height();
									var maxFeaturesHt = (featuresLeftHt >= featuresRightHt) ? featuresLeftHt : featuresRightHt;
									$(this).css("min-height",maxFeaturesHt);
								}
							});
							*/
                        },
                        // loads a different page background for each new page
                        backgroundRandomizer : function (setBG){
                            //There are 28 background images available numbered 00-27
                            var bgNumber = Math.floor(Math.random()*27);
                            bgNumber = (bgNumber < 10) ? '0' + bgNumber : bgNumber;
                            bgNumber = (setBG) ? setBG : bgNumber;
                            $('body').addClass('kids_bg' + bgNumber);
                        },
                        //localization initializations
                        us : function(){},
                        uk : function(){
                            var $natGeoHomeNavs = $('.topnav a[href="http://www.nationalgeographic.com/"]'), //all "bad" home links
                                $shopNav = $('.topnav a[title="Shop"]'), //all navigation items that link to the shop page
                                $littleKidsNav = $('#kids_nav_10'); //10th tophat nav item. "Little Kids" on US site.
                            //corrects home links on UK site to link to UK home
                            $natGeoHomeNavs.each(function(){
                                $(this).attr('href', 'http://www.nationalgeographic.co.uk/');
                            }); 

                            //UK has different shop site
                            $shopNav.attr('href', 'http://www.shopnatgeo.co.uk/');

                            //Change last tophat nav item ("Little Kids" on US) to "Magazine"
                            $littleKidsNav.find('span').text('Magazine');
                            $littleKidsNav.find('a').attr({'href': 'http://www.ngkids.co.uk', 'title': 'Magazine'});
                         },//ends uk
                        ca : function(){},
                        'in' : function(){},
                        
                        events : function (){
                            $('#kids_nav').bind({
                                //this is needed to reset the nav and subnav which acts like a breadcrumb when not being interacted with
                                mouseleave: function(e){
                                    var $activeTab = $('#kids_nav').data('activeNav'),
                                        $inactiveTabs = $('#kids_nav > li').not($activeTab);
					
									$inactiveTabs.children('div').fadeTo(100, 0, function(){ $(this).css('z-index', '-1').parent('.nav_highlight'); }); 
									$inactiveTabs.removeClass('nav_highlight');
                                    $activeTab.addClass('nav_highlight').children('div').css('z-index', '102').fadeTo(100, 1);
                                }
                            });
                            $('#kids_nav > li').bind({
                                mouseenter : function(e){
                                    var $target = ($(e.target).is('li')) ? $(e.target) : $(e.target).parents('li'),
                                        $targetSubNav = $target.children('div'),
                                        $allTabs = $target.siblings().andSelf(),
                                        $allTabsSubNav = $allTabs.children('div'),
										selOn = $allTabs.filter('.nav_highlight').size();

									if (selOn > 0) {
	                                    $allTabsSubNav.not($targetSubNav.get()).fadeTo(0, 0).css('z-index', '-1');
	                                    $allTabs.not($target.get()).removeClass('nav_highlight');
									}
									
									$target.addClass('nav_highlight');                                    
									$targetSubNav.css('z-index', '102').fadeTo(((selOn>0)?0:100), 1);
                                }//ends mouseenter
                                //                     timeout : 100
                            });// ends hover for main nav
                            $('#kids_nav li div li a').bind({
                                mouseenter : function(e){
                                    var $target = $(e.target);
                                    if ($target.is('span')) {
                                        $target = $target.parent();
                                    }
                                    $target.addClass('hover');
                                }
                            });
                            $('#kids_nav li div li a').bind({
                                mouseleave : function(e){
                                    var $target = $(e.target);
                                    if ($target.is('span')) {
                                        $target = $target.parent();
                                    }
                                    $target.removeClass('hover');
                                }
                            });// ends hover for subnav

                            //Wire up modal for send link if present
                            if (false && typeof $.colorbox === 'function') { //'false &&' forces false. Temp until the sendlink can be rewritten
                                $('#send_link').colorbox({
                                    href: (function () {
                                        return $('#send_link').attr('href') + '?url=' + window.location; 
                                    }()),
                                    iframe : true,
                                    innerWidth : '440px',
                                    innerHeight : '335px',
                                    fixed: true,
                                    transition : 'elastic',
                                    onComplete : function () {
                                        $('#colorbox').show();
                                    }
                                });
                            } else {
                                $('#send_link').live('click', function (e) {
                                    e.preventDefault();
                                    SendLink($(this).attr('href'));
                                    return false;
                                });
                            }
                        } // ends events
                    };
                if (!data){
                    $(document).data('initKids', {
                        currentPageTab : $('#kids_nav').children('.nav_highlight')
                    });
                    
                    //general initializations
                    initers.backgroundRandomizer();
                    initers.initNav();
                    initers.initFeatures();
                    initers.events();
                    
                    //apply region specfic funtions
                    if(initers[region]){
                        return initers[region].apply( this, Array.prototype.slice.call( arguments, 1 ));
                    }
                    else{ $.noop(); }
                }
            }
        }, // ends methods
        region = location.host.split('.').reverse()[0].split(':')[0];
        region = (region === 'com') ? 'us' : region;
        
        //redefines region if working locally.
        //until our development environment environment is able to internationalize, in order 
        //to test localally use the query "?intl=[region]" where "[region]" is a 2 character representation of
        //the region you are testin, ie. uk = United Kingdom/Great Britian, ca = Canada, etc.
        region = (location.search.match('intl')) ? location.search.split('=')[1] : region; 
        
        $.initKids = function( method ){
            if(methods[method]){
                return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
            } else if ( typeof method === 'object' || ! method ) {
              return methods.init.apply( this, arguments );
            } else {
              $.error( 'Method ' +  method + ' does not exist on jQuery.initializeKids' );
            }
        };
        
}(jQuery));

$.fn.hasAttr = function(name) {  
   return this.attr(name) !== undefined;
};

// rework kids features module
// creates background styling for kids features modules, makes same size if appearing in pairs
function kidsFeatures() {
	$('.kids_features').parent('div').addClass('kids_features0');
	$('.kids_features0').parent('div.primary').addClass('kids_features1');
	$('.kids_features0').parent('div.primary').append('<div class="clear"></div>');
	$("#content_mainA .kids_features1").each(function(){
		if ($(this).children(".kids_features0").length == 2) {
			var featuresLeftHt = $(this).children(".kids_features0:nth-child(1)").height();
			var featuresRightHt = $(this).children(".kids_features0:nth-child(2)").height();
			var maxFeaturesHt = (featuresLeftHt >= featuresRightHt) ? featuresLeftHt : featuresRightHt;
			$(this).css("min-height",maxFeaturesHt);
		}
	});
}

// skin the thumbnails in modules
function prettyThumbnails(className) {
    var classNameMainA = "#content "+className;
    $(classNameMainA).each(function(index) {
        var tgImgWidth,
            tgPerRow;
        // define spacing for each li based on the size of its images
        if (className === ".thumbnail_grid" || className === ".kids_myshot_grid") {
            tgImgWidth = $(this).children("ul").children("li.first").children("a").children("img").width();
        }
        if (className === ".related_group") {
            if ($(this).children("ul").hasClass("rg_100")) {
                tgImgWidth = 100;
            }
            else if ($(this).children("ul").hasClass("rg_160")) {
                tgImgWidth = 160;
            }
            else {
                tgImgWdith = 60;
            }
        }
    
        // if image width is 100, we can only fit 4 per row
        if (tgImgWidth === 100) {
            $(this).addClass("tg_100");
            tgPerRow = 4;
        }
        // if image width is 160, we can only fit 3 per row
        else if (tgImgWidth === 160) {
            $(this).addClass("tg_160");
            tgPerRow = 3;
        }
        else if (className === "#video_lineup") {
            $(this).addClass("tg_160");
            tgPerRow = 4;
        }
        // default to 3
        else {
            tgPerRow = 3;    
        }
        
        // grab the anchor info of each li and use that to create an absolutely position frame for each li
        $(this).children("ul").each(function(indexUl) {
            $(this).children("li").each(function(indexLi) {
                var thHref,
                    tgTitle,
                    tgImgSrc;
                    
                if (className === ".thumbnail_grid" || className === "#video_lineup" || className === ".kids_myshot_grid") {
                    tgHref = $(this).children("a").attr("href");
                    if (className === ".thumbnail_grid" || className === ".kids_myshot_grid") {
                        tgTitle = $(this).children("a").attr("title");
                        $(this).prepend('<a class="thumbnail_grid_frame" href="'+tgHref+'" title="'+tgTitle+'">&nbsp;</a>');
                    }
                    else {
                       tgImgSrc = $(this).children("a").children("img").attr("src");
//                       alert(tgImgSrc);
                       $(this).children("a").remove();
                       $(this).prepend('<a class="thumbnail_grid_frame" href="'+tgHref+'"><span style="display: block;width: 160px;height: 120px;background-image: url('+tgImgSrc+');">asdf</span></a>');
                    }
                }
                // add first-in-row and last-in-row classes based on allowed thumbnail grid items per row
                if (indexLi % tgPerRow === 0) {
                    $(this).addClass("tg_fir");
                }
                if (indexLi % tgPerRow === (tgPerRow - 1)) {
                    $(this).addClass("tg_lir");
                }
            });
            $(this).children("li.tg_lir").after("<li class=\"clear\">&nbsp;</li>");
        });
    });
    $("#content_mainA a.thumbnail_grid_frame").hover(
        //in
        function () {
            $(this).next("a").next("p").children("a").addClass("pretty_underline");
        }, 
        //out
        function () {
            $(this).next("a").next("p").children("a").removeClass("pretty_underline");
        }
    );
    $("#content .related_group li > a").hover(
        //in
        function () {
            $(this).next("p").children("a").addClass("pretty_underline");
        }, 
        //out
        function () {
            $(this).next("p").children("a").removeClass("pretty_underline");
        }
    );
}

// take the primary photo of article pages and give it the same styling as single_tease_dl
function prettyArticleImg(imgWidth,imgHeight,articleType) {
    var dressCaptions,
        primaryPhotoDiv,
        ppCaption,
        padTheTop,
        captionHeight;
    if (articleType === "article") {
        // container for photo and caption is .primary photo
        primaryPhotoDiv = $("#content_mainA .subsection .primary_photo");
        if (primaryPhotoDiv.children("p.credit").size() > 0 && primaryPhotoDiv.children("div.caption").size() === 0) {
            primaryPhotoDiv.children("p.credit").wrap("<div class=\"caption\" />");
            dressCaptions = false;
        }
        else {
            dressCaptions = true;
        }
        if (primaryPhotoDiv.children("div.caption").size() > 0) {
            ppCaption = primaryPhotoDiv.children("div.caption");
            primaryPhotoDiv.parent(".subsection").css({"float":"left"});
        }
        // account for drop shadow and 18px gutters
        primaryPhotoDiv.parent(".subsection").next(".subsection").css("padding-top",13);
    }
    if (articleType === "openhtml") {
        $($("#article_cream_wrap img")[0]).wrap("<div class=\"primary_photo\" />");
        primaryPhotoDiv = $("#article_cream_wrap .primary_photo");
    }
    if (imgWidth === 600) {
        padTheTop = 23;
        primaryPhotoDiv.addClass("pp_600 pp_mod");
    }
    if (imgWidth === 470) {
        padTheTop = 25;
        primaryPhotoDiv.addClass("pp_470 pp_mod");
    }
    if (imgWidth === 270) {
        padTheTop = 23;
        primaryPhotoDiv.addClass("pp_270 pp_mod");
    }
    
    if (articleType === "article" && primaryPhotoDiv.children("div.big_image").size() > 0) {
        // do nothing
    }
    else {
        if(primaryPhotoDiv.hasClass("pp_mod")) {
            // split primary_photo into two containers - one holding the image, the other is div.caption
            primaryPhotoDiv.children("img").wrap("<div class=\"pp_container_img\" />");
            $(".pp_container_img").prepend("<div><div>&nbsp;</div></div>");
            $(".pp_container_img > div div").css("height",imgHeight);
            $(".pp_container_img").css("min-height",imgHeight + padTheTop);
            if (articleType === "article") {
                if (ppCaption.children("p").size() === 0 && dressCaptions === true) {
                    ppCaption.wrapInner("<p />");
                }
                if (dressCaptions === true) {
                    // pull the credit text into the .caption container
                    ppCaption.append("<p class=\"credit\">"+primaryPhotoDiv.children("p.credit").html()+"</p>");
                    ppCaption.next("p.credit").hide();
                    // 5 because the image container is absolutely top: -5px;
                    ppCaption.css("top",imgHeight + padTheTop - 5);
                }
            }
            if (articleType === "openhtml") {
                $(".pp_container_img").after("<div class=\"caption\">&nbsp;</div>");
                $("#article_cream_wrap div.caption").css({
                    "height":padTheTop + 5,
                    "top":imgHeight + padTheTop - 5,
                    "padding-top":0,
                    "padding-bottom":0
                });
            }

            // adjust .primary_photo to account for absolute positioning
            captionHeight = primaryPhotoDiv.children("div.caption").outerHeight(true);
            primaryPhotoDiv.css({
                "min-height":imgHeight + captionHeight + padTheTop
            });    
        }
    }    
}

function SendLink(url) {
    // ignore url (legacy code) and use current location instead
    var new_url = window.location;
    window.open("/kids/sendlink/?url=" + new_url,"","height=335,width=440,location=no,menubar=no,resizable=no,status=no,toolbar=no");
}

function videoPlayer(url){
    window.location = url;
}
// removes the <center> tag out of legacy openHTML items.
function removeCenter() {
    $("#article_cream_wrap center").each(function() {
        $(this).wrapInner("<div class=\"remove_center\" />");
        $(".remove_center").css("margin-top",10);
        $(".remove_center td").removeAttr("align");
        $(this).children(".remove_center").unwrap();
    });
}

function getIntlStatus() {
    var intlStat = false;
    var h_name = window.location.host.toString();
    if(h_name.substr(h_name.length-3) == ".uk"){
        intlStat = true;
    }
    
    return intlStat;
}

