/****************************************
 * Aviary
 * Global JavaScript
 ****************************************/

// Start closure to prevent namespace conflicts
;(function($) {

// Class: AviaryDialog
// AviaryDialog is a wrapper for the jQuery UI Dialog plugin
// Example usage: 
/* 
		var d = new $.AviaryDialog();
		d.message({'title': 'Message', 'content': '<p>Hi!</p>', 'button': 'Close'});
		...
		d.destroy();
*/
$.AviaryDialog = function() {
	/*
		The "message" dialog is used to display an alert-style message with
		a title and text. The message comes with a button that simply closes 
		the dialog. The default text of the button is "Okay", but it can be 
		set to anything.
	
		(new $.AviaryDialog()).message({
			'title': 'Title of the message dialog',
			'content': '<p>Content of the message dialog</p>',
			'button': 'Text on the close button' // default to "Okay" 
		})
	*/
	this.message = function(options) {
		// Set up close button (default text = "Okay")
		var button = options.button ? options.button : 'Okay';
		var b = {};
		b[button] = function() {
			$(this).dialog('destroy');
			$(this).remove();
		}
		
		// Create dialog
		this.create({
			'title': options.title ? options.title : '',
			'content': options.content ? options.content : '',
			'height': 'auto',
			'buttons': b
		});
		return this;
	};
	
	/*
		The "choices" dialog gives the user a message and any number of options
		to select as buttons. The buttons can be called anything, and they are 
		paired with callback functions.
	
		(new $.AviaryDialog()).choices({
			'title': 'Title of the choices dialog',
			'content': '<p>Content of the choices dialog</p>',
			'buttons': {
				'Button1': function() {
					alert("Button1"); // Executes when Button1 is clicked
				},
				'Button2': function() {
					alert("Button2"); // Executes when Button2 is clicked
				}
				// More buttons
			}
		})
	*/
	this.choices = function(options) {
		// Set up each button to close the dialog in addition to custom callbacks
		$.each(options.buttons, function(name, callback) {
			options.buttons[name] = function() {
				$(this).dialog('destroy');
				$(this).remove();
				callback();
			};
		});

		// Create dialog
		this.create({
			'title': options.title ? options.title : '',
			'content': options.content ? options.content : '',
			'height': 'auto',
			'buttons': options.buttons
		});
		return this;
	};
	
	/*
		Create a dialog with custom title, text, buttons, class, width, and height.
		Used internally for the other dialog types, but can also be used directly.
	*/
	this.create = function(options) {
		// Create the element that is the basis of the dialog
		this.el = $.create('div', {
			'title':options.title ? options.title : ''
		}).appendTo('body').html(options.content ? options.content : '');
		
		// If the content is an existing hidden element, show it
		if(this.el.children().length == 1 && this.el.children().css('display') == 'none') {
			this.el.children().css('display', 'block');
		}
		
		// Determine whether the dialog needs any classes
		var dialogClass = options.buttons ? 'hasButtons' : '';
		dialogClass += options.dialogClass ? ' ' + options.dialogClass : '';

		// Create the dialog
		this.el.dialog({
			'autoResize': false,
			'modal': true,
			'overlay': options.overlay ? options.overlay : {
				'background': '#000',
				'opacity': '0.8'
			},
			'buttons': options.buttons ? options.buttons : false,
			'dialogClass': dialogClass,
			'height': options.height ? options.height : 200,
			'width': options.width ? options.width : 300,
			'draggable': false,
			'resizable': false,
			'close': function() {
				$(this).dialog('destroy');
				// $(this).remove();
			}
		});
		
		return this;
	};

	// Destroy a dialog object and its associated elements
	this.destroy = function(options) {
		this.el.dialog('destroy');
		this.el.remove();
		// delete this;
	};

	// Return
	return this;
};

// Function: AviaryAjax
// AviaryAjax is a wrapper for the jQuery AJAX function
// Example usage: 
/* 
	$.AviaryAjax({
		'url': 'dosomething.aspx',
		'request': {'user':'1234', 'option':'a', 'foo':'bar'},
		'update': '#responseGoesHere'
	});
*/
$.AviaryAjax = function(options) {
	// Show AJAX activity indicator
	$.AviaryAjaxShow();
	
	// Submit AJAX request
	$.ajax({
		// Send the request
		data: options.request,
		dataType: 'html',
		cache: false,
		
		// If there was an error, replace the AJAX dialog with an error message
		error: function() {
			$.AviaryAjaxHide();

			(new $.AviaryDialog()).message({
				'title': 'Oops!', 
				'content': '<p>We were not able to do that for you. Please try again, or let us know if something is broken.</p>'
			});
		},
		
		// If data is returned, deal with it
		success: function(data, status) {
			$.AviaryAjaxHide();
			
			// Put the response in the specified update element
			$(options.update).empty().append(data);
		},
		
		// If there's an onComplete defined in the options, execute it
		complete: function(XMLHttpRequest, textStatus) {
			if(options.onComplete != undefined) {
				options.onComplete(XMLHttpRequest, textStatus);
			}
		},
		
		// AJAX URL
		url: options.url
	});
};

// Function: AviaryAjaxShow
// Show the AJAX indicator
// Example: $.AviaryAjaxShow();
$.AviaryAjaxShow = function() {
	// Show indicator
	$('#aviaryAjax').show();
	
	// For IE6, move the indicator when the window scrolls (and loads)
	if($.browser.msie && $.browser.version.charAt(0) == 6) {
		$(window).bind('scroll', moveAjax);
		moveAjax();
	}
}

// Function: AviaryAjaxHide
// Hide the AJAX indicator
// Example: $.AviaryAjaxHide();
$.AviaryAjaxHide = function() {
	// Hide indicator
	$('#aviaryAjax').hide();
	
	// Remove IE6 scroll event
	if($.browser.msie && $.browser.version.charAt(0) == 6) {
		$(window).unbind('scroll', moveAjax);
	}
}

// Helper function to move AJAX indicator for IE6
function moveAjax() {
	$('#aviaryAjax').css('top', $(window).scrollTop());
}

// Perform initial setup tasks when DOM is ready
$(document).ready( function() {
	setupNavigationLinks();
	$.AviarySetupDefaultInputs();
	$.AviarySetupToggles();
	setupMessages();
  setupCriticalMessages();
	// $.AviarySetupCenterBoxes();
	$.AviarySetupAjaxTabs();
	$.AviarySetupPermissionsForm();
	$.AviarySetupNavSearch();
	$.AviarySetupMarkItUp();
	$.AviarySetupCheckboxes();
});

// Set up main navigation mouseover menus
function setupNavigationLinks() {
	$('.nav-menu').each(function() {
		var menu = $(this);
		
		menu.hover(function() {
			menu.addClass('hover');
		}, function() {
			menu.removeClass('hover');
		});
	});
}

// Go through all form elements with class="default" 
// Set the class to "defaultText" (turns it light grey)
// and set up toggling of that class with focus/blur
$.AviarySetupDefaultInputs = function() {
	var inputs = $('input.default');
	
	inputs.each(function(i) {
		$.AviarySetupDefaultInput(this);
	});
};

// Set up a single default input
$.AviarySetupDefaultInput = function(what) {
	var input = $(what);
	
	input.removeClass('default');
	input.addClass('defaultText');
	input.defaultValue = input.val();
	
	input.focus(function() {
		input.removeClass('defaultText');
		if(input.val() == input.defaultValue) 
			input.val('');
	});
	
	input.blur(function() {
		if(input.val() == input.defaultValue || input.val() == '') 
			input.addClass('defaultText');
		if(input.val() == '') 
			input.val(input.defaultValue);
	});
};

// Set up smooth toggling of elements with class="toggle" when the 
// associated link is clicked. To toggle, <div id="foo" class="toggle">,
// click the <a href="#" id="toggle-foo">. To make the element hidden
// by default, add the class "hidden" (class="toggle hidden")
$.AviarySetupToggles = function() {
	// Loop through all elements with class="toggle"
	var elements = $('.toggle');
	elements.each(function(i) {
		var el = $(this);

		// Get associated link (id="toggle-[el.id]")
		var link = $('#toggle-' + el.attr('id'));
		if(link.length) {
			// Hide the element if necessary
			if(el.hasClass('hidden')) {
				el.hide();
			};

			// Set up the onclick
			link.click(function(e) {
				el.slideToggle('normal');
				return false;
			});
		}
	});
}

// Set up message closing. When a user clicks the "x" icon, the message
// should fade out and disappear
function setupMessages() {
	// Check for #messages
	var container = $('#messages');	
	if(container.length) {
		
		// Loop through messages
		var messages = container.find('.message');
		var total = messages.length;
		messages.each(function() {
			var message = $(this);

			// Close icon
			var close = message.find('.close');
			close.click(function(e) {		
				message.fadeOut('normal', killIt);
				return false;
			});
			
			// Remove the message from the page when the fade out is complete
			function killIt() {
				message.remove();
				total--;
				
				// If there are no more message, remove the container
				if(total == 0) container.remove();
			}
		});
	}
}

// Same deal as setupMessages, but for #criticalmessages container
// TODO: consolidate this with setupMessages and other similar functions
function setupCriticalMessages() {
	// Check for #messages
	var container = $('#criticalmessages');	
	if(container.length) {
		
		// Loop through messages
		var messages = container.find('.message');
		var total = messages.length;
		messages.each(function() {
			var message = $(this);
			// Close icon
			var close = message.find('.close');
			close.click(function(e) {	
				message.fadeOut('normal', killIt);
				document.cookie="ClosedCriticalMessage="+ $(close).attr('id') +"; expires=Monday, 04-Jan-2099 05:00:00 GMT";
				//alert($(close).attr('id'));
				return false;
			});
			
			// Remove the message from the page when the fade out is complete
			function killIt() {
				message.remove();
				total--;
				
				// If there are no more message, remove the container
				if(total == 0) container.remove();
			}
		});
	}
}

// Set up centerbox and centerme elements
// .centerme elements should be vertically and horizontally centered in their
// containing .centerbox elements
$.AviarySetupCenterBoxes = function() {
	$('.centerbox').each(function() {
		// Box is the bounding box. Thing is the element to center inside of it.
		var box = $(this);
		var thing = $('.centerme', box);
		if(thing.length) {
			// Sometimes thing has no dimensions yet (img hasn't loaded)
			// If there are dimensions, center it
			if(thing.height() && thing.width()) {
				centerIt();
			}
			// Otherwise, wait for it to load, then center it
			else {
				thing.load(centerIt);
			}
		}
		
		// Center it!
		function centerIt() {
			thing.css({
				display: 'block',
				position: 'relative',
				top: Math.floor((box.height() - thing.innerHeight())/2),
				left: Math.floor((box.width() - thing.innerWidth())/2)
			});
		}
	});
};

// Set up AJAX tabs
// AJAX tabs are implemented the same way as regular tabs, but the .tabs 
// element has the additional class 'ajaxTabs'. This setup routine just
// moves the 'active' class from one tab to another
$.AviarySetupAjaxTabs = function() {
	$('.ajaxTabs').each(function() {
		var tabs = $(this);
		$('.tabs-nav a', tabs).click(function(e) {
			e.preventDefault();
			var link = $(this);
			if(!link.hasClass('active')) {
				$('.tabs-nav .active', tabs).removeClass('active');
				link.addClass('active');
			}
		});
	});
};

// Set up the various conditional toggles for permissions forms
// Toggle default overrides, contact lists, creative commons options
$.AviarySetupPermissionsForm = function() {
	if($('#permissionsForm').length) {
		// Set up view and edit permissions menus and associated contact lists
		$.each(['view', 'edit'], function() {
			var menu = $('#select-permission-' + this);
			var lists = $('#permission-' + this + '-lists');

			// Hide the lists unless "restricted" is selected
	    if(menu.val() != 'restricted') {
	      lists.hide();
	    }

	    // Show/hide the lists as necessary
	    menu.change(function() {
	      if(menu.val() == 'restricted') {
	        lists.slideDown('fast');
	      }
	      else {
	        lists.slideUp('fast');
	      }
	    });
		});

		// Enforce permissions inheritance on load and when view menu changes
		enforcePermissionsInheritance();
		$('#select-permission-view').change(function() { enforcePermissionsInheritance(); });

		// Internet Explorer doesn't support <option disabled="disabled">, so fake it
		if($.browser.msie) {
			$('#select-permission-edit').change(function() {
				var menu = $(this);

				if($('option:selected', menu).hasClass('disabled')) {
					$('option:not(.disabled):first', menu).attr('selected', 'selected');
					menu.trigger('change');
				}
			});
		}

		// Set up toggling of overrides
		$.each(['#chooseLicense'], function() {
			// Get some elements
			var override = $(this+'-overrides');
			var checkbox = $(this+'-default');

			// Hide overrides if necessary
			if(checkbox.attr('checked')) {
				override.hide();
			}

			// Set up toggling
			checkbox.click(function(e) {
				if(checkbox.attr('checked')) {
					override.slideUp('fast');
				}
				else {
					override.slideDown('fast');
				}
			});
		});
	} // end if($('#permissionsForm').length)

	// Helper function to make sure view permissions >= edit permissions
	function enforcePermissionsInheritance() {
		// Permissions hierarchy:
		var priority = {'everyone': 1, 'contacts': 2, 'restricted': 3, 'private': 4};

		// Get menus
		var viewMenu = $('#select-permission-view');
		var editMenu = $('#select-permission-edit');

		// Get current view menu setting
		var viewSetting = priority[viewMenu.val()];

		// Loop through edit options
		// Keep track of whether we had to change the selection
		var editMenuChanged = false;
		$('option', editMenu).each(function() {
			var option = $(this);		
			// If this is an invalid option, disable it
			if(priority[option.val()] < viewSetting) {
				option.attr('disabled', 'disabled');
				if($.browser.msie) {
					option.addClass('disabled');
					option.css('color', '#aaa');
				}		
				
				// And unselect it if necessary
				if(option.attr('selected')) {
					option.next('option').attr('selected', 'selected');
					editMenuChanged = true;
				}
			}
			// If this is a valid option, make sure it's enabled
			else {
				option.attr('disabled', false);
				if($.browser.msie) {
					option.removeClass('disabled');
					option.css('color', '#000');
				}
			}
		});

		// If the selection was changed, trigger the onchange event
		if(editMenuChanged) {
			editMenu.trigger('change');
		}
	}
};

// Basic email verification
$.AviaryCheckEmail = function(str){
  var filter=/^.+@.+\..{2,3}$/;
  var testresults;
  if (filter.test(str))
  if(str.indexOf(',') > 0) {
    testresults=false;
  } else {
    testresults=true;
  }
  else {
    testresults=false;
  }
  return (testresults);
}

// Copy text to the clipboard
$.AviaryCopyText = function(inElement) {
  inElement = document.getElementById(inElement);

  if (inElement.createTextRange) {
    var range = inElement.createTextRange();
    if (range!=null)
    range.execCommand('Copy');
  } 
  else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="javascript/_clipboard.swf" FlashVars="clipboard='+escape(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}

// Set up submission of the header navigation search box
$.AviarySetupNavSearch = function() {
	var icon = $('#nav-icon.nav-icon-search');
	var container = $('#nav-search');
	var keywords = $('#nav-search-keywords');
	var input = $('#nav-search-input');
	var submit = $('#nav-search-submit');
	var close = $('#nav-search-close');
	var visible = false;
	
	// Toggle search interface
	icon.click(function(e) {
		e.preventDefault();
		
		if(visible) {
			container.fadeOut('normal', function() {
				input.blur();
				visible = false;
			});
		}
		else {
			container.fadeIn('normal', function() {
				input.focus();
				visible = true;
			});
		}
	});
	
	// Close search interface
	close.click(function(e) {
		e.preventDefault();
		container.fadeOut('normal', function() {
			input.blur();
			visible = false;
		});
	});
	
	// Use the input focus state to set the "focus" class on the keywords container
	input.blur();
	input.focus(function() {
		keywords.addClass('focus');
	});
	input.blur(function() {
		keywords.removeClass('focus');
	});
	
	// Submit the search when the submit "button" is clicked
	submit.click(function(e) {
		e.preventDefault();
		var query = $.param({'q': input.val()});
		query += '&' + $.param({'searchtype': $('input[name="searchtype"]:checked', container).val()});
		window.location = '/search?' + query;
	});
	
	// Or when the enter key is pressed
	input.keypress(function(e) {
		if(e.which == 13) {
			e.preventDefault();
			submit.click();
		}
	});
};

// Set up markItUp! buttons for text editing
// http://markitup.jaysalvat.com
$.AviarySetupMarkItUp = function() {
	if(typeof $.markItUp != 'undefined') {
		$('textarea.AviaryCode').markItUp(AviaryCodeSettings);
	}
};

// Set up custom checkboxes
$.AviarySetupCheckboxes = function() {
	var checkboxes = $('.bigActionIcon.checkbox');
	if(checkboxes.length) {
		
		checkboxes.each(function() {
			var checkbox = $(this);
			var img = $('img', checkbox);
			img.addClass('nohover');
			
			checkbox.mouseover(function() {
				img.css('top', -16);
			});
			
			checkbox.mouseout(function() {
				img.css('top', 0);
			});
		
			checkbox.click(function(e) {
				e.preventDefault();
				checkbox.toggleClass('on');
				img.css('top', 0);
			});
		});
	}
};

// Handle custom checkbox click
$.AviaryCheckboxClick = function(checkbox, on, off) {
	if($(checkbox).hasClass('on')) {
		off.call();
	}
	else {
		on.call();
	}
};

// End closure
})(jQuery);

// TODO: deal with these other functions

function showMessage(title, text, critical)
{
    showMessageHere("messages", title, text, critical);
}
function showMessageHere(messagesid, title, text, critical)
{

    var str = "";
    if (critical)
    {
    	str = "<div class='message critical'>";
    }
    else
    {
        str = "<div class='message success'>";
    }
	
	str += "<a class=\"close\" href=\"#\"><img src=\"images/icons/x.gif\" alt=\"Remove message\" title=\"Remove message\" /></a>";
	
	str = str + "<h3>" + title + "</h3>\n<p>" + text + "</p>\n</div>";
	document.getElementById(messagesid).innerHTML = str;
    setupMessagesCustom(messagesid);
	document.getElementById(messagesid).style.display = "";
}

function setupMessagesCustom(messagesid) {
	// Check for #messages
	var container = $('#' + messagesid);	
	if(container.length) {
		
		// Loop through messages
		var messages = container.find('.message');
		var total = messages.length;
		messages.each(function() {
			var message = $(this);

			// Close icon
			var close = message.find('.close');
			close.click(function(e) {		
				message.fadeOut('normal', killIt);
				return false;
			});
			
			// Remove the message from the page when the fade out is complete
			function killIt() {
				message.remove();
				total--;
				
				// If there are no more message, remove the container
				//if(total == 0) container.remove();
			}
		});
	}
}

var arrAudioPlayers = [];
                                    
function loadAudioPlayer (libraryid, fvid, div) {
    var playerCode = '';
    
    if(libraryid=='aviary') {
        playerCode = '\
            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"\
                style="width: 177px; height: 177px; position: absolute; top: 0pt; left: 0pt;"\
                id="PreviewPlayer' + fvid + '" width="177" height="177"\
                codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">\
                <param name="movie" value="/apps/flash/aviary/audio/PreviewPlayer.swf?filesource=local&fileid=' + fvid + '" />\
                <param name="quality" value="high" />\
                <param name="wmode" value="transparent" />\
                <param name="bgcolor" value="#2796ef" />\
                <param name="allowScriptAccess" value="sameDomain" />\
                <embed  src="/apps/flash/aviary/audio/PreviewPlayer.swf?filesource=local&fileid=' + fvid + '" quality="high" bgcolor="#2796ef"\
                    width="177" height="177" name="PreviewPlayer' + fvid + '" align="middle"\
                    play="true"\
                    loop="false"\
                    quality="high"\
                    wmode="transparent"\
                    allowScriptAccess="sameDomain"\
                    type="application/x-shockwave-flash"\
                    pluginspage="http://www.adobe.com/go/getflashplayer">\
                </embed>\
          </object>\
        ';
    } else {
    
        playerCode = '\
            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"\
                style="width: 177px; height: 177px; position: absolute; top: 0pt; left: 0pt;"\
                id="PreviewPlayer' + fvid + '" width="177" height="177"\
                codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">\
                <param name="movie" value="/apps/flash/aviary/audio/PreviewPlayer.swf?filesource=remote&fileid=' + fvid + '" />\
                <param name="quality" value="high" />\
                <param name="wmode" value="transparent" />\
                <param name="bgcolor" value="#2796ef" />\
                <param name="allowScriptAccess" value="sameDomain" />\
                <embed  src="/apps/flash/aviary/audio/PreviewPlayer.swf?filesource=remote&fileid=' + fvid + '" quality="high" bgcolor="#2796ef"\
                    width="177" height="177" name="PreviewPlayer' + fvid + '" align="middle"\
                    play="true"\
                    loop="false"\
                    quality="high"\
                    wmode="transparent"\
                    allowScriptAccess="sameDomain"\
                    type="application/x-shockwave-flash"\
                    pluginspage="http://www.adobe.com/go/getflashplayer">\
                </embed>\
          </object>\
        ';
    }
    $('#' + div + ' #playimg' + fvid).hide();
    
    var theDiv = document.getElementById(div);
    theDiv.innerHTML += playerCode;
    
    $('#' + div).removeAttr( 'onclick' );
   
    var exists = audioPlayerExists('PreviewPlayer' + fvid);
    if (!exists)
    {
        arrAudioPlayers.push('PreviewPlayer' + fvid);
    }
}

function loadSizedAudioPlayer (libraryid, fvid, div, size) {
    var playerCode = '';
    
    var width, height;
    
    if(size == 'small') {
        width = 111;
        height = 111;
        
        offsetTop = 2;
        offsetLeft = 2;
    }
    else if(size == 'smaller') {
        width = 50;
        height = 20;
        
        offsetTop = 15;
        offsetLeft = 4;
    }
        
    
    if(libraryid=='aviary') {
        playerCode = '\
            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"\
                style="width:' + width + 'px; height:' + height + 'px; position: absolute; top: ' + offsetTop + 'pt; left: ' + offsetLeft + 'pt;"\
                id="PreviewPlayer' + fvid + '" width="' + width + '" height="' + height + '"\
                codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">\
                <param name="movie" value="/apps/flash/aviary/audio/PreviewPlayer.swf?filesource=local&fileid=' + fvid + '" />\
                <param name="quality" value="high" />\
                <param name="wmode" value="transparent" />\
                <param name="bgcolor" value="#2796ef" />\
                <param name="allowScriptAccess" value="sameDomain" />\
                <embed  src="/apps/flash/aviary/audio/PreviewPlayer.swf?filesource=local&fileid=' + fvid + '" quality="high" bgcolor="#2796ef"\
                    width="' + width + '" height="' + height + '" name="PreviewPlayer' + fvid + '" align="middle"\
                    play="true"\
                    loop="false"\
                    quality="high"\
                    wmode="transparent"\
                    allowScriptAccess="sameDomain"\
                    type="application/x-shockwave-flash"\
                    pluginspage="http://www.adobe.com/go/getflashplayer">\
                </embed>\
          </object>\
        ';
    } else {
    
        playerCode = '\
            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"\
                style="width: 177px; height: 177px; position: absolute; top: 0pt; left: 0pt;"\
                id="PreviewPlayer' + fvid + '" width="177" height="177"\
                codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">\
                <param name="movie" value="/apps/flash/aviary/audio/PreviewPlayer.swf?filesource=remote&fileid=' + fvid + '" />\
                <param name="quality" value="high" />\
                <param name="wmode" value="transparent" />\
                <param name="bgcolor" value="#2796ef" />\
                <param name="allowScriptAccess" value="sameDomain" />\
                <embed  src="/apps/flash/aviary/audio/PreviewPlayer.swf?filesource=remote&fileid=' + fvid + '" quality="high" bgcolor="#2796ef"\
                    width="177" height="177" name="PreviewPlayer' + fvid + '" align="middle"\
                    play="true"\
                    loop="false"\
                    quality="high"\
                    wmode="transparent"\
                    allowScriptAccess="sameDomain"\
                    type="application/x-shockwave-flash"\
                    pluginspage="http://www.adobe.com/go/getflashplayer">\
                </embed>\
          </object>\
        ';
    }
    $('#' + div + ' #playimg' + fvid).hide();
    
    var theDiv = document.getElementById(div);
    theDiv.innerHTML += playerCode;
    
    $('#' + div).removeAttr( 'onclick' );
   
    var exists = audioPlayerExists('PreviewPlayer' + fvid);
    if (!exists)
    {
        arrAudioPlayers.push('PreviewPlayer' + fvid);
    }
}

function audioPlayerExists(targetId)
{
    for(i=0; i < arrAudioPlayers.length; i++)
    {
        if (arrAudioPlayers[i] == targetId)
            return true;
    }
    return false;
}

function stopAllAudioPlayers(id)
{
    var IE = /*@cc_on!@*/false;
    
    for(i=0; i < arrAudioPlayers.length; i++)
    {
       if(IE) {
            var x;
            eval('x = document.getElementById("' + arrAudioPlayers[i] + '")');
            x.stopPlayer(id);
       } else {
            eval('document.' + arrAudioPlayers[i] + '.stopPlayer("' + id + '");');
       }
    }
}

