// Set visibility of selects to hidden until they're styled
$(function() {
    $('#searchResultsFilter select, #searchResults select').css({visibility: 'hidden'});
});

/* Prevent headers from wrapping by shrinking the font depending on the character length */

/** two line W220 footer link issue **/
function W220footer() {
	$('.w220').each(function () {
			var new_length = $.trim($('.footerLink .titlelink', this).html()).length;
			if(new_length < 29) {$('.content', this).css({'paddingBottom' : '26px'});} 
			else if(new_length > 29 && new_length < 55) {$('.content', this).css({'paddingBottom' : '39px'});} 
			else {$('.content', this).css({'paddingBottom' : '53px'});}
	});
}

function faq_slide() {
	$(".faq-answer").hide();   
	$(".faqshowAll").toggle(function() {
		$(".faq-answer").slideDown(); 
		$('a span',this).html('Hide All Answers');
		$('img',this).attr('src','/site_assets/images/btn_up.png');
	}, function() {
		$(".faq-answer").slideUp();
		$('a span',this).html('Show All Answers');
		$('img',this).attr('src','/site_assets/images/btn_down.png');
	});
   
	$("a[name^='faq_']").live('click',function() {
		if($("#" + this.name).is(':hidden')){$("#" + this.name).slideDown('fast');}
		else{$("#" + this.name).slideUp('fast');}			
		return false;
	});
}

// for the container_bottomBar blocks - if content editor adds too much
// text the fixed height of the blocks causes problems means that the text
// is overlayed on top of the bottom block link. We could fix all this with
// CSS if IE took notice of min-height
//
// As it is we fix it by finding the tallest block and set all blocks to
//match its height
function bottomBlocksLineUp() {
	var container_bottomBarHeight = 0;
	$('#container_bottomBar .content').css('height','auto').each( function (i) { 
																			
		var contentHeight = $(this).outerHeight(true);
		if(contentHeight>container_bottomBarHeight){
				container_bottomBarHeight = contentHeight;
		}else{
			false;
		}
		
	})
	$('#container_bottomBar .content').each( function (i) { 
		var cssPadding = parseInt($(this).css('paddingBottom').split('px', 1));
		var cssPaddingTop = parseInt($(this).css('paddingTop').split('px', 1));		
		var newHeight = (container_bottomBarHeight - (cssPadding+cssPaddingTop));
		$(this).css('height', newHeight + 'px');
	})
	// Added to fix IE6 float drop issue - LE
	$('.ie6 #container_bottomBar .w220float:last-child').css({marginRight: '0'});
}

// Load Facebook
function loadAndEnableFacebook() {
    if ($.browser.msie) {
        return; // see: http://developers.facebook.com/docs/reference/plugins/login (doesn't display in IE either)
    }
    var fbElems = $('.facebook'); // only do the connect if we are on a page with the facebook button
    if (fbElems.length != 0) {
        // this to fix a FB IE issue when 'lazy loading' FB script
        /* if ($.browser.msie && $("#FB_HiddenContainer").length == 0) {
            $("body").append("<div id=\"FB_HiddenContainer\" style=\"position: absolute; top: -10000px; width: 0px; height: 0px;\"><div>");
        } */
        // dynamically load script with callback function to call when loaded
        $.getScript("http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php", 
            function() { 
               if (typeof(FB_RequireFeatures) != "undefined") {
                  FB_RequireFeatures(['XFBML', 'Connect'], function() {
                      FB.init("8d9111749d3c4d7164f1a419f80a46d1", "/Common/xd_receiver.htm", { permsToRequestOnConnect: "email" }); 
                    FB.ensureInit( function(){  // the callback will only get called when FB has initialized
                        $(fbElems).show();
                        /* if ($.browser.msie) {
                            // check FB done its 'magic' to enable button before showing it
                            $(fbElems).each( function(idx) {
                                    setTimeout( function() { 
                                        if ($('a',fbElems[idx]).length > 0) $(fbElems[idx]).show();
                                    }, 250);
                                }
                            );
                        } else {
                            $(fbElems).show();
                        } */
                    } );
                  });
               }
            } 
        );
    }
}

