// environment variables
// ------------------------------

var browser = navigator.appName;
var bVersion = parseInt(navigator.appVersion);
var IE = document.all ? true : false;
var NS4 = (document.layers) ? true : false;
var Mac = (navigator.appVersion.indexOf("Mac") != -1);
var Safari = (navigator.userAgent.indexOf("Safari")!=-1);
var Explorer = (navigator.userAgent.indexOf("MSIE")!=-1);
var javaScriptPopUpInclude = "/shared-static/scripts/jquery.thickbox.js";
var COUNTRYSELECT;

// changes alerts into console logs for FF
function log() {
	if(window.console)
		console.debug.apply(console, arguments);
    else
        alert([].join.apply(arguments, [' ']));
}

function setSelect(field, value)
{
  for (var i = 0; i < field.options.length; i++) {
     if (field.options[i].value == value) field.options[i].selected = true;
     else field.options[i].selected = false;
  }
}

function unicodeToAscii(input)
{
  var output = input;
  output = output.replace(/\u00E1|\u00E4|\u00E2|\u00E3|\u00E5/g, "a");
  output = output.replace(/\u00E6/g, "ae");
  output = output.replace(/\u00E7/g, "c");
  output = output.replace(/\u00E9|\u00EB|\u00EA/g, "e");
  output = output.replace(/\u00ED|\u00EF|\u00EE/g, "i");
  output = output.replace(/\u00F3|\u00F6|\u00F4|\u00F5/g, "o");
  output = output.replace(/\u0153/g, "oe");
  output = output.replace(/\u00FA|\u00FC|\u00FB/g, "u");
  output = output.replace(/\u00F1/g, "n");
  output = output.replace(/\u00C1|\u00C4|\u00C2|\u00C3|\u00C5/g, "A");
  output = output.replace(/\u00C6/g, "Ae");
  output = output.replace(/\u00C7/g, "C");
  output = output.replace(/\u00C9|\u00CB|\u00CA/g, "E");
  output = output.replace(/\u00CD|\u00CF|\u00CE/g, "I");
  output = output.replace(/\u00D3|\u00D6|\u00D4|\u00D5/g, "O");
  output = output.replace(/\u0152/g, "Oe");
  output = output.replace(/\u00DA|\u00DC|\u00DB/g, "U");
  output = output.replace(/\u00D1/g, "N");
  for (var i = 0; i < output.length; i++) {
    if (output.charCodeAt(i) > 127) {
      output = output.substring(0, i) + "?" + output.substring(i + 1);
    }
  }
  return output;
}

function validateAsciiFields() {
  for (var i = 0; i < arguments.length; i++) {
    var text = unicodeToAscii(arguments[i].value);
    if (text != arguments[i].value) {
      alert('Unsupported character(s) were found in field \'' + arguments[i].name + '\' and will be replaced with plain text equivalents (where available). Please review the changes and try again.');
      arguments[i].value = text;
      arguments[i].focus();
      arguments[i].select();
      return false;
    }
  }
  return true;
}

function validateEmail(field) {
  var input = trim(field.value);
  if (input.length == 0) return true;
  var invalidRegExp = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
  var validRegExp = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
  if (!invalidRegExp.test(input) && validRegExp.test(input)) {
    return true;
  }
  alert('\'' + input + '\' is not a valid e-mail address.');
  field.focus();
  field.select();
  return false;
}

function validateNonempty(field, label)
{
  var input = trim(field.value);
  if (input.length > 0) return true;
  alert('Please fill in the \'' + label + '\' field.');
  field.focus();
  field.select();
  return false;
}

function trim(input) {
   return input.replace(/^\s*/, '').replace(/\s*$/, '');
}

function validateCheckPair(field1, field2, label)
{
	if (field1.checked || field2.checked)
	{
		return true;
	}
	alert("Please choose one or both of the options for '" + label + "'");
	return false;

}

function validateNonnegativeInteger(field) {
  for (var i = 0; i < field.value.length; i++) {
     var c = field.value.charAt(i);
     if (c < '0' || c > '9') {
       alert('Quantities must be whole numbers greater than or equal to zero.');
       field.focus();
       field.select();
       return false;
    }
  }
  return true;
}

function getAddressFieldArray(form) {
   return (new Array(form.nametitle, form.firstname, form.lastname, form.department, form.institution, form.address1, form.address2, form.city, form.state, form.zip, form.region));
}

