function checkBrowser(insert){
	var browser_name = BrowserDetect.browser;//navigator.appName;
	var browser_version = BrowserDetect.version;//navigator.appVersion;
	var platform = BrowserDetect.OS;//navigator.platform;
	
	if (browser_name=="Explorer"&&browser_version<=7){
		document.getElementById(insert).innerHTML= "We have detected you are using an out of date browser (Internet Explorer "+browser_version+"). You may experience errors in the site. Please update your browser if errors occur.";
//		document.getElementById(insert).innerHTML= "We have detected you are using "+browser_name+" "+browser_version;
	}else{
		document.getElementById(insert).style.display = 'none';
	}
	
	
	//alert("You are using "+browser_name+" (version "+browser_version+") on "+platform+"funciton inser is: "+result);
}


var BrowserDetect = { //use like BrowserDetect.browser, BrowserDetect.version, BrowserDetect.OS
	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",
			versionSearch: "Version"
		},
		{
			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.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();




jQuery.validator.addMethod(
  "selectNone",
  function(value, element) {
    if (element.value == "null")
    {
      return false;
    }
    else return true;
  },
  "Please select an option."
);
$.validator.addMethod(
	"greaterThanZero",
	function(value, element) {
		var the_list_array = $("#orderForm .item input:checked");
		return the_list_array.length > 0;
		}, 
		"Select at least one construct."
	);
	
function updateAddStock(){
 	if($("form[name=addstock] select[name=insertCatalogue]").attr('value')=="R\&D"){
		$("form[name=addstock] .rdonly").show();
		$("form[name=addstock] .licenseeonly").hide();
		$("form[name=addstock] .only-rd").attr("disabled", "")
		$("form[name=addstock] .only-licensee").attr("disabled", "disabled")
		$("form[name=addstock] label[for=insertCost]").html("Construct Cost Per Vial (USD)");
		
	} else {
		$("form[name=addstock] .rdonly").hide();
		$("form[name=addstock] .licenseeonly").show();
		$("form[name=addstock] .only-licensee").attr("disabled", "")
		$("form[name=addstock] .only-rd").attr("disabled", "disabled")
		$("form[name=addstock] label[for=insertCost]").html("Construct indicative price (USD)");
		
	}	
}

$(document).ready(function(){
  		$(".validateForm").validate({
			rules: {
				moleculeSelect: "greaterThanZero"
			}
		});
		$('label.labelover').labelOver('over-apply');
		$("#popup").hide();
		$("a.toggle_popup").live("click",function(){
			$("#popup").toggle();
		});
		$(".people li").hide();
		$(".people li:first-child").show();
		$(".rdonly").hide();
		updateAddStock();
});
$(function() {
	// Simulates PHP's date function
	Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return(((this.getFullYear()%4==0)&&(this.getFullYear()%100!=0))||(this.getFullYear()%400==0))?'1':'0';},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':'+(Math.abs(this.getTimezoneOffset()%60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()%60));},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d")+"T"+this.format("H:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};
	
	$("#orderForm").bind("keypress", function(e) {
	             if (e.keyCode == 13) {
	                 return false;
	            }
	         });
	
	function updateLeadWarning(delpicker){
			new_date = delpicker.attr("value");
			limit = $("#lead strong").attr("title");
			alert("New: "+new_date+" | Limit: "+limit);
			if(Date.parse(new_date) < Date.parse(limit)) {
				$("#lead strong").html("Lead time of highlighted products are outside of specification. We will post our response in the correspondence section related to this order.");
			} else {
				$("#lead strong").html("");
			}
	}
	function checkLead(){
		$(".ordered .lead").each(function(){
					highest_lead = 0;
					lead = $(this).attr('title');
					if(lead > highest_lead) {
						highest_lead = lead;
					}
				});
				today = new Date();
				lead_date = new Date(today.getTime() + (highest_lead*24*60*60*1000));
				//$("#lead input").attr("value", lead_date.format("l, j F, Y"));
				$("#lead strong").attr("title", lead_date.format("l, j F, Y"));
				//$("#lead strong").html("");
				//$("#lead input").effect("highlight", {}, 3000);
				if(!$("#lead input").attr("value")){}
				else {
				new_date = $("#lead input").attr("value");
				$(".ordered .lead").each(function(){
							today = new Date();
							lead = new Date(today.getTime() + ($(this).attr('title')*24*60*60*1000));
							if(Date.parse(new_date) >= Date.parse(lead.format("l, j F, Y"))) {
								$(this).css("background", "none");
							} else {
								$(this).css("background", "yellow")
							}
						});
						limit = $("#lead strong").attr("title");
						if(Date.parse(new_date) >= Date.parse(limit)&&Date.parse(new_date) <= Date.parse(today.format("l, j F, Y"))) {
							$("#lead strong").html("");
						} else {
							$("#lead strong").html("Lead time of highlighted products are outside of specification. We will post our response in the correspondence section related to this order.");
							$("#lead strong").effect("highlight", {color: "#FFFF00" }, 3000);
							$("#lead input").effect("highlight", {color: "#FFFF00" }, 3000);
						}
					}
						
	}
    $('.delete').click(function() {
        var answer = confirm("Delete this item?")
        if (answer){
            return true;
        }
        else{
            return false;
        };
    });

	$("#lead input").change(function() {
		new_date = $(this).attr("value");
		limit = $("#lead strong").attr("title");
		if(Date.parse(new_date) >= Date.parse(limit)) {
			$("#lead strong").html("");
		} else {
			$("#lead strong").html("Lead time of highlighted products are outside of specification. We will post our response in the correspondence section related to this order.");
			$("#lead strong").effect("highlight", {color: "#FFFF00" }, 3000);
			$("#lead input").effect("highlight", {color: "#FFFF00" }, 3000);
			
			
		}
		$(".ordered .lead").each(function(){
					today = new Date();
					lead = new Date(today.getTime() + ($(this).attr('title')*24*60*60*1000));
					if(Date.parse(new_date) >= Date.parse(lead.format("l, j F, Y"))) {
						$(this).css("background", "none");
					} else {
						$(this).css("background", "yellow")
					}
				});
	});

	$('.existing_licensees').click(function() {
		confirm("Coming soon")
	});
	$("#orderForm .item input[type=radio]").click(function(){
				var cat = $(this).val();
				var cartnum = cat.replace(/&/g,"-amp-");
		        // If checked
		        $("input[type=radio]").each( function() {
					if ($("#orderForm #"+cartnum+"_item input[type=radio]").is(":checked"))
			        {
						//remove all
						$("#orderForm .cart tr").removeClass("ordered");
						$("#orderForm .cart tr input.vialNumber").removeClass("required");
						$("#orderForm .cart tr input.vialNumber").removeClass("digits");
			            //show the hidden div
						$("#orderForm #"+cartnum+"_order").addClass("ordered");
						$("#orderForm #"+cartnum+"_order input.vialNumber").addClass("required");
						$("#orderForm #"+cartnum+"_order input.vialNumber").addClass("digits");
						checkLead();
						
						//get price
						catnum = cat;
						q = parseInt($("#orderForm #"+cartnum+"_order input.vialNumber").val());
						catalogue = $("#catalogue_code").html();
						subcatalogue = $("input[name=orderType]").val();						
						$.ajax({
						   async: false,
						   type: "POST",
						   url: "check_price.php",
						   data: "catnum="+cartnum+"&catalogue="+catalogue+"&subCatalogue="+subcatalogue+"&quantity="+q,
						   success: function(msg){
						     	$("#"+cartnum+"_order .price").html(msg).parent().children("input").val(msg);
								}
						 });
						p = $("#"+cartnum+"_order .price").html();									
						$("#"+cartnum+"_order .subtotal").html(p*q+".00");
						total = 0;
						$(".ordered .subtotal").each(function() {
							st = parseInt($(this).text());
							total = total + st;
						});
						$(".total").html(total+".00");
			        }
			        else
			        {      
			            //otherwise, hide it 
						if(confirm("Drop from cart?")){
						}
			        }
			}); //end each
			
	});
	$("#orderForm .item input[type=checkbox]").click(function(){
				var num = $(this).val().replace(/&/g,"-amp-");
				var cartnum = $(this).val().replace(/&/g, "");
		        // If checked
					if ($(this).is(":checked"))
			        {
			            //show the hidden div
						$("#"+cartnum+"_order").addClass("ordered");
						$("#"+cartnum+"_order input.vialNumber").addClass("required");
						
						//get price
						catnum = num;
						q = parseInt($("#orderForm #"+catnum+"_order input.vialNumber").val());
						catalogue = $("#catalogue_code").html();
						subcatalogue = $("input[name=orderType]").val();
						$.ajax({
						   async: false,
						   type: "POST",
						   url: "check_price.php",
						   data: "catnum="+catnum+"&catalogue="+catalogue+"&subCatalogue="+subcatalogue+"&quantity="+q,
						   success: function(msg){
						     	$("#"+catnum+"_order .price").html(msg).parent().children("input").val(msg);
								}
						 });
						p = $("#"+catnum+"_order .price").html();									
						$("#"+catnum+"_order .subtotal").html(p*q+".00");
						total = 0;
						$(".ordered .subtotal").each(function() {
							st = parseInt($(this).html());
							total = total + st;
						});
						$(".total").html(total+".00");
						checkLead();
						
			        }
			        else
			        {      
			            //otherwise, hide it 
						if(confirm("Drop from cart?")){
							$("#"+cartnum+"_order").removeClass("ordered");
							$("#"+cartnum+"_order input.vialNumber").removeClass("required");
							total = 0;
							$(".ordered .subtotal").each(function() {
								st = parseInt($(this).html());
								total = total + st;
							});
							$(".total").html(total+".00");
							checkLead();
		
						} else {
							$(this).attr('checked', true);
						}
			        }
	});
	$("#orderForm .order select").change(function() {
		q = $(this).val();
		cat = $(this).parent().parent().attr('id');
		p = parseInt($("#"+cat+" input[name=ppv]").attr('value'));
		$("#"+cat+" span").html(p*q+".00");
		total = 0;
		$(".ordered .subtotal").each(function() {
			st = parseInt($(this).html());
			total = total + st;
		});
		$(".total").html(total+".00");
	});
	$("#orderForm input.vialNumber").change(function(){
		/*
		$catnum = $_POST['catnum'];
		$quantity = $_POST['quantity'];
		$catalogue = $_POST['catalogue'];      			//NEED
		$subCatalogue = $_POST['subCatalogue'];			//NEED
		*/
		catnum = $(this).parent().parent().parent().attr('id');
		q = parseInt($(this).val());
		quantity = parseInt($(this).val());
		catalogue = $("#catalogue_code").html();
		subcatalogue = $("input[name=orderType]").val();
		$.ajax({
		   async: false,
		   type: "POST",
		   url: "check_price.php",
		   data: "catnum="+catnum+"&catalogue="+catalogue+"&subCatalogue="+subcatalogue+"&quantity="+q,
		   success: function(msg){
		     $("#"+catnum+" .price").html(msg);
		   }
		 });
		p = parseInt($("#"+catnum+" .price").html());
		$("#"+catnum+" .subtotal").html(p*q+".00");
		total = 0;
		$(".ordered .subtotal").each(function() {
			st = parseInt($(this).html());
			total = total + st;
		});
		$(".total").html(total+".00");
	});
	$("#orderForm .people input[type=checkbox]").click( function(){
				var email = $(this).val();
		        // If checked
						$("#orderForm .people li[title="+email+"]").toggle();
	});
	$("form[name=addstock] select[name=insertCatalogue]").change(function() {
		if($(this).attr('value')=="R\&D"){
			$("form[name=addstock] .rdonly").show();
			$("form[name=addstock] .licenseeonly").hide();
			$("form[name=addstock] .only-rd").attr("disabled", "")
			$("form[name=addstock] .only-licensee").attr("disabled", "disabled")
			$("form[name=addstock] label[for=insertCost]").html("Construct Cost Per Vial (USD)");
			
		} else {
			$("form[name=addstock] .rdonly").hide();
			$("form[name=addstock] .licenseeonly").show();
			$("form[name=addstock] .only-licensee").attr("disabled", "")
			$("form[name=addstock] .only-rd").attr("disabled", "disabled")
			$("form[name=addstock] label[for=insertCost]").html("Construct indicative price (USD)");
			
		}
	});
	$("form[name=addstock]").submit(function() {
		master = $("input[name=master]").val();
		name = $("select[name=insertConstruct] :selected").text();
		name_master = $("input[name=insertName]").val();
		catnum = $("input[name=insertCatnum]").val();
		suffix = $("select[name=insertCatnumSuffix]").val();
		cat = $("select[name=insertCatalogue]").val();
		subcat = $("select[name=insertSubCatalogue]").val();
		vialsize = $("input[name=insertVialSize]").val();
		cost = $("input[name=insertCost]").val();
		stock = $("input[name=insertStock]").val();
		pricingstructure = $("textarea[name=insertPriceStructure]").val();
		minimumorder = $("input[name=insertMinimumOrder]").val();
if(master=="yes") {
		message = "Please check the information you have submitted, click OK to proceed."
		message += "\n\nName: "+name_master;
		message += "\nCatalogue #: "+catnum;
		message += "\nPricing Structure: "+pricingstructure;	
}else {
		message = "Please check the information you have submitted, click OK to proceed."
		message += "\n\nName: "+name;
		message += "\nCatalogue #: "+catnum+"-"+vialsize+"-"+suffix;
		message += "\nCatalogue: "+cat;
		message += "\nSub-Catalogue: "+subcat;
		message += "\nVial Size: "+vialsize+"mg";

		if($("form[name=addstock] select[name=insertCatalogue]").attr("value")=="R\&D"){
			message += "\nStock: "+stock;
			message += "\nCost: $"+cost;
		}else if($("form[name=addstock] select[name=insertCatalogue]").attr("value")!="R\&D"){
			message += "\nMinimum Order: "+minimumorder;
			message += "\nPricing Structure: "+pricingstructure;
			
		}
		
		
}
		
		if(confirm(message)){
			
		}else{
			event.preventDefault()
		};
	});
	$("form[name=labelgen] select").change(function() {
		if($(this).attr('value')==""){
			$("form[name=labelgen] input[name=catnumInput]").attr('value', '');
			$("form[name=labelgen] .manual").show();
			$("form[name=labelgen] input[name=catnumInput]").attr('readonly', '');
		} else {
			$("form[name=labelgen] input[name=catnumInput]").attr('value', $("form[name=labelgen] select option:selected").attr('id'));
			$("form[name=labelgen] input[name=catnumInput]").attr('readonly', 'readonly');
			$("form[name=labelgen] .manual").hide();
		}
	});
});

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-11378169-3']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
  })();
