var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

function loadingImage(msg) {
	if (msg == '' || msg == 'undefined' || msg == null) { 
		txtmsg="Retrieving Shipping Rates..."
	} else {
		txtmsg=msg;
	}
	return '<div style="text-align:center;margin-top:180px;"><img align="center" style="text-align:center;padding-bottom:5px;" alt="loading" src="../webimages/generic/ajax-loader.gif" border="0"/><br><span class="caption">'+txtmsg+'</span></div>';
	
}

function topBar() {	
	return '<div id="lbContent"><div id="titlebar"><a href="#" class="lbAction closebutton" rel="deactivate">X</a></div>';
}

function updateForm() {
	
	if (checkForm() ) {
		var sform = $('quote').serialize(true);
		$('lightbox').update(loadingImage());
		new Ajax.Request("calculate-shipping.cfm", {
			parameters: sform,
			method:'post',
			onComplete: function(t){$('lightbox').update(topBar()+t.responseText);lbs[0].actions();tooltip.init(); }
		});
	}
	
	return false;
}

Event.observe(window, 'load', initialize);
Event.observe(window, 'load', getBrowserInfo);

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		this.content = 'calculate-shipping.cfm';
		this.productID = ctrl.rel;
		Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this));
		ctrl.onclick = function(){return false;};
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(){
		if (browser == 'Internet Explorer' && version == '6'){
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		this.displayLightbox("block");
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
	},
	
	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	
	displayLightbox: function(display){
		if (browser == 'Internet Explorer' && version == '6') {
			$('overlay').style.display = 'none';
		} else { 
			$('overlay').style.display = display;
		}
		$('lightbox').style.display = display;
		if(display != 'none') {
			Event.observe('overlay', 'click', this.deactivate.bindAsEventListener(this)); 
			$('lightbox').update(loadingImage('Loading...'));
			this.loadInfo();
		}
	},
	
	loadInfo: function() {
		
		new Ajax.Request(this.content, {
			parameters: {productID:this.productID},
			method:'get',
			onSuccess: function(t){$('lightbox').update(topBar()+t.responseText);},
			onComplete:this.actions.bindAsEventListener(this)
		});
		
    },
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');
		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this));
			lbActions[i].onclick = function(){return false;};
		}

	},
	deactivate: function(){
		Element.remove($('lbContent'));
		if (browser == "Internet Explorer" && version == '6'){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		this.displayLightbox("none");
	}
}

var lbs = [];
// Onload, make all links that need to trigger a lightbox active
function initialize(){
	addLightboxMarkup();
	lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		lbox[i].style.display='inline';
		lbs[i] = new lightbox(lbox[i]);
	}
}

function addLightboxMarkup() {
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
	overlay.id		= 'overlay';
	lb					= document.createElement('div');
	lb.id				= 'lightbox';
	bod.appendChild(overlay);
	bod.appendChild(lb);
}

function getNewQuote() {
	$('newQuoteButton').hide();
	$('quotesTable').hide();
	countryChange();
	$('quote').style.visibility="visible";
	$('quote').style.display="inline";
}

function showCanada() {
	$("canadatbl").style.visibility = "visible";
	$("canadatbl").style.display = "inline";
}

function hideCanada() {
	$("canadatbl").hide();
}

function showUS() {
	$('zipcodetbl').style.visibility = "visible";
	$('zipcodetbl').style.display = "inline";
}

function hideUS() {
	$('zipcodetbl').hide();
}

function countryChange () {
	
	var fx = document.forms.quote;
	if (fx.country.value == "124") {
		hideUS();
		showCanada();	
	} else if (fx.country.value == "840") {
		hideCanada();
		showUS();
	}
	else {
		hideUS();
		hideCanada();
	}

}

function checkForm () {
	
	var elem = document.getElementById('quote').elements;
	var checkedcount = 0;
	var checkboxq = 0;
	var rval = false;
	var errorP = false;
	var country = document.forms.quote.country.value;
	var usP = (country == "840") ? true : false;
	
	for(var i = 0; i < elem.length; i++) {
		if (elem[i].type == "checkbox") {
			if (elem[i].id != "usP") checkboxq++;
			if (elem[i].checked == true && elem[i].id != "usP") checkedcount++; 
		}
	}

	if (checkboxq >= 1 && checkedcount==0) {
		alert('Please select at least one item to include in shipping quote.');
		errorP = true;
	}
	
	/* now check zipcode */
	if (usP && document.getElementById('zipcode').value == "") {
		alert('Please enter the zipcode of the destination.');
		errorP = true;
	} 
	
	if (!usP && country == "124" && document.getElementById('quote').elements['postalcode'].value == "") {
		alert('You must enter the postal code for shipping estimates to Canada.');
		errorP = true;
	}
	
	if (document.getElementById('quote').elements['q'] != null && document.getElementById('quote').elements['q'].value < 1) {
		alert('Please enter a positive quantity of the item.');
		errorP = true;
	}
	
	if (!errorP) rval = true;

	return rval;
}

var tooltip=function(){
 var id = 'tt';
 var top = 3;
 var left = 10;
 var tt;
 var ie = document.all ? true : false;
 return{
  show:function(v,w){
   if(tt == null){
    this.init;
   }
   tt.innerHTML = v;
   tt.style.position = 'absolute';
   tt.style.width = w ? w + 'px' : 'auto';
   tt.style.display = 'block';
   h = parseInt(tt.offsetHeight);
  },
  init:function() {
  	tt = document.createElement('div');
    tt.setAttribute('id',id);
    $('lightbox').appendChild(tt);
    document.onmousemove = this.pos;
    this.hide;
  },
	pos:function(e) {
	  var u = 0, l = 0;
	  var coordinates = $('lightbox').viewportOffset();
	  u = Event.pointerY(e) - coordinates[1];
	  l = Event.pointerX(e) - coordinates[0];
	  tt.style.top = (u + top )  + 'px';
	  tt.style.left = (l + left) + 'px';
	  
	  },
 	hide:function(){
  	tt.style.display = 'none';
  }
 };
}();
