
function openWindow(page, name, width, height) {
    var newWindow = window.open(page, name, "width=" + width +",height="+ height +",titlebar,scrollbars,resizable");
    newWindow.focus();
}
function openWindowSized(page, name, width, height) {
    var newWindow = window.open(page, name, "width=" + width +",height="+ height +",titlebar,scrollbars,resizable");
    newWindow.focus();
}

function openWindow(page, name, features) {
    var newWindow = window.open(page, name, features);
    newWindow.focus();
}

function openNew(page) {
    var newWindow = window.open(page, '_new');
    newWindow.focus();
}

function openNew(page, name) {
    var newWindow = window.open(page, name);
    newWindow.focus();
}

function linkEmail(user, domain, text) {
	var link = user + '@' + domain;
	if (!text) text = link;
	document.write('<a href=mailto:' + link + '>' + text + '</a>');
}


function checkStandardsCompliance() {
	var bName = getBrowserName();
	var bVer = getBrowserVersion(bName);
	if (bName == "Mozilla") {
		if (bVer >= 1) return true;
		else return false;
	} else {
		if (bVer >= 5) return true;
		else return false;
	}
}

function getBrowserName() {
	var mAppName = navigator.appName;
	var mUserAgent = navigator.userAgent;
	if (mUserAgent.indexOf("Opera") != -1) return "Opera";
	else if (mAppName == "Netscape") {
		if (parseInt(navigator.appVersion) < 5) return "Netscape";
		else if (mUserAgent.indexOf("Netscape") != -1) return "Netscape";
		else return "Mozilla";
	}
	else return mAppName;
}

function getBrowserVersion(bName) {
	var mUserAgent = navigator.userAgent;
	if (bName == "Microsoft Internet Explorer") {
		return parseInt(mUserAgent.slice(mUserAgent.indexOf("MSIE") + 5));
	} else if (bName == "Netscape") {
		return parseInt(mUserAgent.slice(mUserAgent.indexOf("Netscape") + 8));
	} else if (bName == "Mozilla") {
		return parseInt(mUserAgent.slice(mUserAgent.indexOf("rv:") + 3));
	} else if (bName == "Opera") {
		return parseInt(mUserAgent.slice(mUserAgent.indexOf("Opera") + 6));
	} else {
		return parseFloat(navigator.appVersion);
	}
}

function getOS() {
	var OSName="Unknown";
	if (navigator.userAgent.indexOf("Win")!=-1) OSName="Windows";
	else if (navigator.userAgent.indexOf("Mac")!=-1) OSName="MacOS";
	else if (navigator.userAgent.indexOf("X11")!=-1) OSName="Unix";
	else if (navigator.userAgent.indexOf("Linux")!=-1) OSName="Linux";
	else if (navigator.userAgent.indexOf("SunOS")!=-1) OSName="SunOS";
	return OSName;
}

var searchIsDefault = true;
function checkSearch() {
	if (searchIsDefault) {
		document.getElementById("searchQuery").value = "";
		searchIsDefault = false;
	}
}

function expandDocSection(sectionId, doExpand) {
	var sectTitleOpen = document.getElementById(sectionId + "_open");
	var sectTitleClosed = document.getElementById(sectionId + "_closed");
	var sectDocs = document.getElementById("sect_" + sectionId);
	
	if (sectTitleOpen != null)
		sectTitleOpen.style.display = (doExpand == true ? 'block' : 'none');
	if (sectTitleClosed != null)
		sectTitleClosed.style.display =  (doExpand == false ? 'block' : 'none');
	if (sectDocs != null)
		sectDocs.style.display = (doExpand == true ? 'block' : 'none');
}


// Used for print preview of pages which have a printer-friendly version
function printPreview(blnPreview) {
	var thisURL = window.location.href;
	var pfURL = thisURL + "#printerFriendly";
	var newWin = window.open(pfURL, "printPreview", "resizable=yes, scrollbars=yes, menubar=yes");
	newWin.focus();
}

function checkPrinterFriendly() {
	if ( window.location.href.indexOf("printerFriendly") >= 0 ) {
		// Manually implement the same display characteristics of the print stylesheet.
		document.getElementById("pageHeader").style.display = "none";
		document.getElementById("container").style.display = "none";
		document.getElementById("pageFooter").style.display = "none";
		document.getElementById("printerFriendly").style.display = "block";
		var tOut = setTimeout("window.print()", 200);
	}
}


