/*window.onerror = function (errorMessage, url, line) {
    var loggerUrl = "/errorjs.asp";
    var parameters = "?description=" + escape(errorMessage)
      + "&url=" + escape(url)
      + "&line=" + escape(line)
      + "&parent_url=" + escape(document.location.href)
      + "&user_agent=" + escape(navigator.userAgent);

    new Image().src = loggerUrl + parameters;
};*/

function show_kangaroo() {
    $("#popup_newsletter_kangooroo").animate({bottom: '0'}, 3000);
}

var b = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
jQuery.browser = {
	safari: /webkit/.test(b),
	opera: /opera/.test(b),
	msie: /msie/.test(b) && !/opera/.test(b),
	msie6: /msie 6.0/.test(b) && !/opera/.test(b),
	mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)
};


jQuery.fn.indexBarOpenFirstTime = function() {
    return this.each(function(){
        $(this).find('.multimediaThumbsFull')
            .load($(this).find('.multimediaThumbsFull a').attr('href'), function() {
                $(this).parent()
                    .find('.multimediaThumbsTop').remove();
                $(this).parent().parent().indexBarOpen();
            });
    });
}

jQuery.fn.indexBarOpen = function() {
    return this.each(function(){
        $(this).find('.content')
            .slideUp(240, function() {
                $(this)
                    .addClass('open').addClass('been-open').addClass('playBarMMT')
                    .append('<a class="multimediaThumbsClose"><img src="/images/playBar-open-close-btn.png"></a>')
                    .slideDown('slow')
                    .find('.multimediaThumbsClose').click(function() {
                        $(this)
                            .parent().removeClass('open')
                            .parent().find('.multimediaThumbsMore').show();
                        $(this).remove();
                    });
            });
        $(this).find('.multimediaThumbsMore').slideUp(240);
    });
}

jQuery.fn.playBarOpenMMTFirstTime = function() {
    return this.each(function(){
        $(this)
            .find('.playBarMMT')
                .load($(this).find('a.ajax-link').attr('href'), function() {
                    $(this)
                        .append('<div style="clear:both"></div>')
                        .parent().playBarOpenMMT();
                });
    });
}
jQuery.fn.playBarOpenMMT = function() {
    return this.each(function(){
        $(this)
            .find('.playBarMMT')
                .addClass('open').addClass("been-open")
                .append('<a class="multimediaThumbsClose"><img src="/images/playBar-open-close-btn.png"></a>')
                .slideDown('slow')
                .find('.multimediaThumbsClose').click(function() {
                        $(this)
                            .parent().removeClass('open').hide()
                            .parent().find('.yellowHeader').show();
                        $(this).remove();
                    });
        $(this).find('.yellowHeader').slideUp(150);
    });
}

// lesson page 2011

function loadLessionSession(url, height) {
    $('.lessonSessions .content').remove();
    $('.lessonSessions').animate({ height: height });
    $('.lessonSessions').append('<div class="content"></div>');
    $('.lessonSessions .content').load(url);
}

function initLessonSessions() {
    $('.lessonSessions h3').click(function () {
        var $parentli = $(this).parent().parent();
        if (!$parentli.hasClass('active')) {
            $('.lessonSessions li.active').switchClass('active', 'inactive', 300);
            $('.lessonSessions').animate({ height: '70' }, function () { $('.lessonSessions .content').remove(); });
            $parentli.switchClass('inactive', 'active', 300);
            var part = $(this).parent().parent().attr('data-part');
            $('.lessonSessions').removeClass('activeA').removeClass('activeB').removeClass('activeC').addClass('active' + part);
        };
    });

    $('.lessonSessions .btnListen').click(function (e) {
        e.preventDefault();
        loadLessionSession($(this).attr('href'), '114')
    });

    $('.lessonSessions .btnWatch').click(function (e) {
        e.preventDefault();
        loadLessionSession($(this).attr('href'), '473')
    });
}