function validateInteger(qunatity, field){
	qunatity = trim(qunatity);
	if(isNaN(qunatity) || qunatity < 1){
		field.value = "";
		alert("" + qunatity + ", is either not a number or a number greater than zero, please provide a numerical quantity");
	}
}


function formContainsDelimiter(fieldArray) {
  for (var i = 0; i < fieldArray.length; i++) {
    if (fieldArray[i].type == 'select-one') continue;
    if (fieldArray[i].value.indexOf('|') != -1) {
      alert('Reserved character | not allowed. Please remove and try again.');
      fieldArray[i].focus();
      fieldArray[i].select();
      return true;
    }
  }
  return false;
}

function formSave(fieldArray, cookieName) {
  if (formContainsDelimiter(fieldArray)) return false;
  var value = '';
  for (var i = 0; i < fieldArray.length; i++) {
    if (fieldArray[i].type == 'select-one') value += fieldArray[i].options[fieldArray[i].selectedIndex].value;
    else value += fieldArray[i].value;
    value += '|';
  }
  setCookie(cookieName, value);
  return true;
}

function formRecall(fieldArray, cookieName) {
  var value = getCookie(cookieName);
  if (value.length == 0) return;
  for (var i = 0; i < fieldArray.length; i++) {
    var temp = value.substring(0, (j = value.indexOf('|')));
    value = value.substring(j + 1);
    if (fieldArray[i].type == 'select-one') setSelect(fieldArray[i], temp);
    else fieldArray[i].value = temp;
  }
}

function setCookie(name, value)
{
  var expires = new Date();
  expires.setTime(expires.getTime() + (1000 * 60 * 60 * 24 * 31));
  document.cookie = name+ '=' + escape(value) + '; path=/; expires=' + expires.toGMTString() + '; domain=.invitrogen;';
}

function getCookie(name)
{
  var cname = name + '=';
  var dc = document.cookie;
  if (dc == null) return '';
  if (dc.length > 0)
  {
    var begin = dc.indexOf(cname);
    if (begin != -1)
    {
      begin += cname.length;
      var end = dc.indexOf(';', begin);
      if (end == -1) end = dc.length;
      return unescape(dc.substring(begin, end));
    }
  }
  return '';
}

function getValueFromCookie(cookieValue, index){
	var value = "";
	if(cookieValue != null){
		var cookie_ary = cookieValue.split(";");
		var pair = cookie_ary[index].split(":");
		return value = pair[1];
	}
		return value;
}

function getCustomerName(cookieValue){
	return getValueFromCookie(cookieValue, 0);
}

function getUserLogin(cookieValue){
	return getValueFromCookie(cookieValue, 1);
}

function getCustomerCompany(cookieValue){
	return getValueFromCookie(cookieValue, 2);
}

function getCustomerType(cookieValue){
	return getValueFromCookie(cookieValue, 3);
}

function getAccountType(cookieValue){
	return getValueFromCookie(cookieValue, 4);
}

function getCountryCurrency(cookieValue){
	return getValueFromCookie(cookieValue, 5);
}

function getCustomerCGID(cookieValue){
	return getValueFromCookie(cookieValue, 6);
}

function getShipToNumber(cookieValue){
	return getValueFromCookie(cookieValue, 7);
}

function getCountryName(cookieValue){
	return getValueFromCookie(cookieValue, 8);
}

function getRegionName(cookieValue){
	return getValueFromCookie(cookieValue, 9);
}

function getOrderId(cookieValue){
	return getValueFromCookie(cookieValue, 0);
}

function getCartItems(cookieValue){
	return getValueFromCookie(cookieValue, 1);
}

function getUserCountryCode(){
	return getCookie("CK_ISO_CODE");
}

function triggerCountrySelect(booleanSelect){
	COUNTRYSELECT = booleanSelect;
}

function isCountrySelectRequired(){
	return COUNTRYSELECT;
}

function setUserCountryCode(value){
	setCookie("CK_ISO_CODE", value);
}


function getItemFromArray(itemArray, code){
	var returnValue, i;

	for (i in itemArray) {
	  if(i == code){
	  	returnValue = itemArray[i];
	  }
	}
	return returnValue;
}

function getJSInclude(src, url) {
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.onreadystatechange= function () {
	      if (this.readyState == 'complete' || this.readyState == 'loaded') tb_show(null, url, null);
  }
  if(/Safari/i.test(navigator.userAgent)){ //Test for Safari
	  var _timer=setInterval(function(){
	  if(/loaded|complete/.test(document.readyState)){
	    clearInterval(_timer)
	    tb_show(null, url, null) // call target function
	  }}, 10)
	}
   script.onload = function() {tb_show(null, url, null);}
   script.src = src;
   document.getElementsByTagName("body")[0].appendChild(script);
}

