/* ==================================================== *
 * TITLE   : COMMON JAVASCRIPT   |  common.js           *
 * ==================================================== */

/* ==================================================== *
 * EXTERNAL POPUP
 * ==================================================== */

var poppedWin = null;

/**
 * Call like this: ...onclick="return !NewWindow(this.href, {'height': 600, 'scrollable': 'no'})"...
 * @return  true if popup succeeded
 */
function NewWindow(url)
{
	//retrofit for old calls
	if(arguments.length === 5)
	{
		opts =
		{
			'winLabel': arguments[1],
			'width': arguments[2],
			'height': arguments[3],
			'scrollable': arguments[4]
		};
	}
	else if(arguments.length === 2)
	{
		opts = arguments[1];
	}
	else
	{
		opts = {};
	}

	var winLabel = opts['winLabel'] || "CrutchfieldPopup";
	var width = opts['width'] || 400;
	var height = opts['height'] || 450;
	var scrollable = opts['scrollable'] || 'yes';
	var resizable = opts['resizable'] || 'yes';
	var stripped = opts['stripped'] || 'no'; // 'yes', 'no', or 'almost'

	var leftPosition = (screen.width) ? (screen.width-width)/2 : 0;
	var topPosition = (screen.height) ? (screen.height-height)/2 : 0;
	var chromeSettings = (stripped === 'yes' ? ',toolbar=no,location=no,directories=no,status=no,menubar=no' : stripped === 'almost' ? ',toolbar=no,location=yes,directories=no,status=no,menubar=no' : '');

	settings = 'height='+height+',width='+width+',top='+topPosition+',left='+leftPosition+',scrollbars='+scrollable+',resizable='+resizable + chromeSettings;
	poppedWin = window.open(url, winLabel, settings);

	if(poppedWin)
		poppedWin.focus();//just in case we are replacing a backgrounded popup

	return !!poppedWin;// so we can say onclick="return !NewWindow(...)"
}

/**
 * Backwards compatibility. See global.js.
 */
function sizedWindow(url, width, height)
{
	NewWindow(url, {'width':width, 'height':height, 'scrollable':'yes', 'resizable':'yes'});
}

/**
 * Backwards compatibility. See global.js.
 */
function fixedSizedWindow(url, width, height)
{
	NewWindow(url, {'width':width, 'height':height, 'scrollable':'yes', 'resizable':'no'});
}

/**
 * Backwards compatibility. See global.js.
 */
function dictWindow(term, group)
{
	var url = "http://" + window.location.hostname + "/cgi-bin/glossary.asp?term=" + term + "&group=" + group;
	NewWindow(url, {'width':400, 'height':250, 'winLabel':'dictionary', 'scrollable':'yes', 'resizable':'yes'});
}



/**
 * Call like this: ...onclick="return !loadInParent(this.href, true)"...
 * @return  true if popup succeeded
 */
function loadInParent(url, closeSelf)
{
	if(self.opener)
	{
		self.opener.location = url;
		if(closeSelf)
			self.close();
		return true;
	}
	else // on the slight chance that this is called from a non-popup, open link normally
	{
		return false;
	}
}





/*=============*
 * FLASH VIDEO *
 *=============*/

function MM_CheckFlashVersion(reqVerStr,msg){
  with(navigator){
    var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
    var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
    if (!isIE || !isWin){
      var flashVer = -1;
      if (plugins && plugins.length > 0){
        var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
        desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
        if (desc == "") flashVer = -1;
        else{
          var descArr = desc.split(" ");
          var tempArrMajor = descArr[2].split(".");
          var verMajor = tempArrMajor[0];
          var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
          var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
          flashVer =  parseFloat(verMajor + "." + verMinor);
        }
      }
      // WebTV has Flash Player 4 or lower -- too low for video
      else if (userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 4.0;

      var verArr = reqVerStr.split(",");
      var reqVer = parseFloat(verArr[0] + "." + verArr[2]);

      if (flashVer < reqVer){
        if (confirm(msg))
          window.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
      }
    }
  }
}


/*===================================*
 * Late loading for quicktime movies *
 *===================================*/

var re_tagExCC_end = /^<\!\[endif\]-->/i;
var re_tagExCC_begin = /$<\!--\[if IE\]>/i;

/**
 * Bypass IE's ugly restrictions on certain types of active content by loading it dynamically.
 * Whatever needs to be loaded dynamically can be put in a <noscript class="active-content-embed"> block,
 * and this function will drop it into the DOM (after the rest of the onDomReady stuff has been called.)
 *
 * Since Safari can't look inside <noscript> elements, use this:
 * <!--[if IE]><noscript class="active-content-embed"><![endif]-->
 *   ... object and embed code ...
 * <!--[if IE]></noscript><![endif]-->
 */
function lateLoadActiveContent(i)
{
	$(this).before(this.innerHTML.replace(re_tagExCC_end, '').replace(re_tagExCC_begin, ''));
}


/*===========================*
 * Flyout and dropdown menus *
 *===========================*/

var MENU_COUNTER = 1;

function loadMenu()
{
	if(this.id == 'dynamicMenu') {
		$('> ul > li', this).remove();

		var ul = $('<ul></ul>');
		var t = MENU_COUNTER + 10;
		for(; MENU_COUNTER < t; MENU_COUNTER++)
		{
			$('> ul', this).append('<li>Item ' + MENU_COUNTER + '</li>');
		}
	}
}

function unloadMenu()
{
	if(MENU_COUNTER >= 30)
		MENU_COUNTER = 1;
}



/*  new functions go here ^ */


/*=======================*
 * Functions to call  /\ *
 *=======================*
 * Calls to functions \/ *
 *=======================*/
$(function()
{
	if($([]).jdMenu)
	{
		$('ul.jd_menu').jdMenu({onShow: loadMenu, onHide: unloadMenu});
		$('ul.jd_menu_vertical').jdMenu({onShow: loadMenu, onHide: unloadMenu});
	}

	//late-load quicktime movies, since IE insists they must load completely before DOM-ready is called o\__/o
	$('noscript.active-content-embed').each(lateLoadActiveContent);
    	
    //IE background image flicker fix
    if($.browser.msie)
    {
        try { document.execCommand("BackgroundImageCache", false, true); }
	    catch(err) {}
    };
});



/*=======================*
 * for drop down menus
 *=======================*/
 
 
	jQuery(document).ready(function($){
	function makeHoverOn()
	{
		$(this).addClass('hover');
	};
	function makeHoverOff()
	{
		$(this).removeClass('hover');
	};
	$('.subtabs').children().hover(makeHoverOn, makeHoverOff);
});