// Click to view toggle variable
var mainNav = false;

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function Transition(curve, milliseconds, callback) {
    this.curve_ = curve;
    this.milliseconds_ = milliseconds;
    this.callback_ = callback;
    this.start_ = new Date().getTime();
    var me = this;
    this.runCallback_ = function() {
	me.run();
    };
}

Transition.prototype.run = function() {
    if (!this.hasNext()) return;
    this.callback_(this.next());
    setTimeout(this.runCallback_, 10);
}

Transition.prototype.hasNext = function() {
    if (this.done_) return this.oneLeft_;
    var now = new Date().getTime();
    if ((now - this.start_) > this.milliseconds_) {
	this.done_ = true;
	this.oneLeft_ = true;
    }
    return true;
}

Transition.prototype.next = function() {
    this.oneLeft_ = false;
    var now = new Date().getTime();
    var percentage = Math.min(1, (now - this.start_) / this.milliseconds_);
    return this.curve_(percentage);
}


function SineCurve(percentage) {
    return (1 - Math.cos(percentage * Math.PI)) / 2;
}


function navigationMain(updatedText) {	
	var element = document.getElementById("mainNavigation");
	var text=document.getElementById("clickToView");
	
	if (mainNav == false){
		text.innerHTML = "Click to view " + updatedText;
    
		var transition = new Transition(SineCurve, 1000, function(percentage) {
		var y = 60;
		element.style.marginTop = -60 + Math.round(percentage * y) + "px";
    	});
    	transition.run();
    	mainNav = true;
 	}

 	else {
    	text.innerHTML = "Click to view all Music Dispatch Product Categories";

		var transition = new Transition(SineCurve, 1000, function(percentage) {
		var y = 60;
		element.style.marginTop = -Math.round(percentage * y) + "px";
   		});
    	transition.run();
    	mainNav = false;
	}
}

/* ------------------------------------------------------------------------------ */

/*********************
//* jQuery Multi Level CSS Menu #2- By Dynamic Drive: http://www.dynamicdrive.com/
//* Last update: Nov 7th, 08': Limit # of queued animations to minmize animation stuttering
//* Menu avaiable at DD CSS Library: http://www.dynamicdrive.com/style/
*********************/

//Specify full URL to down and right arrow images (23 is padding-right to add to top level LIs with drop downs):
var arrowimages={down:['downarrowclass', 'down.gif', 23], right:['rightarrowclass', 'right.gif']}

var jqueryslidemenu={

animateduration: {over: 200, out: 100}, //duration of slide in/ out animation, in milliseconds

buildmenu:function(menuid, arrowsvar){
	jQuery(document).ready(function($){
		var $mainmenu=$("#"+menuid+">ul")
		var $headers=$mainmenu.find("ul").parent()
		$headers.each(function(i){
			var $curobj=$(this)
			var $subul=$(this).find('ul:eq(0)')
			this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
			this.istopheader=$curobj.parents("ul").length==1? true : false
			
			//$subul.css({top:this.istopheader? this._dimensions.h+"px" : 0})
			//$subul.css({top:0+"px"})
			
			//$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: arrowsvar.down[2]} : {}).append(
			//	'<img src="'+ (this.istopheader? arrowsvar.down[1] : arrowsvar.right[1])
			//	+'" class="' + (this.istopheader? arrowsvar.down[0] : arrowsvar.right[0])
			//	+ '" style="border:0;" />'
			//)
			
			$curobj.hover(
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					
					this._offsets={left:$(this).offset().left, top:$(this).offset().top}
					//this._offsets={left:$(this).offset().left, top:0}
					
					var menuleft=this.istopheader? 0 : this._dimensions.w
					menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
					if ($targetul.queue().length<=1) //if 1 or less queued animations
						$targetul.css({left:menuleft+"px", width:this._dimensions.subulw+'px'}).slideDown(jqueryslidemenu.animateduration.over)
				},
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					$targetul.slideUp(jqueryslidemenu.animateduration.out)
				}
			) //end hover
		}) //end $headers.each()
		$mainmenu.find("ul").css({display:'none', visibility:'visible'})
	}) //end document.ready
}
}

//build menu with ID="myslidemenu" on page:
jqueryslidemenu.buildmenu("myslidemenu", arrowimages);

/* ------------------------------------------------------------------------------ */

var marqueePos = 0;
var speed = 1;
function scroll() {
    marqueePos = scrollTicker( "vmarquee", marqueePos );
}

function scrollTicker(id, pos) {
  if (document.getElementById(id) != null){
	  var div = document.getElementById(id);
	  if (pos < (div.offsetWidth * -1)) {
	    pos = 810;
	  } else {
	    pos -= speed;
	  }
	  div.style.left = pos + "px";
	  return pos;
	}
}
setTimeout("window.setInterval( 'scroll()', 15)", 1000);


/* ------------------------------------------------------------------------------ */
function changeBg(elemId, action) {
	var bg = 'url(/images/navbg.gif)';
	if (action == 'mouseover') {
		bg = 'url(/images/navbg2.gif)'
	}
	var elem = document.getElementById(elemId);
	elem.style.background = bg;
}

/* ------------------------------------------------------------------------------ */

/**
 * 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;
		}
	}