// Random Survey function

    function randPopUp(svyId, svyPath) {
		var argv = randPopUp.arguments;  
		var argc = randPopUp.arguments.length;
		
		if ( (svyId == null) || (svyPath == null) )
			return;
		
		var mgn = (argc > 2) ? argv[2] : 2;
		var top = (argc > 3) ? argv[3] : 3;
		var winw = (argc > 4) ? argv[4] : 400;
		var winh = (argc > 5) ? argv[5] : 650;
		
        var x = GetCookie("svystkn");
        if (x!=null) {
			// The "/" character is a spacer so that SV11 won't trigger a search for the SV1 cookie
            if (-1 != x.indexOf(svyId + "/"))
                return;
        } else {
            x = new String("");
        }
		
        var nbr = Math.round(Math.random() * top);                
		
        if (nbr == mgn) {
            x += "" + svyId + "/";
            SetCookie("svystkn", x, exp);
            openWindow("" + svyPath, "CirrusLogicSurvey", winw, winh);
        }
    }


// Cookie functions - These scripts and many more ara available free online at The JavaScript Source!! http://javascript.internet.com

	function GetCookie (name) {  
		var arg = name + "=";  
		var alen = arg.length;  
		var clen = document.cookie.length;  
		var i = 0;  
		while (i < clen) {
			var j = i + alen;    
			if (document.cookie.substring(i, j) == arg)      
				return getCookieVal (j);    
			i = document.cookie.indexOf(" ", i) + 1;    
			if (i == 0) break;   
		}  
		return null;
	}
	
	function SetCookie (name, value) {  
		var argv = SetCookie.arguments;  
		var argc = SetCookie.arguments.length;  
		var expires = (argc > 2) ? argv[2] : null;  
		var path = (argc > 3) ? argv[3] : null;  
		var domain = (argc > 4) ? argv[4] : null;  
		var secure = (argc > 5) ? argv[5] : false;  
		document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
	}
	
	function DeleteCookie (name) {  
		var exp = new Date();  
		exp.setTime (exp.getTime() - 1);   
		var cval = GetCookie (name);  
		document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
	}
	
	var expDays = 30;
	var exp = new Date(); 
	exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
	
	function amt() {
		var count = GetCookie('count')
		if(count == null) {
			SetCookie('count','1')
			return 1
		} else {
			var newcount = parseInt(count) + 1;
			DeleteCookie('count')
			SetCookie('count',newcount,exp)
			return count
		}
	}
	
	function getCookieVal(offset) {
		var endstr = document.cookie.indexOf (";", offset);
		if (endstr == -1)
			endstr = document.cookie.length;
		return unescape(document.cookie.substring(offset, endstr));
	}

	
/* THANKS to David Flanagan (JavaScript: The Definitive Guide, O'Reilly) */
/*
 * This function parses comma-separated name=value argument pairs from
 * the query string of the URL. It stores the name=value pairs in 
 * properties of an object and returns that object.
 */

function getArgs(  ) {
    var args = new Object(  );
    var query = location.search.substring(1);     // Get query string
    var pairs = query.split(",");                 // Break at comma
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');          // Look for "name=value"
        if (pos == -1) continue;                  // If not found, skip
        var argname = pairs[i].substring(0,pos);  // Extract the name
        var value = pairs[i].substring(pos+1);    // Extract the value
        args[argname] = unescape(value);          // Store as a property
        // In JavaScript 1.5, use decodeURIComponent(  ) instead of unescape(  )
    }
    return args;                                  // Return the object
}


function constrainImg(image, maxwidth, maxheight) {
	if (image != null) {
		
		if ( maxwidth != null && image.width > maxwidth ) {
			if ( maxheight == null || image.width >= (image.height * maxwidth / maxheight) ) {
				// Adjust width
				image.style.width = maxwidth + "px";
			} else {
				// Adjust height
				image.style.height = maxheight + "px";
			}
			
		} else if ( maxheight != null && image.height >= maxheight ) {
				// Adjust height
				image.style.height = maxheight + "px";
		}
		// Otherwise, the image is already the right size - do nothing.
	}
}