//Enable Facebook Connect 
function enableFacebook() {
      /* if(typeof(FB_RequireFeatures) != "undefined"){
         $.get('/common/FacebookApiKey.aspx', function(apikey) {
		    FB_RequireFeatures(['XFBML','Connect'],function() {FB.init($.trim(apikey), "/Common/xd_receiver.htm", {permsToRequestOnConnect : "email"});})
		    $(function(){$('.facebook').show();});
         });
       } */
       if (typeof(FB_RequireFeatures) != "undefined") {
          FB_RequireFeatures(['XFBML', 'Connect'], function() { 
            FB.init("72b3df8795afebbe99e7eb0834d6659b", "/Common/xd_receiver.htm", { permsToRequestOnConnect: "email" }); 
            FB.ensureInit( function(){  // the callback will only get called when FB has initialized
                fbElems.show();
            } );
          });
       }
}

/* add to bag transition */
function addedtobag() {
	$(function () {
		$(".btn_addtocart").switchClass('btn_addtocart', 'btn_blue');
		$('.btn_addtocart input').val('Added');
		setTimeout(function () {
				$(".btn_blue").switchClass('btn_blue', 'btn_addtocart');
				$('.btn_blue input').val('Add to Cart');
		}, 2000);
	});
}
//Search Select JS in Menu Bar

function GetRadioButtonValue(id){
	var radio = document.getElementsByName(id);
	for (var ii = 0; ii < radio.length; ii++){}
}

function DisplayDiv(id){            
	var a=document.getElementById(id);
	if(a.className=="divInvisible"){a.className="divVisible";}else{a.className="divInvisible";}
	return false;
}

function Focus(objname, waterMarkText, cssClass) {
	obj = document.getElementById(objname);
	if (obj.value == waterMarkText) {
		obj.value = "";
		obj.className = "NormalTextBox";
		if (obj.value == "Search Resources" || obj.value == "" || obj.value == null) {}
	}
}

function Blur(objname, waterMarkText, cssClass, SetValue) {
	obj = document.getElementById(objname);
	if(obj.value==""){obj.value = SetValue;obj.className = cssClass;}else{obj.className = "NormalTextBox";}
	if(obj.value==SetValue||obj.value==""||obj.value == null) {}
}

// SC: 2010-10-28 - Cookie Helper Functions
function GetCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            var endstr = document.cookie.indexOf(";", j);
            if (endstr == -1) {
                endstr = document.cookie.length;
            }
            return unescape(document.cookie.substring(j, endstr));
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}
function SetCookie(name, value) {  // additional args: expires (ms), path, domain, secure
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    document.cookie = name + "=" + escape(value) +
	((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == true) ? "; secure" : "");
}
function DeleteCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = GetCookie(name);
    if (cval == null) cval = "";
    document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
function CookiesEnabled() {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false
    //if not IE4+ nor NS6+
    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
        document.cookie = "cookieEnabled"
        cookieEnabled = (document.cookie.indexOf("cookieEnabled") != -1) ? true : false
    }
    return cookieEnabled;
}

// SC: 2010-10-18 - Popup Survey (Updated)
/*
$(document).ready(function () {
    // use this to quickly switch this functionality off
    if (false) return;
    // only do this if cookies enabled, otherwise will keep getting popup
    if (!CookiesEnabled()) return;
    // CookieName to check
    var cookieName = "PlanetSurvey201110";
    // number of days the cookie should persist
    var expDays = 30;
    // URL to the pop-up
    var popupUrl = "http://surveys.automatesurvey.com/s?p=W10003282508S91&h=2223567";
    // Popup Window Name
    var popupName = "PlanetSurvey2011";
    // popup window properties
    var popupProps = "width=600,height=600,location=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes";
    // array of Url paths to execute popup on - make sure these are lowercase
    var aUrlPaths = new Array(
        "/en/",
        "/en-us/",
        "/en-gb/",
        "/en/resources/",
        "/en-us/resources/",
        "/en-gb/resources/",
        "/en/search/resources/",
        "/en-us/search/resources/",
        "/en/search/resources/resource-type--lesson",
        "/en/store/",
        "/en/support/software/activinspire/",
        "/en/professional-development/activtips/",
        "/en/professional-development/activlearning/free-courses/",
        "/en/Support/Support.aspx",
        "/en-us/Support/Support.aspx",
        "/en-gb/Support/Support.aspx"
    );
    // functionality ... 
    var siteUrl = document.location.protocol + "//" + document.domain;
    var currUrl = document.URL.toLowerCase();
    var currPath = currUrl.substring(siteUrl.length);
    var cookieDomain;
    if (document.domain.indexOf("prometheanplanet.com") != -1) {
        cookieDomain = ".prometheanplanet.com";
    } else if (document.domain.indexOf("prometheanworld.com") != -1) {
        cookieDomain = ".prometheanworld.com";
    } else {
        cookieDomain = document.domain;
    }
    var cookiePath = "/";
    for (var idx in aUrlPaths) {
        if (aUrlPaths[idx] == currPath) {
            var exp = new Date();
            exp.setTime(exp.getTime() + (expDays * 24 * 60 * 60 * 1000));
            var count = GetCookie(cookieName);
            if (count == null) {
                // only set the cookie if the popup successfully opened
                // timeout for Chromes benefit as it says the window is open even if it blocks it
                // still doesn't fix Chrome (or Opera)
                var win = window.open(popupUrl, popupName, popupProps);
                window.setTimeout(function () {
                    if (!win || win.closed || typeof win.closed == 'undefined') {
                        // poup blocked
                    }
                    else {
                        SetCookie(cookieName, 1, exp, cookiePath, cookieDomain);
                    }
                },
                1000);
            }
            else {
                count = parseInt(count);
                if (isNaN(count)) { count = 0; }
                SetCookie(cookieName, ++count, exp, cookiePath, cookieDomain);
            }
            break;
        }
    }
});
*/


