document.observe("dom:loaded",page_loaded);

var emailtest = /^[a-zA-Z]+([_\.-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,4})+$/

var addthis_config = {
    data_track_linkback: true
}

var geonamesPostalCodeCountries = ["LU","LT","ZA","RE","HR","HU","DO","MK","VA","DE","MC","MD","DK","AT","MX","AR","US","MY","IN","AU","IS","IT","MQ","PT","AD","ES","NL","YT","JP","NZ","GF","BR","GB","TH","CA","TR","NO","BG","FR","FO","BD","BE","FI","CZ","SE","SI","SK","SM","PL","GT","CH","GP","PK","LI","LK","GL","GR"];

var refimgs;

stuHover = function() {
	if ($('nav')){
		var cssRule;
		var newSelector;
		for (var i=0; i<document.styleSheets.length; i++)
			for (var x=0; x<document.styleSheets[i].rules.length ; x++){
				cssRule = document.styleSheets[i].rules[x];
				if (cssRule.selectorText.indexOf("LI:hover") >= 0){
					newSelector = cssRule.selectorText.replace(/LI:hover/gi, "LI.iehover");
					document.styleSheets[i].addRule(newSelector , cssRule.style.cssText);
				}
			}
		var getElm = document.getElementById("nav").getElementsByTagName("LI");
		for (var i=0; i<getElm.length; i++) {
			cn = getElm[i].className;
			if (cn.search(/homelink/i)==-1){
				getElm[i].onmouseover=function() {
					this.className+=" iehover";
				}
				getElm[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp(" iehover\\b"), "");
				}
			}
		}
	}
}

if (window.attachEvent) window.attachEvent("onload", stuHover);

function validateform(formid){

	var error = false;
	var firsterror = "";

	$$('#'+formid+' .req').each(function(obj){

		var errorspan = $(obj.id+'-error');

		if (!errorspan){
			Element.insert(obj.parentNode, {bottom:'<span class="err" id="'+obj.id+'-error"></span>'});
			errorspan = $(obj.id+'-error');
		}
		if ($F(obj)=="" && obj.visible()){
			obj.addClassName('errorfield');
			errorspan.show();
			errorspan.update('Required field');
			error = true;
			if (firsterror == ""){
				firsterror = obj.id;
			}
		} else {
			obj.removeClassName('errorfield');
			errorspan.hide();
		}
	});

	$$('#'+formid+' .reqemail').each(function(obj){
		$(obj).value = $F(obj).strip();

		var errorspan = $(obj.id+'-error');

		if (!errorspan){
			Element.insert(obj.parentNode, {bottom:'<span class="err" id="'+obj.id+'-error"></span>'});
			errorspan = $(obj.id+'-error');
		}

		if ($F(obj)=="" || !emailtest.test($F(obj))){
			obj.addClassName('errorfield');
			errorspan.show();
			errorspan.update('Please enter a valid email address');
			error = true;
			if (firsterror == ""){
				firsterror = obj.id;
			}
		} else {
			obj.removeClassName('errorfield');
			errorspan.hide();
		}
	});

	if (!error){
		//validateform.submit();
		return true;
	} else {
		//$(firsterror).scrollTo();
		//$(firsterror).focus();
		return firsterror;
	}
}

function roundNumber(num, dec) {
	var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
	return result;
}

function calcroofpeak(){
	
	var width = parseFloat($F('width'));
	var height = parseFloat($F('height'));
	var pitch = parseFloat($F('roofpitch'));
	
	if (!isNaN(width) && width!=0 && !isNaN(height) && height!=0 && !isNaN(pitch) && pitch!=0){
		var peakheight = height+((width/2/12)*pitch);
		$('roofpeak').update(roundNumber(peakheight,3) + "");
	} else {
		$('roofpeak').update("-");
	}
	
}