// This is used in the global nav to set the correct search tab options
function setSearchTab(tab) {
	if (tab != null) {
		var curTab = (document.curTab != null ? document.curTab : "keyword");
		if ( curTab != tab ) {
			var keyTab = document.getElementById("searchTabKey");
			var parTab = document.getElementById("searchTabPar");
			var sform = document.getElementById("searchForm");
			var sfc = document.getElementById("searchFormContents");
			
			if ( tab == "param") {
				keyTab.className="searchTabUnsel";
				parTab.className="searchTabSel";
				
				document.oldSFC = sfc.innerHTML;
				
				if (document.newSFC == null) {
					var ih = "<select style=\"width: 160px;\" name=\"technology\" id=\"technologyList\" onchange=\"paramSearchWindow(this.value); return true;\">";
					ih = ih + "<option value=\"0\">Please select...</option>";
					ih = ih + "</select>";
					sfc.innerHTML = ih;
				} else {
					sfc.innerHTML = document.newSFC;
				}
				sfc.className = "searchPrompt";
				
				// Note: in IE you can't set the "action" attribute of a form that also has a child element named "action", so we change the attribute AFTER we've swapped the internal html.
				sform.action = "/dispatch/forms/my/srch/results.jsp";
				buildTechnologySelect();	
			} else {
				keyTab.className="searchTabSel";
				parTab.className="searchTabUnsel";
				
				document.newSFC = sfc.innerHTML;
				
				sform.action = "/dispatch/forms/my/srch/results.jsp";
				sfc.innerHTML = document.oldSFC;
				sfc.className = "searchPrompt";
			}
			document.curTab = tab;
		}
	}
}


var isDefaultUrl = true;
function buildTechnologySelect() {
	// The /dispatch path doesn't work on local builds - so put in code for an alternate method
	if (isDefaultUrl)
		getXMLRequest(handleStateChange, '/dispatch/forms/pro/paramSearch/getTechsWithTableXML.do');
	else
		getXMLRequest(handleStateChange, '/bweb/forms/pro/paramSearch/getTechsWithTableXML.do');
}

function getXMLRequest(handler, url) {
	// branch for native XMLHttpRequest object (including IE7 now)
	if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
		// IE7 doesn't support "overrideMimeType()", so check for it...
		if (xmlHttp.overrideMimeType)
			xmlHttp.overrideMimeType("text/xml");
		xmlHttp.onreadystatechange = handler;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
		
	// branch for IE6-/Windows ActiveX version
	} else if (window.ActiveXObject) {
		isIE = true;
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		if (xmlHttp) {
			xmlHttp.onreadystatechange = handler;
			xmlHttp.open("GET", url, true);
			xmlHttp.send();
		}
	}
}

// These are for the Technology Select/parametric search list
function handleStateChange() {
	// only if req shows "loaded"
	if (xmlHttp.readyState == 4) {
		// only if "OK"
		if (xmlHttp.status == 200) {
			consumeTechsXML(xmlHttp.responseXML);
		} else {
			if (isDefaultUrl) {
				// If the default (/dispatch) url path doesn't work, try again without it.
				isDefaultUrl = false;
				buildTechnologySelect();
			} else {
				alert("Unable to load Parametric Search list.\n" +
					xmlHttp.statusText);
			}
		}
	}			
}

function consumeTechsXML(xmlDoc) {
	if (xmlDoc == null)   {
		return;
	}
	
	var root = xmlDoc.getElementsByTagName("technologies").item(0);
	var techOptions = new Array(root.childNodes.length);	
	
	var techSelect = document.getElementById("technologyList");
	techSelect.length = 0;
	
	for (var i = 0; i < root.childNodes.length; i++) {
		var tech = root.childNodes.item(i);
		var id = tech.getElementsByTagName("id").item(0).firstChild.nodeValue;
		var title = tech.getElementsByTagName("title").item(0).firstChild.nodeValue;
		
		var op = new Option(title, id);
		techSelect.options.add(op);	
	}
}

function paramSearchWindow(techId) {
	
	var width = '800';
	if (screen.availWidth >= 1024) {
		width = '1024';
	}
	
	document.getElementById("technologyList").selectedIndex = 0;	
	window.open('/dispatch/forms/pro/paramSearch/search.do?techId=' + techId, null, 'width=' + width + ', height=600, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no, status=yes, menubar=no');
}