// hereon is code that will run after DOM is loaded

$(document).ready(function(){
    // Tooltip for search results
    $(".ResourceTitle").mouseenter(function () {
      $(this).parents('li').find(".moreInfo").fadeIn("slow");
        });

    $(".ResourceTitle").mouseleave(function () {
      $(this).parents('li').find(".moreInfo").fadeOut("slow");
        });
        
    $(".PremiumResourceTitle").mouseenter(function () {
      $(this).parents('li').find(".moreInfo").fadeIn("slow");
        });

    $(".PremiumResourceTitle").mouseleave(function () {
      $(this).parents('li').find(".moreInfo").fadeOut("slow");
        });  
    try{
    // Homepage footer blocks last block  
    $('.hb_blocks').last().css('margin-right', '0');    
     }catch(Error){}
    // Load and Enable facebook
    loadAndEnableFacebook();
});


$(document).ready(function() {

    // login form home page
    // var loginFormHomePagePfx = 'ctl00_cphMainPanel_ucLoginFormHomePage1_'; // test
    var loginFormHomePagePfx = 'ucLoginFormHomePage1_';
    $('#' + loginFormHomePagePfx + 'logout_content').each(function() {
        // username
        $(this).find('#' + loginFormHomePagePfx + 'textboxUserID').each(function() {
            $(this).val($(this).attr('title'));
            $(this).focus(function() {
                if ($(this).val() == $(this).attr('title'))
                    $(this).val('');
            });
        });
        // password
        $(this).find('#' + loginFormHomePagePfx + 'textboxPassword').each(function(i) {
            $(this).hide();
            var pwdElem = this;            
            $(pwdElem).after(
                $(document.createElement('input'))
                    .attr( { id : 'temp_pass_' + i, type : 'text' } )
                    .val( $(this).attr('title') )
                    .focus(function() {
                        $(this).hide();
                        $(pwdElem).show().focus();                
                    })
            );
        });
    });
    
    /*
    // Need JS localisation provider writing (API ajax call?)
    $("#ucLoginFormHomePage1_textboxUserID").val('Username or Email').focus(function() {
        $(this).val('');
    });

    $("#ucLoginFormHomePage1_textboxPassword").hide();
    var new_input = document.createElement("input");
    new_input.setAttribute("id", "temp_pass");
    new_input.setAttribute("type", "text");
    
    // Need JS localisation provider writing (API ajax call?)
    new_input.value = "Password";
    $("#ucLoginFormHomePage1_textboxPassword").after(new_input);
    $(new_input).focus(function() {
        $(this).hide();
        $("#ucLoginFormHomePage1_textboxPassword").show();
    });
    */

    setTimeout(function() {
        W220footer();
        bottomBlocksLineUp();
        faq_slide();
        $('.tab_text li:first').show();
    }, 2000);

    function makeVisible() {
        $(this).parent().children("li").find("div:first").hide();
        if ($.browser.msie) {
            $("div:first", this).show();
        } else {
            $("div:first", this).fadeIn('slow');
        }
    }

    function makeInvisible() {
        if ($.browser.msie) {
            $("div:first", this).hide();
        } else {
            $("div:first", this).fadeOut();
        }
    }

    $("#mainNav #menu ul li[class='navigation-item']").each(function() {
        $("div:first", this).hide();
        if ($.browser.msie) {
            $("div:first", this).css("left", "auto");
        }
        $("div div", this).css("display", "block");
    });

    var config = { sensitivity: 3, interval: 200, over: makeVisible, timeout: 500, out: makeInvisible };
    $("#mainNav #menu ul li[class='navigation-item']").hoverIntent(config);

    /*  
    IE shows hidden containers when hitting enter on a input field. to prevent this the following code 
    disables the enter keystroke. placing an attribute called 'submitbuttonclass' with the value of the submit 
    button class, this will submit the input on enter instead of doing the default method
    */

    $('input').bind('keypress', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            if ($(this).attr('submitbuttonclass')) {
                $('.' + $(this).attr('submitbuttonclass')).trigger('click');
            }
            return false;
        }
    });

    setTimeout(function() {
        if ($('.searchFiltersCol').size() == 1) { $('.searchFiltersCol input').each(function() { $(this).attr('submitbuttonclass', 'searchfilterbtn'); }); }
    }, 2000);

    //Top Bar Slide Down Panels
    $("#page-container .login  a:first").click(function(e) { $('.topBarPanel:not(div#signin_menu)').slideUp(100); e.preventDefault(); $("div#signin_menu").slideToggle(); $(this).toggleClass("selected"); });
    $(".countrySelect a:first").click(function (e) {
        e.preventDefault();
        $('.topBarPanel:not(div#countryMenu)').slideUp(100);
        setCustomiseDisplay(); // Added to hide customise button on community if menu open to prevent overlap
        $("div#countryMenu").slideToggle();
        $(this).toggleClass("selected");
    });
    $(".loginClose").click(function(e) { $("div#signin_menu").slideUp(); });
    $(".countryClose").click(function(e) { $("div#countryMenu").slideUp(); });

    // Hide customise button in community when language dropdown visible
    function setCustomiseDisplay() {
        if ($('#countryMenu').is(':visible')) {
            $('.site-banner .internal-link.edit-page').hide();
        } else {
            $('.site-banner .internal-link.edit-page').show();
        }
    }

    // Remove nojs class for menu
    $("*").removeClass("nojs");


    $("#footer ul li:last").addClass("lastFooter");
});


