var clear="/images/clear.gif"; //path to clear.gif
function pngfix(){
	var els=document.getElementsByTagName('*');
	var ip=/\.png/i;
	var i=els.length;
	while(i-- >0){
		var el=els[i];
		var es=el.style;
		if(el.src && el.src.match(ip) && !es.filter)
		{
			es.height=el.height;es.width=el.width;
			es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";
			el.src=clear;
		}
		else
		{
			var elb=el.currentStyle.backgroundImage;
			if(elb.match(ip))
			{
				var path=elb.split('"');
				var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';
				es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";
				es.backgroundImage='none';
				var elkids=el.getElementsByTagName('*');
				if (elkids)
				{
					var j=elkids.length;
					if(el.currentStyle.position!="absolute")es.position='static';
					while (j-- >0)
					if(!elkids[j].style.position)elkids[j].style.position="relative";
				}
			}
		}
	}
}

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/* ------------------------------------------------------------------------------ */
/*	Show and hide pop-up divs
	To include: <div class="popUpDiv" id="uniqueId"></div>
	To show: displayPopUp('uniqueId',x offset,y offset,true or false relative toggle)
	To hide:hidePopUp('uniqueId')
*/

	var IE = document.all?true:false;
	var lxPos;
	var lyPos;
		function displayPopUp(element, x, y,relative){
			var elem = document.getElementById(element);
			$(elem).fadeIn(250);
			// Position relative to cursor position
			if (relative){
				elem.style.left = lxPos + x + "px";
				elem.style.top = lyPos + y + "px";
			} 
			// Position relative to upper left corner of website
			else {
				elem.style.left = "50%";
				elem.style.marginLeft = x - 420 + "px";
				elem.style.top = y + "px";			
			}							
		}
				
		function hidePopUp(element){
			var elem = document.getElementById(element);
			$(elem).fadeOut(250);
		}
		
/* ------------------------------------------------------------------------------ */			
		function mouseMoveEvent(e){
				      if (IE){
						     lxPos = event.clientX;
							 lyPos = event.clientY;
						} else {
						     lxPos = e.pageX;
							 lyPos = e.pageY;
						}
		}	
		document.onmousemove=mouseMoveEvent; 

/* ------------------------------------------------------------------------------ */

function notationPopup(id) {
	$('#notationImage').replaceWith('<div id="notationImage" style="margin-top: 50px; margin-bottom: 20px;" align="center"><img src="/images/MusicNotationGuide' + id + '.gif"></div>');
	displayPopUp('notationPopup', 150, 200, false);
}

/* ------------------------------------------------------------------------------ */
/*	Form Validation Function
	To use:
		1) Create form and put a unique id on each form element to be validated
		2) Put a title attribute on each element to be validated - the title text will appear in the validation message "Please provide your [title tag]"
		3) In the form tag place onsubmit="return validateForm('name','email') where each argument corresponds to the id of a field to be validated*
		4) If a form requires special validation or contains fields which are not required but still should be checked for malicious characters, 
			create a function on the JSP which first calls validateForm and then performs special validation
		4) Place the error div (or p) on the page: <p id="errors" class="errorContent"><html:errors bundle="md" /></p> - This will be used by both the JS and Java validation**
		
		*Any field with the id of email will automatically be validated as an email address
		** The "return" in onsubmit will cause the form to submit only if it passes JS validation. If JS is disabled, it will submit and then have to pass server side validation
*/
	// checks that an input string looks like a valid email address.
	var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
	var passed = true;
	var validEmail = true;
	var validFields = true;
	
	// Check if a string matches the email reg ex
	function isEmail(s) {
		return String(s).search (isEmail_re) != -1;
	}
	// Validate an email field and append error
	function validateEmail(s){
		validEmail = isEmail(s);
		if (!validEmail) {
			$("#errors").append("<li>Please provide a valid email address.</li>");
		}	
	}
	// Test if a field is empty, append error or strip semi colons and percent signs
	function validateForEmpty(fieldValue, fieldDesc){
		if (fieldValue.length == 0){
			$("#errors").append("<li>Please provide your " + fieldDesc +".</li>");
			validFields = false;
		} else { // Sanitize semi colons and percent signs
			stripSemiColonsPercent(fieldValue);		
		}
	}	
	// Sanitize a string replacing semi colons and percent signs
	function stripSemiColonsPercent(fieldValue){
		fieldValue=fieldValue.replace(/;/g, ",");
		fieldValue=fieldValue.replace(/%/g, " percent");	
		return fieldValue;
	}
	// Sanitize any number of fields - use this if there are multiple fields which are not required on a form
	function sanitizeInputs(){
		for(var i=0; i<arguments.length; i++){
			document.getElementById(arguments[i]).value = stripSemiColonsPercent(document.getElementById(arguments[i]).value);
		}
	}
	// Check any number of fields from a form to see if they are blank
	function validateForm(){
		passed = true;
	 	validEmail = true;
	 	validFields = true;		
		$("#errors").html("<ul>"); // Begin the list
		$("#errors").css("display", "none"); // Initially hide errors
		for(var i=0; i<arguments.length; i++){
			elemName = arguments[i]; 
			if (elemName == "email"){
				validateEmail(document.getElementById(elemName).value); // Check for a valid email address 
			} else {
				validateForEmpty(document.getElementById(elemName).value, document.getElementById(elemName).title); // Check for a blank field
				document.getElementById(elemName).value = stripSemiColonsPercent(document.getElementById(elemName).value); // Sanitize input
			}
		}
		$("#errors").append("</ul>");
		if (!validEmail || !validFields){
			passed = false;
		}
		if (passed){
			return true;
		} else { // Slide the error div in, animate a yellow to white fade on the background
			$("#errors").css("background-color", "#FFFFCC");
			$("#errors").slideDown(250);
			$('#errors').animate({ backgroundColor: "#ffffff" }, 'slow');
			return false;
		}
	}

/* ------------------------------------------------------------------------------ */

var len = 0;
var removed = 0;
$(document).ready(function() {
	$(window).load(function() {
		$('.footer-items img').each(function() {
			len = len + $(this).width();
			if (len > 940) {
				len = len - $(this).width();
				$(this).parent().parent().remove();
				removed++;
			}
		});
		$('.footer-items img:not(:last)').css( 'margin-right', Math.round((940 - len) / $('.footer-items img').length) + 'px' );
		if (removed > 0) {
			$('#removed').html(removed + ' item(s) exceeded the width of the page.');
		}
	});
	
	$('ul.sf-menu').removeClass('noScript');
	$('div#header').removeClass('noScript');
	$('#content.largeCover ul').removeClass('noScript');
	$('#content.promoFeature ul').removeClass('noScript');
	
});