// These are for the Google AdWords Conversion snippets
var strGawXmlPath = "http://www.cirrus.com/en/pubs/misc/";
function checkGAWCookie() {
	var gawFound = GetCookie("gAdWords");
	if (gawFound) {
		switch (gawFound) {
			case "registration":
				strGawXmlPath += "gawConversion_Registration.html";
				break;
			case "datasheet":
				strGawXmlPath += "gawConversion_Datasheets.html";
				break;
			case "podcast":
				strGawXmlPath += "gawConversion_Podcast.html";
				break;
			case "prodsearch":
				strGawXmlPath += "gawConversion_ProdSearch.html";
				break;
			/* NOTE: the Buy Now case is handled directly on the Buy Now distyLineItems page.
			case "buynow":
				strGawXmlPath += "gawConversion_BuyNow.html";
				break;
			*/
		}
		loadGoogleAdWordsSnippet();
	}
}
function loadGoogleAdWordsSnippet() {
	var gawDiv = document.getElementById("adWordsFrame");
	if (gawDiv == null) {
		return;
	}
	gawDiv.src = strGawXmlPath;
	DeleteCookie('gAdWords');
}

function trimStr(sString) {
	if (sString != null) {
		while (sString.substring(0,1) == ' ') {
			sString = sString.substring(1, sString.length);
		}
		while (sString.substring(sString.length-1, sString.length) == ' ') {
			sString = sString.substring(0,sString.length-1);
		}
	}
	return sString;
}

// This is for Google Analytics
function recordOutboundLink(link, category, action) {
  try {
    var pageTracker=_gat._getTracker("UA-XXXXX-X");
    pageTracker._trackEvent(category, action);
    if ( (link.target != null) && (link.target != '') ) {
    	setTimeout('window.open("' + link.href + '", ' + link.target + '")', 100)
    } else {
    	setTimeout('document.location = "' + link.href + '"', 100);
    }
  }catch(err){}
}



// Utility function to limit a textarea field to a specified character length.
// The function is best called from onKeyUp and/or onChange events
function checkTextAreaLength(ta, max, ev, span) {
	var key, kChar, rem, spnRem, doCheck = true; rtn = true;
	
	// Store the array of key IDs that will short-circuit the length checking
	var arrchars = new Array(8, 46, 35, 36, 37, 38, 39, 40, 16, 0); // 8=backspace; 46=delete; 35-40=home/end/arrow keys; 16=shift; not sure what 0 is, but Donovan had it in there - possibly a no-key event
	
	// Make sure a text area field was passed (or something with a value attribute) - if not, no point to this function
	if ((ta == null) || (ta.value == null))
		return;
	// If no max value was passed, then the field can't be too long
	if (max == null)
		return true;
	
	// Capture the key-press for the current browser event
	if (window.event)
		key = ev.keyCode;
	else
		key = ev.which;
	
	// If we want to short-circuit the length checking for some keys, check here
	for (i = 0; i < arrchars.length; i++) {
		if (key == arrchars[i]) {
			doCheck = false;
			break;
		}
	}
	
	// If we're not skipping...
	if (doCheck) {
		
		// Check if the field length is longer than the max - if so, truncate the field value, cancel the event and return false
		if (ta.value.length > max) {
			ta.value = 	ta.value.substr(0, max);
			ev.cancelBubble = true;
			ev.returnValue = false;
			rtn = false;
		}
	}
	
	// If a span/object ID was passed, get it and replace the contents with the characters remaining before hitting the max
	spnRem = document.getElementById(span);
	if (spnRem != null) {
		spnRem.innerHTML = max - ta.value.length;
	}
	
	return rtn;
}

/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008
	
	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}

function appendCampId(url) {

	var retval = url;
	
	var qs = new Querystring();
	var campId = qs.get("adCampId");
	var campPro = qs.get("adCampPro");
	
	if (campId) {
		if (retval == null) {
			retval = "adCampId=" + campId;
		} else if (retval.indexOf("?") > -1) {
			retval = retval + "&adCampId=" + campId;
		} else {
			retval = retval + "?adCampId=" + campId;
		}
	}
	if (campPro) {
		if (retval == null) {
			retval = "adCampPro=" + campPro;
		} else if (retval.indexOf("?") > -1) {
			retval = retval + "&adCampPro=" + campPro;
		} else {
			retval = retval + "?adCampPro=" + campPro;
		}
	}
	
	return retval;
}