/****************************************************/
/* Add IE classes to community server to fix header */
/****************************************************/

$(document).ready(function () {
    var isCommunity = $('.header-fragments');
    if ($.browser.msie && parseFloat($.browser.version) == 6 && isCommunity) {
        $('body').addClass('ie6');
    }
    if ($.browser.msie && parseFloat($.browser.version) == 7 && isCommunity) {
        $('body').addClass('ie7');
    }
    // If ie8 is in ie7 mode
    // && isCommunity - Removed to fix planet site
    if (document.documentMode && document.documentMode == 7) {
        $('body').addClass('ie7');
    }
});



/*******************************/
/* Header Search Bar Functions */
/*******************************/

$(document).ready(function() {
    
    // Remove label value when clicked
    $(function() {
        var defaultValue = $('.headerSearchField').attr('initialtext');
        
        $('.headerSearchField:text, .SearchKeywordsInput:text').focus(function() {
            var newValue = $(this).val();
            if ($(this).val() == defaultValue) {
                $(this).attr('value','');
            } else {
                $(this).val(newValue);
            }            
        });
        
        $('.headerSearchField:text, .SearchKeywordsInput:text').blur(function() {
            var newValue = $(this).val();
            if ($(this).val() == '') {
                $(this).attr('value',defaultValue);
            } else {
                $(this).val(newValue);
            }
        });
    });
    
    // Hide dropdowns as default
	$('.headerDropdown').hide();

	// Apply click function to show
	$('.headerDropdownBtn').click(function() {
	    if ($(this).parent().find('.headerDropdown').is(':hidden')) {
		    $(this).parent().find('.headerDropdown').slideDown(300);
		    $(this).css({backgroundPosition: '-63px -963px'});
		} else {
		    $(this).parent().find('.headerDropdown').slideUp(300);
		    $(this).css({backgroundPosition: '-25px -963px'});
		}
	});

	// If option is selected on favourite search dropdown, automatically close
	$('#headerFavSearch .headerDropdown').click(function() {
		$(this).parents('#headerFavSearch').find('.headerDropdown').slideUp(300);
		$(this).css({backgroundPosition: '-25px -963px'});
	});

	

	// Close again once search button clicked
	$('#headerSimpleSearch .searchBtn').click(function() {
	    if ($(this).parent().find('.headerDropdown').is(':visible')) {
		    $(this).parent().find('.headerDropdown').slideUp(300);
		    $(this).css({backgroundPosition: '-25px -963px'});
		}
	});
	
	// Fix z-index bug
	$(function() {
	    var zIndexNumber = 699;
	    $('#headerSearch div').each(function() {
		    $(this).css('zIndex', zIndexNumber);
		    zIndexNumber -= 1;
	    });
	});

});