$(document).ready(function () {
    $('#part-user-notifications').load('/api/parts/UserNotifications?' + Math.random() * 99999); // prevent caching in old IE
    if ($('#part-lesson-sessions').length == 1)
        $('#part-lesson-sessions').load(
	        '/lessons/lesson/' + $('#part-lesson-sessions').attr('data-lessonnumber'),
	        initLessonSessions);

    try {
        start_ticker();
        setTimeout("show_kangaroo()", kangurooShowTime * 1000);
    } catch (err) { }

    $('.multimediaThumbsFull a').hide();
    $('.multimediaThumbsMore').click(function () {
        if (!($(this).parent().find('.content').hasClass('been-open')))
            $(this).parent().indexBarOpenFirstTime();
        else
            $(this).parent().indexBarOpen();
    });

    $('.summaryBox-read-more').click(function () {
        $(this).parent().parent().find('.introductionBox').slideDown();
        $(this).parent().parent().find('.corner').fadeOut();
        $(this).fadeOut();
        try { _gaq.push(['_trackEvent', 'Lessons', 'Expand', 'Introduction']); } catch (eee) { }
    });
    $('.introductionBox-close').click(function () {
        $('.introductionBox').slideUp();
        $(this).parent().parent().parent().find('.corner').fadeIn();
        $(this).parent().parent().parent().find('.summaryBox-read-more').fadeIn();
    });

    if (!jQuery.browser.msie6) {
        $('.tourBarOpenMMT').click(function () {
            if (!($(this).parent().parent().parent().find('.playBarMMT').hasClass('been-open')))
                $(this).parent().parent().parent().playBarOpenMMTFirstTime();
            else
                $(this).parent().parent().parent().playBarOpenMMT();
        });
    }
    else {
        $('.tourBarOpenMMT').css({ cursor: 'default' }).find('em').hide();
    }

    /* side bar ui */

    $('ul.gadgetTabIcons > li').not('.active').animate({ opacity: '0.25' });

    $('.gadgetTabsContainer')
        .mouseover(function () {
            $(this).find('ul.gadgetTabIcons > li').not('.active').css({ opacity: '0.5' });
        })
        .mouseout(function () {
            $(this).find('ul.gadgetTabIcons > li').not('.active').css({ opacity: '0.25' });
        });

    $('ul.gadgetTabIcons li').mouseover(function () {
        var $container = $(this).parent().parent();

        var newIndex = $container.find('ul.gadgetTabIcons > li').index(this);
        var oldIndex = $container.find('ul.gadgetTabs > li').index($container.find('ul.gadgetTabs li.active'));
        if (newIndex != oldIndex) {
            $container.find('ul.gadgetTabs > li.active').removeClass('active');
            $container.find('ul.gadgetTabs > li').eq(newIndex).addClass('active');
            $('ul.gadgetTabIcons > li.active').removeClass('active').css({ opacity: '0.5' });
            $(this).addClass('active').css({ opacity: '1.0' });
            $container.animate({ height: parseInt($container.find('ul.gadgetTabs > li.active').height()) + 22 + 'px' });
        }
    });

    var $toolTags = $('.module-tags');
    if ($toolTags.find('a').length > 8) {
        $toolTags.find('a:gt(6)').not('.close-tags, .more-tags').hide();
        $toolTags.find('.pad1').append('<a class="more-tags">more tags...</a><a class="close-tags"></a>');
        $('a.more-tags').click(function () {
            $('.module-tags')
                .addClass('extended')
                .find('a').not('.close-tags, .more-tags').show();
        });
        $('a.close-tags').click(function () {
            $('.module-tags')
                .removeClass('extended')
                .find('a:gt(12)').not('.close-tags, .more-tags').hide();
        });
    }

    // homepage

    $('#hp-sign-in-form input.input').each(function () {
        if ($(this).attr('value') != '') $(this).addClass('focus')
    });

    $('#hp-sign-in-form #username')
        .attr('value', $('#hp-sign-in-form label[for="username"]').html())
        .focus(function () { $(this).addClass('focus') })
        .blur(function () { if ($(this).attr('value') == '') $(this).removeClass('focus') });
    $('#hp-sign-in-form #password')
        .attr('value', $('#hp-sign-in-form label[for="password"]').html())
        .focus(function () { $(this).addClass('focus'); $('.forgot').fadeIn(); })
        .blur(function () { if ($(this).attr('value') == '') $(this).removeClass('focus') });

    $('#action-free-lessons-banner')
        .mouseover(function () {
            $(this).find('.over').stop().animate({ opacity: '1.0' });
        })
        .mouseout(function () {
            $(this).find('.over').stop().animate({ opacity: '0.0' });
        })
        .find('.over').css({ opacity: '0.0', visibility: 'visible' });

    // faq

    $('h3.faq-question').click(function () {
        $(this).parent().find('.faq-answer').slideToggle();
    });

    $('table.row-marks-radio *')
        .css('cursor', 'pointer')
        .click(function () {
            $(this).parent('tr').find('input').attr('checked', 'checked');
        });

    // fancyboxes pop-ups
    if ($.fancybox) {
        $('a.fancybox').not('.payment-questions').fancybox();
        $('a.payment-questions').fancybox({
            'autoDimensions': false,
            'width': '790',
            'height': '520'
        });
        $('a.fancybox-long').fancybox({
            'autoDimensions': false,
            'width': '630',
            'height': '520'
        });
        $('a.fancybox-lesson-related').fancybox({
            'autoDimensions': false,
            'width': '850',
            'height': '500'
        });
    }

    initLoadMoreLessons();
    
    $('.has-footnotes').each(function() {
    	var $footnotes = $(this).find('.footnote');
	if ($footnotes.length > 0)
	{
	    $(this).append('<ol class="reset footnotes"></ol>');
	    var $footnotesOl = $(this).find('ol.footnotes');
	    for (i = 1; i <= $footnotes.length; i++)
	    {
	        var $f = $footnotes.eq(i-1);
		var noteText = trim($f.html(),'{,}').replace(/"/g, '&quot;');
		$footnotesOl.append('<li id="footnote-' + i + '">' + noteText + '</li>');
		$f.html('<a title="' + noteText + '" href="#footnote-' + i + '">[' + i + ']</a>');
	    }
	}
    });
    $('.footnote a')
        .click(function() {
    	    $('ol.footnotes li').removeClass('highlight');
	        $($(this).attr('href')).addClass('highlight');
        })
        .tipsy({ gravity: 's' });
});

function initLoadMoreLessons() {
    $('.loadMoreLessons').click(function (e) {
        e.preventDefault();
        var href = $(this).attr('data-ajaxhref');
        $(this).parent()
            .html('<span class="loadingIndicator"></span>')
            .load(href, initLoadMoreLessons);
    });
}


function GetMsgText(id,TheRow) {
    if ($('#Msg'+id).css('display') == 'none')
        $('#Msg'+id).show()
    else
        $('#Msg'+id).hide();
/*  if (document.all('Msg'+id).style.display == 'none') {
      document.all('Msg'+id).style.display = 'block';
  }else {
      document.all('Msg'+id).style.display = 'none';
  } 
*/
}


function validEmail(email) {
    invalidChars = " /:,;"
    if (email == "") 
    {						// cannot be empty
	    return false
    }

    for (i=0; i<invalidChars.length; i++) {	// does it contain any invalid characters?
		badChar = invalidChars.charAt(i)
		if (email.indexOf(badChar,0) > -1) {
			return false
		}
	}
	atPos = email.indexOf("@",1)			// there must be one "@" symbol
	if (atPos == -1) {
		return false
	}
	if (email.indexOf("@",atPos+1) != -1) {	// and only one "@" symbol
		return false
	}
	periodPos = email.indexOf(".",atPos)
	if (periodPos == -1) {					// and at least one "." after the "@"
		return false
	}
	if (periodPos+3 > email.length)	{		// must be at least 2 characters after the "."
		return false
	}
	return true
}

/*
 * getCookie(): given a cookie name, get its value. Returns null if the cookie can't be found.
 * From http://www.webreference.com/js/column8/functions.html
 *
 */
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}
 
