/*
This is our main CSS file where most of the page functionality is set:
    - this code requires the following jQuery plug-ins:
        - jQuery (1.3.2)
        - swfObject (2.2)
        - jquery.easing
        - jquery.scrollTo
        - jquery.tabs
*/

var contentBlocks;
var blockOffsets = [];
var contentWrapper;
var content;
var dayChangerColorElems;
var copiedYtPlayer;

jQuery(document.documentElement).addClass("js");

/*
swfobject.createCSS("div#the-space","background-image:url(/assets/images/HubBGs/Space_Hub_Loader.png)");
swfobject.createCSS("div#dinner","background-image:url(/assets/images/HubBGs/Dinner_Hub_Loader.png)");
swfobject.createCSS("div#tours","background-image:url(/assets/images/HubBGs/Tours_Hub_Loader.png)");
swfobject.createCSS("div#lunch","background-image:url(/assets/images/HubBGs/Lunch_Hub_Loader.png)");
swfobject.createCSS("div#workshops","background-image:url(/assets/images/HubBGs/Workshops_Hub_Loader.png)");
swfobject.createCSS("div#whats-on","background-image:url(/assets/images/HubBGs/WhatsOn_Hub_Loader.png)");
*/

jQuery(document).ready(function()
{
    /* 
    EMERGENCY FIX - 12/6/09
        - so all the nested forms were causing failure in IE as it didn't know which viewstate to use
        - so on click of all initial submit buttons input[type="submit"] we delete the contents of .viewstate(s)
        - any more info please Ask Fab
    */
    jQuery('input[type="submit"]').each(function() {
        jQuery(this).click(function() {
            jQuery('.view_state div').remove();
        });
    });
    
    //add booking information	
	jQuery('#showBooking').click(function(){
	    jQuery('#booking_summary').addClass('postit');
	    jQuery('#booking_information').removeClass('postit');
	    return false;	    
	});
	
	jQuery('#closeBooking').click(function(){
	    jQuery('#booking_summary').removeClass('postit');
	    jQuery('#booking_information').addClass('postit');
	    return false;	    
	});
	
    /* creating references to standard objects */
	var nav = jQuery("#navigation")
	var navMenu = nav.find("ul");
	contentWrapper = jQuery("div#contentWrapper");
	var content = jQuery("div#content");
	contentBlocks = jQuery(".contentBlock");
	var navItems = nav.find("li a");
	
	dayChangerColorElems = jQuery("div#day-navigation p a.active, div#day-navigation p.dateSelect .submitDay, div#day-navigation p.dateSelect a.help")
	
	var index = false;
	
	// this link needs to act differently to others in the mainnav
	jQuery('.promoLinks a').attr('target','_blank');

	function getLocationIndex()
	{
		var scrollTop = contentWrapper[0].scrollTop;
		
		var newIndex = 0;
		var screenY = jQuery(window).height();
		
		for(var i = 0; i < blockOffsets.length; i++)
		{
			if((blockOffsets[i].offset - (screenY / 2)) > scrollTop)
			{
				newIndex = i - 1;
				break;
			}
			
			newIndex = i ;
		}
		
		return newIndex;
	}
	navItems.add("div.hubNav>ul>li>a[href*='#'], #content ul.homeNav li a[href*='#']").click(function(evt)
	{
		var navItem = jQuery(this);
		if (!navItem.parent().hasClass('.promoLinks')) {
		    evt.preventDefault();
		    // some links don't have hrefs but have names - this allows for both :)
		    var hashID = navItem.attr("href") ? navItem.attr("href").split("#")[1] : navItem.attr("name");

		    // google analytics page count stuff
		    var lang = "en";
		    if(typeof pageTracker._trackPageview === "function") {
				lang = getLanguage();
				var analytics = hashID == 'home' ? '/home' : '/' + lang + '/section/' + hashID.replace(/-/,'_');
				pageTracker._trackPageview(analytics);
			}
		    		
		    var target = contentWrapper.find("a[name='" + hashID + "']").parents("div.contentBlock");
		
		    var fromIndex = getLocationIndex();
		    var toIndex = navItem.parents("li").prevAll().size();
		
		    var diff = fromIndex - toIndex;
		
		    if(diff < 0)
			    diff = 0 - diff;
		
		    diff = ((diff - 1) / 2) + 1;
		
		    contentWrapper.scrollTo(target, (1000 * diff), {easing:'easeOutCirc'});
		    
		}
	});
	
	// when the window resizes we position the dayNav appropriatly
	jQuery(window).resize(function()
	{
	    // dirty layout trick for perfect alignment of day nav bar
	    if(jQuery('#generic').length === 0) {
	        //jQuery("div#day-navigation>div").css("margin-left", (jQuery("#content").offset().left + (1024 - 638)));
	    } else {
	        //jQuery("div#day-navigation>div").css("margin-left", (jQuery("#content").offset().left + (1024 - 485)));
	    }
	    
        jQuery('#day-navigation').width(jQuery('#contentWrapper').width() - $.getScrollbarWidth());
	});
	
	// ensuring proper position of dayNav on load
	jQuery(window).resize();
	
	// as the page scroll the colour of inputs/links in the daynav change
	var oldIndex = false;
	
	contentWrapper.scroll(function()
	{
		var color = "#666";
		var block;
		var index = getLocationIndex();
		
		
		if(index !== oldIndex)
		{
		    
		    try
		    {
       	        dayChangerColorElems.css("background-color", blockOffsets[index].color);
       	        oldIndex = index;
       	    }
       	    catch(e) {}
       	}
	});
	
	// animation for the faux drop-down in day nav
	jQuery('#follow').hide();
  
    jQuery('a#follow-show').mouseenter(function()
    {
        jQuery('li#follow').slideDown('medium');  
    });
   
    jQuery('a#follow-show').parents("ul").eq(0).mouseleave(function()
    {
        jQuery('li#follow').slideUp('medium');
    });    
    
    // when hovering over the mouse ALL links should be the checked pattern, not bold (that's the rollover)
	jQuery('ul.homeNav').mouseenter(function()
	{
	    jQuery(this).addClass('active');
	});
	
	jQuery('ul.homeNav').mouseleave(function()
	{
	    jQuery(this).removeClass('active');
	});
	
	// code for partners page only
	if (jQuery('#partnersInfo').length != 0){
	    var partner_links = jQuery('#partnersInfo li');
	    partner_links.find('a').each(function() {
	        jQuery(this).append("<span class='gauze'></span>");
	    });
	    partner_links.hover(
	        function() {
	            jQuery(this).find('.gauze').css('display','block');
	        },
	        function() {
	            jQuery(this).find('.gauze').css('display','none');
	        }
	    );
	    partner_links.click(function() {
	        var that = jQuery(this);
	        var parent_html = that.html();
	        jQuery('#partnerDesciption').html(parent_html);
	        return false;
	    });
	}
	
	// code for booking stage 2 only
	if (jQuery('#billingAddress').length != 0) {
	    //Hide div w/id extra but only if it's suposed to be hidden, ie not when showing errors!
        if ($('.yes:checked').length === 1) {
            $("#billingAddress").hide();
        }    

    // Add onclick handler to checkbox w/id checkme
   $(".no").click(function(){

        // If checked

        if ($(".no").is(":checked"))

        {

            //show the hidden div

            $("#billingAddress").show();

        }

        else

        {     

            //otherwise, hide it

            $("#billingAddress").hide();

        }

    });

    $(".yes").click(function(){

        $("#billingAddress").hide();

    })
	}
	 
    hubInit(jQuery("div#content"));
	
	// if on the home page, open footer links in new window
	jQuery("#footer ul li a").click(function(evt) {
	    if (jQuery("div#generic").size() == 0) {	        
	        jQuery(this).attr("target","_blank");
	    } 
	});
	
	/* this is a dirty hack version of what comes below */
	jQuery('.btn_whatson').click(function() {
	    if (jQuery('.disclaimer input:checked').length == 0) {
	        jQuery('.disclaimer').addClass('error');
	        return false;
	    }
	});
	
	jQuery('.funkybox p.disclaimer').each(function() {
	    var that = jQuery(this);
	    var btn_submit = that.parents('.funkybox').find('.button');
	    btn_submit.click(function() {
	        if (that.find('input:checked').length == 0) {
	            that.addClass('error');
	            return false;
	        }
	    });
	});
	
	
});