/***********************************/
/* Advanced Search Functions - NEW */
/***********************************/
$(function () {

    var resourceContainsDiv = '#advancedSearch li.FileFormatResourceContents div.content div.rightColumn';

    // Open
    $('#headerSearch .advSearch').bind('click', function (e) {
        $('#advancedSearchOverlay').fadeTo(500, 0.7);
        $('#advancedSearch').fadeIn(500);
        e.preventDefault();
    });
    // Close
    $('#advancedSearchCloseBtn').bind('click', function (e) {
        $('#advancedSearchOverlay, #advancedSearch').fadeOut(500);
        e.preventDefault();
    });
    $('#advancedSearchOverlay').live('click', function (e) {
        $('#advancedSearchOverlay, #advancedSearch').fadeOut(500);
    });
    $(document).bind('keyup', function (e) {
        e.preventDefault();
        if (e.which == 27) {
            $('#advancedSearchOverlay, #advancedSearch').fadeOut(500);
        }
    });
    loadSearch();
    resourceContains(resourceContainsDiv);
    $(resourceContainsDiv).hide();
});

// Show/Hide resource contains div
function resourceContains(resourceContainsDiv) {
    // Use hidden input value for ids to check
    var ids = $('#hidDisplayResourceContains').val().split(','),
        chkIds;

    $.each(ids, function (i, val) {
        ids[i] = '#' + val;
    });

    chkIds = String(ids);

    $(chkIds).bind('click', function () {
        var self = $(this),
            checked = self.is(':checked'),
            othersChecked = $(chkIds).not(self).is(':checked');
        if (checked) {
            $(resourceContainsDiv).show();
        } else {
            if (!othersChecked) {
                var checkboxes = $(resourceContainsDiv).find(':checkbox');
                checkboxes.each(function () {
                    $(this).attr('checked', false);
                });
                $(resourceContainsDiv).hide();
            }
        }
    });
}

function loadSearch() {
    var mask,
		maskH,
		maskW,
		windowH = $(window).height(),
        windowW = $(window).width(),
		adSearchH = $('#advancedSearch').outerHeight(),
		posTop = (windowH - adSearchH) / 2;
    $('<div id="advancedSearchOverlay"/>').insertBefore('#advancedSearch');
    mask = $('#advancedSearchOverlay');
    maskH = ($('#page-container').hasClass('ie6') || $('.site-banner').hasClass('ie6')) ? $(document).height() + 20 : windowH; //
    maskW = windowW;

    if ($('body').hasClass('ie6')) {
        $('#advancedSearchOverlay').css({ 'z-index': '949', 'top': 0, 'left': '50%', 'margin-left': -(maskW / 2), 'height': maskH, 'width': maskW, 'opacity': 1 });
        $('#advancedSearch').css({ 'z-index': '999', 'top': '20px', 'display': 'none' });
    } else {
        $('#advancedSearchOverlay').css({ 'z-index': '949', 'top': 0, 'left': '50%', 'margin-left': -(maskW / 2), 'height': maskH, 'width': maskW, 'opacity': 1 });
        $('#advancedSearch').css({ 'z-index': '999', 'top': posTop, 'display': 'none' });
    }
    advancedSearchSlider();
    advancedSearchTooltips();

    // Centre advanced search in window
    $(window).resize(function () {
        if ($('#advancedSearch').css('top') != '0') {
            var windowH = $(window).height(),
            windowW = $(window).width(),
			adSearchH = $('#advancedSearch').outerHeight(),
			posTop = (windowH - adSearchH) / 2,
			maskH = ($('#page-container').hasClass('ie6') || $('.site-banner').hasClass('ie6')) ? $(document).height() + 20 : windowH,
            maskW = windowW;
            $('#advancedSearchOverlay').css({ 'z-index': '949', 'height': maskH, 'width': maskW, 'top': 0, 'left': '50%', 'margin-left': -(maskW / 2) });
            //$('#advancedSearch').css({ 'z-index': '999', 'top': posTop });
            if ($('body').hasClass('ie6')) {
                $('#advancedSearch').css({ 'z-index': '999', 'top': '20px' });
            } else {
                $('#advancedSearch').css({ 'z-index': '999', 'top': posTop });
            }
        }
    });
}

