/* Prevent headers from wrapping by shrinking the font depending on the character length */
function longheadersfix() {
	$('.header h2').each(function () {
			var new_length = $(this).html().length;
			if(new_length > 75 && new_length < 76) {$(this).attr('style','font-size:11px !important');} 
			else if(new_length > 77) {$(this).attr('style', 'font-size :10px !important');}
	});
}

/** 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');
	})
}

//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("8d9111749d3c4d7164f1a419f80a46d1", "/Common/xd_receiver.htm", {permsToRequestOnConnect : "email"});})
	        $(function(){$('.facebook').show();});
         }
       }
}

/* add to bag transition */
function addedtobag() {
	$(function () {
		$(".btn_addtocart").switchClass('btn_addtocart', 'btn_blue');
		$('.btn_addtocart input').val('Added');
		$('body').Sleep(2000, function () {
				$(".btn_blue").switchClass('btn_blue', 'btn_addtocart');
				$('.btn_blue input').val('Add to Cart');
		});
	});
}
//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) {}
}

$(function() {

    $('body').Sleep(200, function() {
        W220footer();
        bottomBlocksLineUp();
        faq_slide();
        longheadersfix();
        $('.tab_text li:first').show();
    });

    /*
    //Mega Menu Dynamic Width & Heights    
    $('#mainNav .navigation-item div[id^="parent-container"]').each(function() {
        var settings = {}

        settings = {
            'headerCol1': { 'selector': $('#headerCol1:first', this), 'fullheight': 0, 'fullwidth': 0 },
            'headerCol2': { 'selector': $('#headerCol2:first', this), 'fullheight': 0, 'fullwidth': 0 },
            'menuCellHeight': 0, 'menuCellWidth': 0, 'offsetHeight': 20, 'offsetWidth': 15
        };

        if (settings.headerCol1.selector.size() == 1) {
            settings.headerCol1.fullheight = settings.headerCol1.selector.outerHeight(true);
            settings.headerCol1.fullwidth = settings.headerCol1.selector.outerWidth(true);
            $('#headerCol1:first img', this).css({
                'width': settings.headerCol1.fullwidth - 20
            });
        }
        if (settings.headerCol2.selector.size() == 1) {
            settings.headerCol2.fullheight = settings.headerCol2.selector.outerHeight(true);
            settings.headerCol2.fullwidth = settings.headerCol2.selector.outerWidth(true) + 20;
            $('#headerCol2:first img', this).css({
                'width': settings.headerCol2.fullwidth - 20
            });
        }

        settings.menuCellHeight = settings.headerCol1.fullheight;
        settings.menuCellWidth = (settings.headerCol1.fullwidth + settings.headerCol2.fullwidth);

        if (settings.headerCol2.fullheight > settings.headerCol1.fullheight) {
            settings.menuCellHeight = settings.headerCol2.fullheight;
        }

        settings.offsetHeight = (settings.menuCellHeight / 20);

        $(this).width(settings.menuCellWidth + settings.offsetWidth);

        $('img:first', this).css({
            'height': settings.menuCellHeight + settings.offsetHeight,
            'width': settings.menuCellWidth + settings.offsetWidth
        });

    });
    */
    // The main menu - Mega menu


    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;
        }
    });
    
    $('body').Sleep(200, function () {
        if ($('.searchFiltersCol').size()==1){$('.searchFiltersCol input').each(function() {$(this).attr('submitbuttonclass', 'searchfilterbtn');});}
    });
    
    //Top Bar Slide Down Panels
    $(".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); $("div#countryMenu").slideToggle(); $(this).toggleClass("selected"); });
    $(".loginClose").click(function(e) { $("div#signin_menu").slideUp(); });
    $(".countryClose").click(function(e) { $("div#countryMenu").slideUp(); });


    // Remove nojs class for menu
    $("*").removeClass("nojs");


    $("#footer ul li:last").addClass("lastFooter");


});


// 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-06-28 - Popup Survey
/*
$(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 = "PopUpSurvey01";
    // number of days the cookie should persist
    var expDays = 30;
    // URL to the pop-up
    var popupUrl = "http://customer.automatesurvey.com/interview/interview.do?pid=5HJMRKMMURTCBEZXsL0oh6yMyBsUSRHZw6fyN7mzMAAOu3iQkBCoIFgOjfMDREkHRjiEkHymHE8borKYo&scid=rVMzt8iutmezzQJ1aveoMqYchMjtdW9RwtMyFuxLPcNqTo";
    // Popup Window Name
    var popupName = "PopUpSurvey01";
    // 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/search/resources/",
	    "/en-us/search/resources/",
	    "/en/search/resources/resource-type--lesson",
	    "/en/store/",
	    "/en/support/software/activinspire/",
	    "/en-us/support/software/activinspire/"
    );
    // 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
                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 {
                SetCookie(cookieName, ++count, exp, cookiePath, cookieDomain);
            }
            break;
        }
    }
});
*/