/*
 * Separated out hub specific init stuff so we can init for sub navigation
 */
function hubInit(hubElem)
{
    try
    {
        hubElem.find("div.ytPlayer").ytPlayer();
    }
    catch(e) {}

    try
    {
        lightboxes();
    }
    catch(e) {}
    
    try
    {
        hubElem.find('.js_tabs').accessibleTabs({fx:'fadeIn', fxspeed:0});
    }
    catch(e) {}
    
    // OK - this is dirty as the river Frome but it should work
    if (hubElem.find('p.close').length != 0) {
        // we know we are in a lightbox and can call the function without erroring
        try {
            electrolux.paginate_tabs.create_links('.overlayBody .paginate_me');
        }
        catch(e) {}
    } 

    /* CODE TO CLEAR TEXT BOXES */

    hubElem.find("input.text").click(function()
    {
        var input = jQuery(this);
    
        if(input[0].defaultValue == input.val())
        {
            input.val("");
        }
    });
    
    hubElem.find("input.text").blur(function()
    {
        var input = jQuery(this);
    
        if("" == input.val())
        {
            input.val(input[0].defaultValue);
        }
    });
    
    hubElem.find("div.resourceGrid ul li").mouseover(function()
    {
        if (jQuery(this).hasClass("youtube")) {
            jQuery(this).find("div.imageMask span").text(translations.lightbox.play);
            jQuery(this).find("span.imageMask span").text(translations.lightbox.play);
            jQuery(this).find("span.action span").hide();
        } else {
            jQuery(this).find("div.imageMask span").text(translations.lightbox.viewShort);
            jQuery(this).find("div.imageMask span").show();
            jQuery(this).find("span.imageMask span").text(translations.lightbox.viewShort);
            jQuery(this).find("span.imageMask span").show();
        }
        
    });
    
    hubElem.find("div.resourceGrid ul li").mouseout(function()
    {
        if (jQuery(this).hasClass("youtube")) {
            jQuery(this).find("div.imageMask span").text("");
            jQuery(this).find("span.imageMask span").text("");
            jQuery(this).find("span.action span").show();
        } else {
            jQuery(this).find("div.imageMask span").text("");
            jQuery(this).find("div.imageMask span").hide();
            jQuery(this).find("span.imageMask span").text("");
            jQuery(this).find("span.imageMask span").hide();
        }
    });
    
    hubElem.find("div.resourceGrid ul li").click(function(evt)
    {
        if(typeof(evt.originalTarget) != "undefined")
        {
            evt.preventDefault();
            jQuery(this).find("a").click();
        }
    });
}