function advancedSearchTooltips() {
    $('#advancedSearch [data-tooltip]').each(function (i) {
        var self = $(this);

        // Show tooltips
        if (self.attr('data-tooltip') == 'true') {
            self.find('.tooltip').show();
            self.find('.tooltip .open').bind('click', function (e) {
                e.preventDefault();
                if (self.find('.tooltipBody').css('display') == 'block') {
                    return false;
                } else {
                    closeOpenedTooltips();
                    self.find('.tooltipBody').prepend('<a href="#" class="close" title="Close Help">Close</a>');
                    self.find('.tooltipBody').show();
                }
            });
            self.find('.tooltip .close').live('click', function (e) {
                e.preventDefault();
                self.find('.tooltipBody').hide();
                self.find('.tooltipBody .close').remove();
            });
        }
    });
}

function closeOpenedTooltips() {
    $('.tooltipBody').each(function () {
        var self = $(this);
        if (self.css('display') == 'block') {
            self.hide();
            self.find('.close').remove();
        }
    });
}

function advancedSearchSlider() {
    // Initialise active tab and do tab workings
    $('#advancedSearch div.searchSlider li.tab:eq(0)').addClass('active');
    $('#advancedSearch div.searchSlider li.tab').each(function () {
        var self = $(this);
        self.bind('click', function (e) {
            if (self.siblings().hasClass('active')) {
                self.siblings().removeClass('active');
            }
            self.addClass('active');
        });
    });
    // Keywords Box - Remove Default Value && Change Text Colour
    $(function () {
        var placeHolderText = $('.addKeywordsInput').attr('data-init-value');
        $('.addKeywordsInput').focus(function () {
            var self = $(this),
                value = self.val();
            if (value == placeHolderText) {
                self.attr('value', '');
                self.css({ color: '#000' });
            }
        }).blur(function () {
            var self = $(this),
                value = self.val();
            if (value == placeHolderText || value == '') {
                self.attr('value', placeHolderText);
                self.css({ color: '#999' });
            }
        });
    });
    // Subject Tab - Check Discipline: Check All Subjects && Check Subject: Uncheck Discipline
    $('.Subject ul').each(function () {
        var self = $(this),
            discipline = self.children('li.title'),
            subjects = self.children('li:gt(0)'),
            dCheck = discipline.find(':checkbox'),
            sCheck = subjects.find(':checkbox');
        dCheck.bind('click', function () {
            sCheck.attr('checked', this.checked);
        });
        sCheck.bind('click', function () {
            var me = $(this);
            if (dCheck.attr('checked')) {
                dCheck.attr('checked', false);
                sCheck.attr('checked', false);
            }
            me.attr('checked', this.checked);
        });
    });
    // Clear All Checkboxes Link
    $('a.clearFilters').bind('click', function (e) {
        var allChecks = $('#advancedSearch').find(':checkbox');
        allChecks.attr('checked', false);
        e.preventDefault();
    });
}

/***********************************/
/* Selectbox Replacement Functions */
/***********************************/

$(document).ready(function () {
    // Replace select boxes with styled dropdowns
    if ($('#searchResultsFilter').size() > 0) {
        $('#searchResultsFilter select, .searchResultsBar select').selectbox();
    }

    // Set height of replaced select boxes
    $('#content .jquery-selectbox').each(function () {
        if ($(this).find('.jquery-selectbox-list').height() <= '166') {
            return;
        } else {
            $(this).find('.jquery-selectbox-list').css({ 'height': '167px', 'overflow': 'auto' });
        }
    });

    // Hide relevant select boxes
    $('#ctl00_cphMainPanel_SearchResults1_pnlActiveFilters .jquery-selectbox').hide();

    // Fix IE6 last dropdown margin	
    if ($.browser.msie && parseFloat($.browser.version) < 7) {
        $('#ctl00_cphMainPanel_SearchResults1_pnlActiveFilters .jquery-selectbox').last().css({ marginBottom: '0' });
    }

    // Reapply selectbox classes to replacements
    /*$('.searchResultsBar').each(function () {
    $(this).find('label:eq(0)').attr('class', '').addClass('sortBy');
    $(this).find('label:eq(1)').attr('class', '').addClass('resultsAmount');
    });*/


    // Sort display results text if select boxes replaced
    if ($('.searchResultsBar select').css('display') == "none") {
        $('.searchResultsBar label').css('margin-right', '5px');
        $('.searchResultsBar .displayingResults').css('margin-left', '0');
        $('.ie7 .searchResultsBar .pagination, .ie6 .searchResultsBar .pagination').css('margin-left', '0');
        $('.ie6 .searchResultsBar .displayingResults').css('margin-right', '0');
        $('.ie6 .searchResultsBar').css('height', '24px');
    }

    // On LA sidebars, remove wording after Select
    // loop over current items and first dropdown items
    $('.la #searchResultsFilter .jquery-selectbox-currentItem').each(function () {
        // create startsWith function for checking against
        String.prototype.startsWith = function (str) {
            return (this.substr(0, str.length) === str);
        };

        var returnedString = $(this).text();
        if (returnedString.startsWith("Seleccionar")) {
            var trimmedString = returnedString.substring(0, 11);
            var newString = trimmedString + "...";
            $(this).text(newString);
        }
    });

});