/*
 * utmvCookieCheck(): given a value, read the __utmv cookie and see if
 * that value is already set. Return true if so, false otherwise.
 *
 */
function utmvCookieCheck(value) {
	var utmvCookie = getCookie("__utmv"); 
 
	if (utmvCookie == null)
		return false;
 
	// get rid of the Google's domain prefix ID, which appear on all
	// GA cookies
	utmvCookie = utmvCookie.replace(/^\d*\./, '');
 
	return (utmvCookie == value) ? true : false;
}


function lhpTrackEvent(actionName) {
    try {
        _gaq.push(['_trackEvent', 'Player', actionName, '']);
    }
    catch (e) { }
}

/* Mini MP3 Players Sync */

function StopPlayers(activeID) {
    for (id = 0; id < playerCount; id++) {
        if (id != activeID) {
            thisMovie('Player' + id).StopMe();
        }
    }
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    }
    else {
        return document[movieName];
    }
}


// HOTFIX: We can't upgrade to jQuery UI 1.8.6 (yet)
// This hotfix makes older versions of jQuery UI drag-and-drop work in IE9
// (function ($) { var a = $.ui.mouse.prototype._mouseMove; $.ui.mouse.prototype._mouseMove = function (b) { if ($.browser.msie && document.documentMode >= 9) { b.button = 1 }; a.apply(this, [b]); } } (jQuery));



/* product pages */
function contactFormSubmit() {
    $('#contact-form-button').hide();
    $('#contact-form-sending').show();
}

/* Cookies */

function Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");

}


/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/
 
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