function rollOn(img,isForm,formObject){
	newImg=eval(img+"On.src")
	if (isForm==1)
		orig=formObject;
	else
		orig=eval("document."+img);
	orig.src=newImg
}

function rollOff(img,isForm,formObject){
	newImg=eval(img+"Off.src")
	if (isForm==1)
		orig=formObject;
	else
		orig=eval("document."+img);
	orig.src=newImg
}

//WCM Only Functions
function setOminitureUserValues(customer_info){
	var countryCurrency = ""
	var countryCode = "";
	var pageName = "";
	var userLogin = "";
	var accountType = "";
	var customerCGID = "";
	var customerType = "";
	var countryRegion = "";
	var countryName = "";

	if(customer_info.length > 1){
		countryCurrency = getCountryCurrency(customer_info);
		countryCode = getUserCountryCode();
		userLogin = getUserLogin(customer_info);
		accountType = getAccountType(customer_info);
		customerCGID = getCustomerCGID(customer_info);
		customerType = getCustomerType(customer_info);
		countryRegion = getRegionName(customer_info);
		countryName = getCountryName(customer_info);
	}

	s.currencyCode=''+ countryCurrency +'';
	s.prop1=''+ countryName +'';
	s.eVar1='' + countryName + '';
	s.prop2=''+ countryRegion +'';
	s.eVar2=''+ countryRegion +'';
	s.prop25=''+ userLogin +'';
	s.eVar25=''+ userLogin +'';
	s.prop26=''+ accountType +'';
	s.eVar26=''+ accountType +'';
	s.prop28=''+ customerCGID +'';
	s.eVar28=''+ customerCGID +'';
	s.prop29=''+ customerType +'';
	s.eVar29=''+ customerType +'';

}

function performCountrySelect(locationHref, javaScriptSource, countrySelectURL, enforceCountrySelect, regionalized){
   	locationHref = locationHref.toLowerCase();
	if (locationHref.indexOf("invitrogen.com") != -1){
		if((getUserCountryCode() == null) || (getUserCountryCode() == '')){
			if(isCountrySelectRequired() == true){
				getJSInclude(javaScriptSource, countrySelectURL);
			} else if (enforceCountrySelect == "yes" || regionalized == "yes") {
				getJSInclude(javaScriptSource, countrySelectURL);
			}
		}
	}
}

function getRegionalizedHandle(context, handle){
	return context + masterHandle + ".regionalized.html";
}

function getAjaxPage(url, containerid){
	var xmlHttp;

	if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
    	xmlHttp = new XMLHttpRequest();
    }

	xmlHttp.onreadystatechange = function(){
	 	loadpage(xmlHttp, containerid);
	}

	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function loadpage(xmlHttp, containerid){
	if (xmlHttp.readyState == 4 && (xmlHttp.status==200 || window.location.href.indexOf("http")==-1)){
		document.getElementById("" + containerid + "").innerHTML = xmlHttp.responseText;
	}
}


function createProductCatalog() {

		log("global createProductCatalog");

		$('.productCatalog').tabs({ fxFade: false, fxSpeed: 'fast' })
         
        var navHeight = $('div.productCatalog ul.tabs-nav').height();
        var initialHeight = $('#firsttab').height();

        if(navHeight >= initialHeight) {
            var initWrapHeight = navHeight;
        } else {
            var initWrapHeight =  initialHeight;
        }

        $('div.productCatalog').height(initWrapHeight);

        // get the new height when you click on something
        $(".productCatalog ul.tabs-nav li a").click(function(){            
            var containerID = $(this).attr("href");
            var containerHeight = $(containerID).height();

                if(navHeight >= containerHeight) {
                    var wrapHeight = navHeight;
                } else {
                    var wrapHeight = containerHeight;
                }

                $('div.productCatalog').height(wrapHeight);
        });
}

function showPopupMessage(pageURL, height, width){
   
   pageURL += "&amp;" + "keepThis=true&amp;&amp;TB_iframe=true&amp;";
   pageURL += "height=" + height + "&amp;";
   pageURL += "width=" + width;
   getJSInclude(javaScriptPopUpInclude, pageURL);
   
}