// preloading background images - then rendering on page as an inline style
jQuery(window).load(function()
{
    var imageCache = Array();

    var i = 0;

    var top = jQuery("#content").offset().top;

    contentBlocks.each(function(i)
    {
        var block = jQuery(this);

		var color = "#FF9C00";
		var tweet;

		if((tweet = contentBlocks.eq(i).find("div.tweet div")).size())
		{
		   color = tweet.css("background-color");
		}

		blockOffsets.push(
		    {
		        'offset':(block.offset().top - top),
		        'color':color
		    });
	    
        //console.log(typeof(backgrounds));

        if(typeof(backgrounds) != "undefined")
        {

            //console.log(backgrounds[block.attr("id")]);

            var background = backgrounds[block.attr("id")];
            
            if(background != undefined)
            { 
                imageCache[i] = jQuery("<img />");  

                imageCache[i].load(function()  
                {  
                    block.css("background-image", "url(" + jQuery(this).attr("src") + ")");
                });  
                
                //console.log(background['background-image']);
                
                imageCache[i].attr("src", background['background-image']);
            
                i++;
            }
        }
    });
    
    //blockOffsets.push({top: 99999, color:'#ECC31E'});
    
    
    contentWrapper.scroll();

});
/*! Copyright (c) 2008 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 */

/**
 * Gets the width of the OS scrollbar
 */
(function($) {
	var scrollbarWidth = 0;
	$.getScrollbarWidth = function() {
		if ( !scrollbarWidth ) {
			if ( $.browser.msie ) {
				var $textarea1 = $('<textarea cols="10" rows="2"></textarea>')
						.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'),
					$textarea2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>')
						.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body');
				scrollbarWidth = $textarea1.width() - $textarea2.width();
				$textarea1.add($textarea2).remove();
			} else {
				var $div = $('<div />')
					.css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: -1000 })
					.prependTo('body').append('<div />').find('div')
						.css({ width: '100%', height: 200 });
				scrollbarWidth = 100 - $div.width();
				$div.parent().remove();
			}
		}
		return scrollbarWidth;
	};
})(jQuery);