function test(initname,lz_sess_id,lz_request_window,lz_intern_id,lz_group_id,lz_request_id,lz_win){
	if ($F('lz_invitation_name')=="" || $F('lz_invitation_name')==initname) {
		alert("Please enter your name");
		return false;
	} else {
		lz_win.lz_livebox_chat(lz_sess_id,lz_request_window,lz_intern_id,lz_group_id);
		lz_win.lz_livebox_close();
		lz_tracking_accepted_request(lz_request_id);
	}
}

function CB_ExternalFunctionPageLoad(){
	if ($('CB_TC')){
		Element.insert('CB_TC', {after:"<span id='photoquotelink'><a href='"+dir+"/metal-building-quote'>Request a quote</a> and buy your own building!</span>"});
		Event.observe('photoquotelink','click',function(e){
			if ($('CB_Image')){
				_gaq.push(['_trackEvent', 'Quote link from photo', $('CB_Image').src]);
			}
		});
	}
}

function CB_ExternalFunctionLoad(){
	if ($('CB_Image')){
		_gaq.push(['_trackEvent', 'Photoview', $('CB_Image').src]);
	}
}

function page_loaded(){
	
	/*if ($('referrals')){
		refimgs = $$('.bigimage');
		Event.observe(window,'scroll',function(e){
			
			var vp = document.viewport.getDimensions();
			
			var visimg = refimgs.reject(function(n){
				var $elem = $(n.id);
				var $elemOffset = $elem.viewportOffset();
				if($elemOffset.left < 0 || $elemOffset.top < 0 || $elemOffset.left > vp.width || $elemOffset.top > vp.height){
					return true;
				}
			});
			
			visimg.each(function(obj){
				var imgnum = obj.id.sub('bigimg_','');
				if ($('abc_'+imgnum)==undefined){
					Element.insert($('referralimage_'+imgnum), {bottom:'<span id="abc_'+imgnum+'">abc</span>'});
				}
			});
			
			/*refimgs.each(function(obj){
				
				var $elem = $(obj.id);
				var imgnum = obj.id.sub('bigimg_','');
				
				var $elemOffset = $elem.viewportOffset();
				if($elemOffset.left < 0 || $elemOffset.top < 0 || $elemOffset.left > vp.width || $elemOffset.top > vp.height){ 
					
				} else if ($('abc_'+imgnum)==undefined){
					Element.insert($('referralimage_'+imgnum), {bottom:'<span id="abc_'+imgnum+'">abc</span>'});
				}
			});
		});
	}*/
	
	if ($('specialinquiry')){
		var urlparts = window.location.href.split("#");
		if (urlparts[1]=="inquiry"){
			$('name').focus();
		}
	}
	
	if ($('homeslideshow')){
		var cacheBuster = "?t=" + Date.parse(new Date());
		var stageW = "230";
		var stageH = "174";
		
		var attributes = {};
		attributes.id = 'homeslideshow';
		attributes.name = attributes.id;
		
		var params = {};
		params.bgcolor = "#000000";
		params.wmode = "transparent";
		
		var flashvars = {};
		flashvars.pathToFiles = "";
		flashvars.xmlPath = dir+"/slideshow/homeslide.xml";
		
		swfobject.embedSWF(dir+"/slideshow/preview.swf"+cacheBuster, attributes.id, stageW, stageH, "9.0.124", "", flashvars, params); 
	}
	
	if ($('homeslide')){
		jQuery(document).ready(function($) {
			$('#homeslide').coinslider({ width: 700, height:240, navigation: true, delay: 5000, effect: 'straight', spw: 3, sph:2 });
		});
	}
	
	if ($('bigspecialmaplink')){
		Event.observe('bigspecialmaplink','click',function(e){
			Event.stop(e);
			Effect.SlideDown('bigspecialmap',{duration:0.5});
			Effect.BlindUp('smallspecialmap',{duration:0.5});
		});
	}
	
	if ($('action')){
		$$('input','textarea','select').each(function(obj){
			Event.observe(obj,'blur',function(e){
				if ($F(this).length>0){
					var formname = $F('action');
					var action = "input_exit";
					var fieldname = this.name;
					_gaq.push(['_trackEvent', 'Form: '+formname, 'input_exit',fieldname]);
				}
			});
		});
	}

	if ($('quote')){
		
		if ($('roofpeak')){
			$('width').focus();
			
			Event.observe('width','change',function(){
				calcroofpeak()
			});
			
			Event.observe('height','change',function(){
				calcroofpeak()
			});
			
			Event.observe('roofpitch','change',function(){
				calcroofpeak()
			});
		}
		
		/*Event.observe('width','change',calcroofpeak());
		Event.observe('height','change',calcroofpeak());
		Event.observe('roofpitch','change',calcroofpeak());*/

		Event.observe('sitecountry','change',function(){
			$('zipcode').clear();
			$('place').update("");
			if ($F(this)=="US"){
				$('zipcodelabel').update('Zipcode');
				$('statelabel').update('State');
			} else if ($F(this)=="CA") {
				$('zipcodelabel').update('Postal code');
				$('statelabel').update('Province');
			} else {
				$('zipcodelabel').update('Postal code');
				$('statelabel').update('State');
			}

			switch ($F(this)){
				case "US":
					$('customstate').hide();
					$('castate').hide();
					$('sitestate').show();
					$('statereqsign').show();
					if ($('countyrow')) $('countyrow').show();
					if ($('sitecounty')) $('sitecounty').show();
				break;

				case "CA":
					$('customstate').hide();
					$('castate').show();
					$('sitestate').hide();
					$('statereqsign').show();
					if ($('countyrow'))$('countyrow').hide();
					if ($('sitecounty'))$('sitecounty').hide();
				break;

				default:
					$('customstate').show();
					$('castate').hide();
					$('sitestate').hide();
					$('statereqsign').hide();
					if ($('countyrow'))$('countyrow').hide();
					if ($('sitecounty'))$('sitecounty').hide();
				break;
			}
		});
		
		if ($('zipcode')){
			Event.observe('zipcode','blur',function(e){
				if (geonamesPostalCodeCountries.indexOf($F('sitecountry')) && !$F('zipcode').empty()){
					var zipcode = $F('zipcode').strip();
					var country = $F('sitecountry');
					new Ajax.Request(dir+"/lib/request.php",{
						parameters : "r=z&zipcode="+zipcode+"&country="+country,
						onCreate : function(){
						
						},
						onSuccess : function(resp){
							if ( resp.responseJSON.postalcodes.size()>0){
								response = resp.responseJSON.postalcodes[0];
								resparray = new Array();
								resparray.push(response.placeName);
								if (response.adminName2 !== undefined){
									resparray.push(response.adminName2+' county');
									$('sitecounty').value = response.adminName2;
								}
								if (response.placeName != response.adminName1){
									resparray.push(response.adminName1);	
								}
								
								if (country == "US" || country == "CA"){
									$('sitestate').value = response.adminCode1;
								}
								
								$('place').update("<em>Location:</em> " + resparray.join(", "));
								$('customstate').value = response.adminName1;
							} else {
								$('place').update("-");
							}
						}
					});
				}
			});
		}

		if ($('wallcolorname')){
			Event.observe('wallcolorname','click',function(e){
				Event.stop(e);
				if ($('wallcolorchooser').visible()){
					$('wallcolorchooser').blindUp({duration:0.5});
					this.className = "arrowdown";
				} else {
					$('wallcolorchooser').blindDown({duration:0.5});
					this.className = "arrowup";
				}
			});
		}

		if ($('roofcolorname')){
			Event.observe('roofcolorname','click',function(e){
				Event.stop(e);
				if ($('roofcolorchooser').visible()){
					$('roofcolorchooser').blindUp({duration:0.5});
					this.className = "arrowdown";
				} else {
					$('roofcolorchooser').blindDown({duration:0.5});
					this.className = "arrowup";
				}
			});
		}
		if ($('trimcolorname')){
			Event.observe('trimcolorname','click',function(e){
				Event.stop(e);
				if ($('trimcolorchooser').visible()){
					$('trimcolorchooser').blindUp({duration:0.5});
					this.className = "arrowdown";
				} else {
					$('trimcolorchooser').blindDown({duration:0.5});
					this.className = "arrowup";
				}
			});
		}

		$$('a.color').each(function(obj){
			Event.observe(obj,'click',function(e){
				Event.stop(e);
				var section = obj.parentNode.id.sub('chooser','');
				$(section+'name').update(this.innerHTML);
				$(section+'value').value = this.title;
				$(section).className = obj.className.sub('color','smallcolor');
			});
		});

		if ($('customizebuildinglink')){
			Event.observe('customizebuildinglink','click',function(e){
				Event.stop(e);
				new Effect.Appear('custombuildingdata');
				$('customizespan').fade({duration:0.2});
				$('custom').value = 1;
			});
		}
		
		if ($('sitestate')){
			Event.observe('sitestate','change',function(e){
				var state = $F('sitestate');
				new Ajax.Request(dir+"/lib/request.php",{
					parameters : "r=county&state="+state,
					onCreate : function(){
						
					},
					onSuccess : function(resp){
						$('sitecounty').options.length = 0;
						resp.responseJSON.each(function(county){
							var option = new Option(county.county,county.county);
							$('sitecounty').appendChild(option);
						});
					}
				});
			});
		}
		
		Event.observe('quote','submit',function(e){

			Event.stop(e);

			val = validateform('quote');
			if (val===true){
				$('quote').submit();
			} else {
				$(val).focus();
			}
		});

	}
	
	if ($('lquote')){

		Event.observe('lquote','submit',function(e){

			Event.stop(e);

			val = validateform('lquote');
			if (val===true){
				$('lquote').submit();
			} else {
				$(val).focus();
			}
		})
	}

	if ($('contactmsg')){

		Event.observe('contactmsg','submit',function(e){

			Event.stop(e);

			val = validateform('contactmsg');
			if (val===true){
				var values = $('contactmsg').serialize();
				new Ajax.Request(dir+"/lib/request.php",{
					parameters : "r=c&"+values,
					onCreate : function(){
						$('msgsendbtn').disabled = true;
						$('contactsubmitrow').hide();
						$('contactloader').show();
					},
					onSuccess : function(){
						$('msgsendbtn').disabled = false;
						$('contactloader').hide();
						$('contactthankyou').show();
						//pageTracker._trackPageview(dir+"/thankyou?t=4");
						_gaq.push(['_trackPageview', "/thankyou?t=4"]);
					}
				});
			} else {
				$(val).focus();
			}
		})
	}

	if ($('exportform')){
		Event.observe('exportform','submit',function(e){
			Event.stop(e);

			val = validateform('exportform');
			if (val===true){
				var values = $('exportform').serialize();
				new Ajax.Request(dir+"/lib/request.php",{
					parameters : "r=e&"+values,
					onCreate : function(){
						$('exportsend').disabled = true;
						$('exportsend').hide();
						$('exportloader').show();
					},
					onSuccess : function(){
						$('exportsend').disabled = false;
						$('exportloader').hide();
						$('exportthankyou').show();
						//pageTracker._trackPageview(dir+"/thankyou?t=5");
						_gaq.push(['_trackPageview', "/thankyou?t=5"]);
					}
				});
			} else {
				$(val).focus();
			}
		});
	}

	if ($('specialinquiry')){
		Event.observe('specialinquiry','submit',function(e){
			Event.stop(e);

			val = validateform('specialinquiry');
			if (val===true){
				$('specialinquiry').submit();
			} else {
				$(val).focus();
			}
		});
	}
	
	if ($('greenbuildingform')){
		Event.observe('greenbuildingform','submit',function(e){
			Event.stop(e);

			val = validateform('greenbuildingform');
			if (val===true){
				$('greenbuildingform').submit();
			} else {
				$(val).focus();
			}
		});
	}

	if ($('calculatefinancing')){
		Event.observe('calculatefinancing','click',function(e){
			Event.stop(e);
			if (!isNaN($F('price'))){
				new Ajax.Request(dir+"/lib/request.php",{
					parameters : "r=f&price="+$F('price'),
					onCreate : function(){
						$('calculatefinancing').disabled = true;
					},
					onSuccess : function(response){
						$('calculatefinancing').disabled = false;
						$('monthly').update("<strong>"+response.responseText+"</strong> for 60 months");
					}
				});
			}
		})
	}

	$$('.privacypolicylink').each(function(obj){
		Event.observe(obj,'click',function(e){
			Event.stop(e);
			window.open(dir+'/privacy-policy?sa','','scrollbars=yes,menubar=no,height=400,width=600,resizable=yes,toolbar=no,location=no,status=no');
		});
	});
	
	$$('.livechatlink').each(function(obj){
		Event.observe(obj,'click',function(e){
			Event.stop(e);
			window.open(dir+'/livesupport/livezilla.php','', 'width=500,height=500,left=0,top=0,resizable=yes,menubar=no,location=no,status=yes,scrollbars=yes');
			
			switch (obj.id){
				case "smallchatlink":
					var pushedchatbutton = "Small chat button on the top";
				break;
				
				case "quotechatlink":
					var pushedchatbutton = "Chat banner on top of quote";
				break;
				
				case "contactchatlink":
					var pushedchatbutton = "Chat link over contact form";
				break;
			}
			
			_gaq.push(['_trackEvent', 'Chat open', pushedchatbutton]);
			
		});
	});
	
	$$('a').each(function(linkobj){
		if (linkobj.hostname != location.hostname) {
			Event.observe(linkobj,'click',function(e){
				_gaq.push(['_trackEvent', 'Outgoing link', linkobj.hostname,linkobj.href]);
			});
		}
	});
	
	if ($('brochureimglink')){
		Event.observe('brochureimglink','click',function(e){
			_gaq.push(['_trackEvent', 'Download', 'Brochure','imagelink']);
		});
	}
	
	if ($('brochuretextlink')){
		Event.observe('brochuretextlink','click',function(e){
			_gaq.push(['_trackEvent', 'Download', 'Brochure','textlink']);
		});
	}
	
	if ($('thankyoubrochurelink')){
		Event.observe('brochuretextlink','click',function(e){
			_gaq.push(['_trackEvent', 'Download', 'Brochure','thankyou textlink']);
		});
	}
	
	if ($('thankyoubrochureimagelink')){
		Event.observe('brochuretextlink','click',function(e){
			_gaq.push(['_trackEvent', 'Download', 'Brochure','thankyou imagelink']);
		});
	}
	
	if ($('showmoredeliverylink')){
		Event.observe('showmoredeliverylink','click',function(e){
			Event.stop(e);
			$('short30days').hide();
			$('long30days').show();
		});
	}
	
	if ($('featuredreferral')){
		new Carousel('carousel-wrapper', $$('#carousel-content .slide'), $$('a.carousel-control', 'a.carousel-jumper'),{wheel:false,auto:true,circular:true,duration:0.5,frequency:8});
	}
	
	if ($('sidetestimonials')){
		$$('.hometestimonialpic').each(function(pic){
			Event.observe(pic,'mouseover',function(){
				pic.src = pic.src.sub('-g','');
			});
			Event.observe(pic,'mouseout',function(){
				pic.src = pic.src.sub('/64/','/64-g/');
			});
		});
	}

}