// Favourites Page Tabs
$(document).ready(function () {
    // Apply last-child class for IE6/7
    if ($('.favorable-content-list .content-fragment-inner .content-fragment-content .filter .query-filter .filter-option:last-child').is('.selected')) {
        $('.favorable-content-list .content-fragment-inner .content-fragment-content .filter .query-filter .filter-option:last-child').addClass('last-child');
    }

    // Change size in IE8 for addthis
    if ($.browser.msie && parseFloat($.browser.version) == 8) {
        if (!$('body').hasClass('ie8') && !$('#page-container').hasClass('ie8')) {
            $('html').addClass('ie8');
        }
    }
});

/**************************************/
/*** Show User Feedback Modal Popup ***/
/**************************************/
$(function () {
    var showFeedback = document.getElementById('showFeedbackForm');
    if (showFeedback != undefined) showFeedbackForm();

    // Close
    $('#userFeedbackCloseBtn').bind('click', function (e) {
        $('#userFeedbackOverlay, #userFeedbackForm').fadeOut(500);
        e.preventDefault();
    });
    $('#userFeedbackOverlay').live('click', function (e) {
        $('#userFeedbackOverlay, #userFeedbackForm').fadeOut(500);
    });
    $(document).bind('keyup', function (e) {
        e.preventDefault();
        if (e.which == 27) {
            $('#userFeedbackOverlay, #userFeedbackForm').fadeOut(500);
        }
    });
});

function showFeedbackForm() {
    var mask,
		maskH,
		maskW,
		windowH = $(window).height(),
        windowW = $(window).width(),
		adSearchH = $('#userFeedbackForm').outerHeight(),
		posTop = (windowH - adSearchH) / 2;
    $('<div id="userFeedbackOverlay"/>').insertBefore('#userFeedbackForm');
    mask = $('#userFeedbackOverlay');
    maskH = ($('#page-container').hasClass('ie6') || $('.site-banner').hasClass('ie6')) ? $(document).height() + 20 : windowH; //
    maskW = windowW;

    $('#userFeedbackOverlay').css({ 'z-index': '949', 'top': 0, 'left': '50%', 'margin-left': -(maskW / 2), 'height': maskH, 'width': maskW, 'opacity': 1 });
    $('#userFeedbackForm').css({ 'z-index': '999', 'top': posTop });

    $('#userFeedbackOverlay').fadeTo(500, 0.7);
    $('#userFeedbackForm').fadeIn(500);

    // Centre advanced search in window
    $(window).resize(function () {
        if ($('#userFeedbackForm').css('top') != '0') {
            var windowH = $(window).height(),
            windowW = $(window).width(),
			adSearchH = $('#userFeedbackForm').outerHeight(),
			posTop = (windowH - adSearchH) / 2,
			maskH = ($('#page-container').hasClass('ie6') || $('.site-banner').hasClass('ie6')) ? $(document).height() + 20 : windowH,
            maskW = windowW;
            $('#userFeedbackOverlay').css({ 'z-index': '949', 'height': maskH, 'width': maskW, 'top': 0, 'left': '50%', 'margin-left': -(maskW / 2) });
            if ($('body').hasClass('ie6')) {
                $('#userFeedbackForm').css({ 'z-index': '999', 'top': '20px' });
            } else {
                $('#userFeedbackForm').css({ 'z-index': '999', 'top': posTop });
            }
        }
    });
}

/*** Fix Media Gallery Thumbnail Lists - CommunityServer ***/
$(window).load(function () {    
    if ($('.media-gallery-post-list').size() > 0) {
        var maxHeight = 0;

        $('.content-item.file-thumbnail-list').each(function (i, val) {
            if ($(this).height() > maxHeight) {
                maxHeight = $(this).height();
            }
        });

        $('.content-item.file-thumbnail-list').css({ height: maxHeight });
    }
});

