document.observe('dom:loaded', function(){ if($('price_calculator')){init_order();} });

function init_order(){
	window.disableTab = true;
	if($('order-page')){
		window.pageWidth = 790;
		$$('.finish_button')[0].observe('mousedown',finish_order);
		if(parent.location.protocol=='http:'){
			window.location = String.interpret(window.parent.document.location).sub(new RegExp('http:\/\/[^\/]+'+SITE_ROOT),SECURE_ROOT);
		}
	} else {
		window.pageWidth = 540;
		$$('.save_for_later_button')[0].observe('mousedown',save_for_later);
		$$('.order_now_button').each(function(n){n.observe('mousedown',finish_quote)});
	}
	if($('price_calculator')){
		arm_price_nav_buttons();
		window._currentPricePage = 1;
		$('price_calculator').select('[condition]').reject(function(nh){return nh.hasAttribute('nohide');}).invoke('hide');
		$('price_calculator').select('[type="text"]').filter(function(e){ return e.readAttribute('omit')!="true";}).each(function(i){i.observe('keyup', update_value);});
		$('price_calculator').select('select').each(function(i){i.observe('change', update_value);});
		$('price_calculator').select('[type="checkbox"]').each(function(i){i.observe('click', update_value);});
		$('price_calculator').select('[type="radio"]').each(function(i){i.observe('click', update_value);});
		order_change_description();
	}
	window._currentlyAnimating = false;
	window._currentlyUpdating = [];
	$('loading_image').hide();
	//// Reset Values to defaults
	reset_all_prices();
}
function startUpdate(){
	window._currentlyUpdating.push("update");
	disable_price_nav_buttons();
	$('loading_image').show();
}
function updateComplete(){
	if(window._currentlyUpdating.length > 0){
		window._currentlyUpdating.pop();
	}
	if(window._currentlyUpdating.length==0){
		arm_price_nav_buttons();
		$('loading_image').hide();
	}
}
function reset_all_prices(){
	var e = $$('.price').filter(function(n){return n.innerHTML.match(/each$/);});
	e.each(function(f){
			var par = f.up('ul');
			var nom = f.previous('label').readAttribute('for');
			update_price(par,nom,'min',false,true);  //f.previous('[name="'+nom+'"]').getValue() gets current
		});
	
}
function arm_price_nav_buttons(){
	$$('.add_button').each(function(i){i.stopObserving(); i.observe('mousedown', add_order_page)});
	$$('.continue_button','.start_button').each(function(i){i.stopObserving(); i.observe('mousedown', add_order_page)});
	$$('.skip_button').each(function(i){i.stopObserving(); i.observe('mousedown', skip_order_page)});
	$$('.back_button').each(function(i){i.stopObserving(); i.observe('click',slide_order_right);});
}
function disable_price_nav_buttons(){
	$$('.add_button').each(function(i){i.stopObserving();});
	$$('.continue_button','.start_button').each(function(i){i.stopObserving();});
	$$('.skip_button').each(function(i){i.stopObserving();});
	$$('.back_button').each(function(i){i.stopObserving();});
}
function currentPricePage(){
	return $('price_calculator').down('[pageNum='+window._currentPricePage+']');
}
function addPricePage(pageID){
	var cPage = $$('[pageNum='+pageID+']')[0];
	cPage.insert({'after':cPage.clone(true)});
	$('price_calculator').setStyle({'width':(parseInt($('price_calculator').getWidth()) + 1000)+'px'});
	
	cPage.next('ul.price_page').select('[type="text"]').each(function(t){t.stopObserving();});
	cPage.next('ul.price_page').down('.buttons').select('div').each(function(b){b.stopObserving();});
	
	cPage.next('ul.price_page').select('[type="text"]').filter(function(e){ return e.readAttribute('omit')!="true";}).each(function(i){i.observe('keyup', update_value);});
	sort_price_pages();
	return cPage.next('ul.price_page');
}
function sort_price_pages(){
	for(var p=0;p<$$('.price_page').length;p++){
		$$('.price_page')[p].writeAttribute('pageNum',p+1);
	}
}
function add_order_page(r){
	//console.log('doing next page',r);
	if(!currentPricePage().hasAttribute('noactions') && window._currentlyAnimating == false){
		var item = currentPricePage().down('h1');
		var iSelector = item.innerHTML.gsub(/\s/,'_').toLowerCase();
		if($('price_calculator').down('[name="'+iSelector+'_price"]')){
			//calculator parsing
			if($('price_calculator').down('[name="'+iSelector+'_price"]').getValue() == 'N'){
				new Effect.Highlight(currentPricePage().down('.price'), {'startcolor':'#ff4040'});
			} else if(currentPricePage().select('[req]').filter(function(r){ return r.getValue()==false; }).length > 0){
				currentPricePage().select('[req]').filter(function(n){ return n.getValue()==false; }).each(function(f){
						new Effect.Highlight(f, {'startcolor':'#ff4040'});
					});
			} else {
				run_order_page_hooks(iSelector);
				var price = toRealFloat(currentPricePage().down('[name="'+iSelector+'_price"]').getValue());
				var currentTotal = $('total_column').select('li').filter(function(r){return r.down('h1').innerHTML == item.innerHTML;})[0];
				if(iSelector == 'classic_viewers'){
					var quant = $$('.color_quantity').collect(function(f){ return f.getValue(); }).inject(0,function(n,i){return n + parseInt(i);});
				} else if(iSelector == 'imprints'){
					var quant = $('price_calculator').down('[name="imprint_quantity"]').getValue();
				} else if(iSelector == 'packaging' || iSelector == 'fulfillment'){
					var quant = '  ';
				} else {
					var quant = $('price_calculator').down('[name="'+iSelector+'"]').getValue();
				}
				if(iSelector == 'packaging' || iSelector == 'fulfillment'){
					var subItems = currentPricePage().select('label').filter(function(t){return t}).collect(function(f){return f.innerHTML;});
					var subValues = currentPricePage().select('label').collect(function(f){ return f.next('[type="text"]').getValue();});
					var subPrices = currentPricePage().select('label').collect(function(f){return f.next('[type="hidden"]').getValue();});
					var sub=true;
				}
				if(currentTotal){
					currentTotal.down('span').update('$'+price);
					currentTotal.select('h1')[1].update(quant);
				} else {
					$('total_column').select('li:last-child').last().insert({'before':new Element('li').update(item.clone(true)).insert(new Element('h1').update(quant)).insert(new Element('span').update('$'+price))});
					currentTotal = $('total_column').select('li:last-child').last().previous();
				}
				if(sub==true){
					currentTotal.select('ul').invoke('remove');
					currentTotal.insert(new Element('ul'));
					subValues.each(function(f,i){
							if(f > 0){
								currentTotal.down('ul').insert(new Element('li').update(
									new Element('h1').update(subItems[i])
								).insert(
									new Element('h1').update(f)
								).insert(
									new Element('span').update('$'+toRealFloat(subPrices[i]))
								));
							}
						});
				}
				slide_order_left();
				update_total();
			}
		} else {
			//order page parsing
			slide_order_left();
		}
	} else if(window._currentlyAnimating == false){
		slide_order_left();
	}
}
function skip_order_page(){
	currentPricePage().select('input').invoke('setValue',0);
	currentPricePage().select('select').invoke('setValue',0);
	currentPricePage().select('hidden').invoke('setValue',0);
	currentPricePage().select('.price').each(function(nr){nr.update(nr.innerHTML.gsub(/\d+/,0));});
	currentPricePage().select('select').filter(function(r){return r.down('option').readAttribute('value')=='stock';}).invoke('setValue','stock');
	$('total_column').select('li').filter(function(r){return r.down('h1').innerHTML == currentPricePage().down('h1').innerHTML}).invoke('remove');
	slide_order_left();
}
function run_order_page_hooks(sel){
	switch(sel){
		case 'master_setups':
			var pagens = $$('[name]').filter(function(f){return f.readAttribute('name').match(/^reels_\d$/);});
			var rPageNum = $F($$('[name="master_setups"]')[0]);
			$$('.price_page').filter(function(n){ return (n.down('input'))?n.down('input').readAttribute('name').match(/^reels_[2-9]/):false;}).invoke('remove');
			$$('.newDesc').invoke('remove');
			var firstNum = $$('[name]').filter(function(f){return f.readAttribute('name').match(/^reels_\d$/);})[0].up('.price_page').readAttribute('pageNum');
			for(var p=rPageNum;p>1;p--){
				var newPage = addPricePage(firstNum);
				newPage.select('h1').filter(function(f){return f.innerHTML.match("Reels 1");}).each(function(i){i.update(i.innerHTML.sub(/\d$/,this.p));},{'p':p});
				newPage.select('[name="reels_1_price"]').invoke('writeAttribute','name','reels_'+p+'_price');
				newPage.select('[name="reels_1"]').invoke('writeAttribute','name','reels_'+p);
				newPage.select('[for="reels_1"]').invoke('writeAttribute','for','reels_'+p).each(function(pi){pi.update(pi.innerHTML.sub(/\d:$/,this.p));},{'p':p});
				arm_price_nav_buttons();
				
				var newDesc = $$('.price_page_description')[firstNum-1].clone(true).addClassName('newDesc');
				$$('.price_page_description')[firstNum-1].insert({'after':newDesc});
			}
			var convs = $$('[name="3d_image_conversions"]').last();
			convs.update('');
			$R(0,rPageNum*7).each(function(rn){this.co.insert(new Element('option',{'value':rn}).update(rn));},{'co':convs});
			for (var n=1;n<=$$('.price_page_description').length;n++){
				$$('.price_page_description')[n-1].writeAttribute('descNum',n);
			}
			break;
	}
}
function run_pre_page_hooks(sel){
	switch(sel){
		case 'estimated_total_price':
			var totalPrice = $('price_calculator').select('.subtotal').inject(0,function(t,p){return t + parseFloat(p.getValue())});
			$$('[name="total_price"]')[0].writeAttribute('value',totalPrice).previous('h2').update('$'+toRealFloat(totalPrice));
			break;
		case 'rush_service':
			if(getSelectValue('[name="time_frame"]')!='10-15'){
				slide_order_left(2);
			}
			break;
	}
}
function slide_order_left(n){
	if(!n){n=1;}
	window._currentPricePage += 1;
	window._currentlyAnimating = true;
	new Effect.Move('price_calculator',{'x':parseInt(window.pageWidth-(window.pageWidth*2))*n, 'y':0, 'mode':'relative', 'duration':.4, 'afterFinish':function(){
		// effect issues with ie
		window._currentlyAnimating = false;
		$('price_calculator').setStyle({'left':'-'+(window.pageWidth*(window._currentPricePage-1))+"px"});
	} });
	order_change_description();
	order_fix_height();
	run_pre_page_hooks(currentPricePage().down('h1').innerHTML.gsub(/\s/,'_').toLowerCase());
}
function slide_order_right(){
	window._currentPricePage -= 1;
	window._currentlyAnimating = true;
	new Effect.Move('price_calculator',{'x':window.pageWidth,'y':0,'mode':'relative','duration':.4, 'afterFinish':function(){
		// effect issues with ie
		window._currentlyAnimating = false;
		$('price_calculator').setStyle({'left':'-'+(window.pageWidth*(window._currentPricePage-1))+"px"});
	} });
	order_change_description();
	order_fix_height();
}
function order_change_description(){
	$$('.price_page_description').invoke('hide');
	$$('.price_page_description').filter(function(i){return i.readAttribute('descNum') == window._currentPricePage;}).invoke('show');
}
function order_fix_height(){
	var newHeight = currentPricePage().getHeight()+50;
	if(newHeight > 200){
		new Effect.Morph('price_page_holder',{'style':'height:'+newHeight+'px;','duration':.4});
	}
}
function update_value(e){
	var targetElement = (!arguments[3])?e.findElement():arguments[3].down('[name="'+arguments[1]+'"]');
	var el = (!arguments[3])?e.findElement().up('li'):arguments[3];
	var nom = (!arguments[1])?e.findElement().readAttribute('name'):arguments[1];
	var val = (!arguments[2])?$F(e.findElement()):arguments[2];
	
	if(!nom.match(/_type$/)){
		if(targetElement.hasAttribute('async')){
			startUpdate();
		}
		hide_if_condition('any');
		hide_with_condition(nom);
		if(val != null){$('price_calculator').select('[condition="'+nom+'##'+val.gsub(/\s/,'')+'"]').invoke('show');}
		if(val != null){
			if(nom == 'rush_service'){
				//yeah, yeah...
				window.rushValue = val;
				val = $$('[name]','[type="text"]').filter(function(n){return n.readAttribute('name').match(/^reels_/);}).reject(function(r){return r.hasClassName('subtotal');}).inject(0,function(t,o){return t + parseInt($F(o));});
			} else if(nom.match(/^packaging/)){
				if(val>0){
					var subTotal = $('price_calculator').down('[name="packaging_price"]').previous();
					if(!nom.match(/clam$/)&&!nom.match(/transparent$/)){
						$('price_calculator').select('[condition="'+nom+'##1"]').invoke('show');
						nom = nom+"##"+$F($('price_calculator').down('[name="'+nom.sub(/^packaging_/,'')+'_type"]')).toLowerCase();
					}
				}
			} else if(nom.match(/^fulfillment/)&&val>0){
				var subTotal = $('price_calculator').down('[name="fulfillment_price"]').previous();
			} else if(val.match(/^\d+$/)){
				$('price_calculator').select('[condition]').filter(function(i){
					var r = i.readAttribute('condition').match(new RegExp(nom+"##(\\d)>"));
					return (r)?(parseInt(r[1]) <= this.val):false;
				}, {'val':val,'nom':nom}).invoke('show');
			} else if(nom=="international_ship_payment"){
				var nval = val.sub(/\s\w+$/,'').gsub(/\s/,'');
				currentPricePage().select('[condition="'+nom+'##'+nval+'"]').invoke('show');
			} else if(nom=="speed_of_service"){
				currentPricePage().down('[condition="speed_of_service##RushService"]').show();
			} else {
				currentPricePage().select('[condition]').filter(function(i){
						return i.readAttribute('condition').match(new RegExp('any##'+val.sub(/\s\w+$/,'').sub(/\s/,'')));
					}).invoke('show');
			}
		}
		order_fix_height();
	
		if(nom.match(/^imprint/)){
			update_imprint_val(el,nom,val);
		} else if(nom.match(/^color_quantity/) || nom.match(/^viewer_color/)){
			var colors = $$('.color_quantity').collect(function(r){ return r.previous('select'); }).collect(function(e){ return e.getValue(); });
			var quantities = $$('.color_quantity').collect(function(f){ return f.getValue(); });
			var pObj = [];
			for (var c=0;c<colors.length;c++){
				if(quantities[c] > 0){
					pObj[c] = ['classic_viewers'+((colors[c]=='custom')?'##custom':''), quantities[c]];
				}
			}
			update_price_multi($$('[name="classic_viewers_price"]')[0], pObj);
		} else if($('order-page')){
			
		} else {
			update_price(el, nom, val, subTotal);
		}
	
	} else {
		var elm = $('price_calculator').down('[name="packaging_'+nom.sub('_type','')+'"]');
		update_value(null,'packaging_'+nom.sub('_type',''),$F(elm),elm.up('li'));
	}
}
function parseNonNegative(n){
	return (n>0)?n:0;
}
function update_imprint_val(el,nom,val){
	val = parseInt($$('[name="imprint_quantity"]')[0].getValue());
	if(val > 0){
		var colrs = parseInt($$('[name="imprint_colors"]')[0].getValue());
		if(colrs<1){
			$$('[name="imprint_colors"]')[0].setValue(1).up('li').next('[condition="imprint_colors##1>"]').show();
		}
		var locs = parseInt($$('[name="imprint_locations"]')[0].getValue());
		var totalImprints = locs*val;
		if(locs<1){
			$$('[name="imprint_locations"]')[0].setValue(1);
		}
		var setups = 1;// only 1 setup unless we're not using the colors & locations. locs+colrs-1;
		update_price_multi($$('[name="imprints_price"]')[0],[['imprint', totalImprints],
		['imprint_setup',setups],
		['imprint_colors',parseNonNegative(parseInt($$('[name="imprint_colors"]')[0].getValue())-1)],
		['imprint_locations',parseNonNegative(parseInt($$('[name="imprint_locations"]')[0].getValue())-1)],
		['imprint_colors##custom',currentPricePage().select('[condition]').filter(function(f){
			var r = (f.down('select'))?f.down('select').readAttribute('name').match(new RegExp('imprint_color_\\d')):false;
			return (r)?f.down('select').getValue() == 'custom':false;
		}).length ]]);
	}
}
function update_price_multi(toEl,args){
	var info = [];
	for(var i=0;i<args.length;i++){
		info.push($A(args)[i]);
	}
	new Ajax.Request(SITE_ROOT+'index.php',{
			parameters: {
				'ajax_request':'get_price_multi',
				'info':Object.toJSON(info)
				},
			onComplete:function(t){
				if(t.responseText == 'N'){
					var ret = "Not available at this quantity.";
				} else if(t.responseText == 'C'){
					var ret = "Call for price";
				} else {
					var ret = '$'+toRealFloat(parseFloat(t.responseText));
				}
				toEl.setValue(parseFloat(t.responseText).toFixed(2));
				toEl.previous().update(ret);
				updateComplete();
			}
		});
}
function update_price(pel,nom,val,subT,noaction){
	if(val==""||val==0){
		val='min';
		noaction=true;
	}
	var sVal = false;
	if(nom.match(/^reels_/)){
		var aNom = nom.sub(/_\d/,'');
		if($$('[name="time_frame"]').last().getValue()=='30'){
			aNom = 'reels_30days';
		}
		if(val!='min'){
			sVal = val;
			val = get_total_quantity(new RegExp('\^reels_'));
		} else {
			val = ($$('[name="time_frame"]').last().getValue()=='30')?'500':'10';
		}
	} else if(nom.match(/^packaging_/)){
		var aNom = nom;
		if(nom.match(/handout$/)||nom.match(/tab_fold$/)||nom.match(/gift_box$/)||nom.match(/reelvelopes$/)){
			aNom += "##stock";
		}
	} else {
		var aNom = nom;
	}
	if(aNom=='time_frame'){
		updateComplete();
		var defaultValue = ($$('[name="time_frame"]').last().getValue()=='30')?'500':'10';
		var elm = $('price_calculator').down('[name="reels_1"]');
		update_value(null,'reels_1',defaultValue,elm.up('li'));
	}
	new Ajax.Request(SITE_ROOT+'index.php', {
			parameters:{
				'ajax_request':'get_price',
				'item':aNom,
				'quantity':val
			},
			onSuccess:function(t){
				if(t.responseText == 'N'){
					if(nom.match(/^packaging/)||nom.match(/^fulfillment/)){
						var ret = "N/A @ Qty.";
						var nVal = 0;
					} else {
						var ret = "N/A @ Qty.";
						var nVal = 'N';
					}
				} else if(t.responseText == 'C'){
					var ret = "Call for price";
					var nVal = 0;
				} else {
					if(val=='min'){
						var retV = (t.responseText).evalJSON();
						val=(retV[1]==0)?1:retV[1];
						t.responseText = retV[0];
					}
					var priceEach = parseFloat(t.responseText)/val;
					var ret = '$'+toRealFloat(priceEach)+' each';
					if(sVal != false){
						// for reels only...
						var nVal = priceEach*sVal;
						$('total_column').select('li').filter(function(r){return r.down('h1').innerHTML.match(/reels/i);}).each(function(n){ n.down('span').update('$'+toRealFloat(parseInt(n.select('h1').last().innerHTML)*priceEach));});
						$$('.subtotal').filter(function(st){
								return st.readAttribute('name').match(/reels/i);
							}).each(function(s){
								s.setValue(nVal);
							});
					} else if(nom == 'rush_service'){
						var nVal = priceEach*parseInt(window.rushValue);
					} else if(nom.match(/^packaging_/)||nom.match(/^fulfillment_/)){
						if(noaction==true){
							var nVal = 0;
						} else {
							var nVal = t.responseText;
						}
					} else {
						var nVal = t.responseText;
					}
				}
				pel.down('[name="'+nom.sub(/##[\w_]+$/,'')+'"]').next('.price').update(ret);
				pel.down('[name="'+nom.sub(/##[\w_]+$/,'')+'_price"]').writeAttribute('value',parseFloat(nVal).toFixed(2));
				if(typeof noaction == "undefined" || noaction==false){
					update_total();
					update_subtotal(subT);
				}
				updateComplete();
			}
		});
}
function get_total_quantity(r){
	return $('price_calculator').select('[type="text"]').filter(function(n){return n.readAttribute('name').match(r);}).inject(0,function(i,n){return i+parseInt($F(n));});
}
function update_subtotal(n){
	if(n){
		var tot = n.up('.price_page').select('input').filter(function(f){
			var no=f.readAttribute('name');
			return (no.match(/_price$/)&&no!=this.nn)?true:false;
			},{'nn':n.next().readAttribute('name')}).inject(0,function(o,r){return o + parseFloat($F(r))});
		n.update('$'+toRealFloat(tot));
		n.next().writeAttribute('value',tot);
	}
}
function update_total(){
	var t = $$('#total_column > ul > li').inject(0, function(to,p,ind){
			if(!p.down('span').hasClassName('total_price')&&ind>0){
				return to + parseFloat(p.down('span').innerHTML.sub(/\$/,''));
			} else {
				return to;
			}
		});
	$('total_column').down('.total_price').update($('total_column').down('.total_price').innerHTML.sub(/\$[\d\.]+/, '$'+toRealFloat(t))); //((t+'').match(/[^\.]+\.[\d]{2}/))?t:t+'.00')???
}
function hide_with_condition(n){
	$('price_calculator').select('li').filter(
		function(i){
			if(i.readAttribute('condition')){
				i.select('[name]').each(function(ic){
					//$$('[condition="'+ic.readAttribute('name')+'##'+$F(ic)+'"]').invoke('hide');
				});
				return i.readAttribute('condition').match(n)
			}else{
				return false;
			}
		}).invoke('hide');
}
function hide_if_condition(cond){
	var cs = currentPricePage().select('[condition]').filter(function(n){ return n.readAttribute('condition').match(new RegExp('^'+cond)); });
	cs.reject(function(n){
		var nom = n.readAttribute('condition').sub(/[^#]+##/,'');
		var c = currentPricePage().select('input','select').invoke('getValue').filter(function(r){return r;}).collect(function(s){return s.sub(/\s/,'').sub(/\s.+$/,'');});
		return c.filter(function(r){return r.match(nom);}).length > 0;
	}).invoke('hide');
}
function finish_quote(){
	$$('.save_for_later_button','.back_button').invoke('stopObserving');
	save_quote(function(t){
			window.location=t.responseText;
		});
}
function finish_order(){
	if($F($$('[name="terms_conditions_agree"]')[0])=='yes'){
		$$('.finish_button','.back_button').invoke('stopObserving');
		$('price_form').request({
			method:'post',
			parameters:{'ajax_request':'save_order'},
			onComplete:function(t){
				if(t.responseText=='true'){
					slide_order_left();
				}
			}
		});
	} else {
		new Effect.Highlight($$('[name="terms_conditions_agree"]')[0].up('p'),{'duration':.4,'startcolor':'#FF4040'});
	}
}
function save_for_later(){
	$$('.save_for_later_button','.back_button').invoke('stopObserving');
	save_quote(function(t){
		$('price_calculator').select('.back_button').each(function(i){i.observe('click',slide_order_right);});
		slide_order_left();
		});
}
function save_quote(handler){
	if($F($$('[name="name"]')[0]).length == 0){
		new Effect.Highlight($$('[name="name"]')[0],{'startcolor':'#ff4040'});
	} else if($F($$('[name="phone"]')[0]).length == 0){
		new Effect.Highlight($$('[name="phone"]')[0],{'startcolor':'#ff4040'});
	} else if($F($$('[name="email"]')[0]).length == 0){
		new Effect.Highlight($$('[name="email"]')[0],{'startcolor':'#ff4040'});
	} else {
		$('price_form').request({
				method:'post',
				parameters:{'ajax_request':'save_quote'},
				onComplete:handler
			});
	}
}

function toRealFloat(i,d){
	var i = i+'';
	if(!arguments[1]){
		d = 2;
	}
	if(i.match(/\./)){
		var ia = i.split('.',2);
		return ia[0]+'.'+(ia[1]+'00').truncate(d,'');
	} else {
		return i+'.00';
	}
}

function getSelectValue(c){
	return (Object.isArray($F($$(c).last())))?$F($$(c).last())[0]:$F($$(c).last());
}
/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}
//// FIGLEAF SOFTWARE RGB to Hex - modified to take css value.
Math.rgbToHex = function(c){
	var r = c.match(/\((\d)/);
	var g = c.match(/\(\d,(\d)/);
	var b = c.match(/\(\d,\d,(\d)/);
	return '#'+(r<<16 | g<<8 | b);
}