/*** GA Member Profiling CVs ***/
function setMemberVars(values) {

    var v, career, workplace, subject, year;
    v = (values instanceof Array) ? values : [];
    for (var i = 0; i < 4; i++) {
        switch (i) {
            case 0:
                career = (v[i] != undefined && v[i] != null) ? v[i] : '';
            case 1:
                workplace = (v[i] != undefined && v[i] != null) ? v[i] : '';
            case 2:
                subject = (v[i] != undefined && v[i] != null) ? v[i] : '';
            case 3:
                year = (v[i] != undefined && v[i] != null) ? v[i] : '';
                break;
        }
    }
    if (career != '') {
        //console.log("['_setCustomVar', 1, 'Career', " + career + ", 1]");
        _gaq.push(['_setCustomVar', 1, 'Career', career, 1]);
    }
    if (workplace != '') {
        //console.log("['_setCustomVar', 2, 'Workplace', " + workplace + ", 1]");
        _gaq.push(['_setCustomVar', 2, 'Workplace', workplace, 1]);
    }
    if (subject != '') {
        //console.log("['_setCustomVar', 3, 'Subject', " + subject + ", 1]");
        _gaq.push(['_setCustomVar', 3, 'Subject', subject, 1]);
    }
    if (year != '') {
        //console.log("['_setCustomVar', 4, 'Year', " + year + ", 1]");
        _gaq.push(['_setCustomVar', 4, 'Year', year, 1]);
    }
}

// Register/Change Account Page
function registerAccountSettingsPage() {
    var drilldownVisible = false;

    $('.subjectField .fieldChoices > li > input').each(function () {
        var self = $(this);
        var drilldown = self.siblings('.drilldownPopup');
        self.bind('change', function (e) {
            e.stopPropagation();
            if (this.checked == true) {
                closeOthers(self.closest('li'));
                drilldown.fadeIn(200);
                drilldownVisible = true;
                setTimeout(function () {
                    closeOpen(drilldownVisible, self.closest('li'));
                }, 300);
            } else {
                var checkedBoxes = drilldown.find(':checked');
                if (drilldown.is(':visible')) {
                    if (checkedBoxes.size() > 0) {
                        checkedBoxes.attr('checked', false);
                    }
                    drilldown.hide();
                    drilldownVisible = false;
                } else {
                    if (checkedBoxes.size() > 0) {
                        checkedBoxes.attr('checked', false);
                    }
                }
            }
        });
    });

    $('.closeDrilldown').bind('click', function (e) {
        e.preventDefault();
        $(this).closest('.drilldownPopup').hide();
        drilldownVisible = false;
    });

    $('.drilldownPopup, .fieldChoices > li > input').bind('click', function (e) {
        e.stopPropagation();
    });

    if ($('#page-container').hasClass('ie7')) fixZindex($('.fieldChoices > li'));

    function closeOpen(drilldownVisible, parent) {
        $(document).unbind('click').bind('click', function () {
            if (drilldownVisible) {
                parent.find('.drilldownPopup').hide();
                drilldownVisible = false;
            }
        });
    }
    function closeOthers(li) {
        if (li.siblings('li').find('.drilldownPopup:visible')) {
            li.siblings('li').find('.drilldownPopup:visible').hide();
        }
    }
    function fixZindex($elem) {
        var zNum = 100;
        $elem.each(function () {
            $(this).css({ zIndex: zNum });
            zNum -= 5;
        });
    }
}

// Show/Hide Profile Questions
function profileQs(ids, source, target) {
    var ids = $('#' + ids).val().split(',');

    $('#' + source).bind('change', function () {
        ShowHideQuestions(ids, $(this), target);
    });

    ShowHideQuestions(ids, $('#' + source), target);
}

function ShowHideQuestions(ids, self, target) {

    var selected = self.children(':selected'),
		shouldShow = false;

    $.each(ids, function (i, val) {
        if (selected.val() == val) shouldShow = true;
    });

    if (shouldShow) {
        $('#' + target).fadeIn(500);
    } else {
        $('#' + target).fadeOut(500);
    }
}

// Channel One Community Link
// Take Today's Flipcharts link href, replace 'Today' with 'YYYY-MM-DD' formatted string
$(function () {
    var link = $('a[href$="http://www.prometheanplanet.com/en-us/search/resources/?PublishedDate=Today&Partner=Channel%20One&SortField=Title_asc"]');
    if (link.size() > 0) {
        var href = link.attr('href').split('Today'),
			now = new Date(),
			yyyy = now.getFullYear(),
			mm = (now.getMonth() < 9) ? '0' + (now.getMonth() + 1) : (now.getMonth() + 1),
			dd = now.getDate(),
			today = yyyy + '-' + mm + '-' + dd,
			dateLink = href.join(today);
        link.attr('href', dateLink);
    }
});
