/*
 * Renewal Windows site custom JavaScript
 * Copyright 2011 Mosquito Interactive
 * Original developer Michael Burrows
 * Version 1.0 - 01 August 2011
 */
// define variables
showroom = '';
phoneNumber = '';
drtvPromoCode = '';
customPromo = '';
pageCustomized = false;

//JQuery
$(document).ready(function() {
	
	// fix png images
	$(document).pngFix();
	
	// add class to the menu item set in a variable on each page
	if (typeof(sidebarPos) != 'undefined') {
		sidebarPos = 'sidebar-' + sidebarPos;
		$('#content').addClass(sidebarPos);
	} else {
		$('#content').addClass('sidebar-right');
	}
	
	// configure any links that have a rel of prettyPhoto
	$("a[rel^='prettyPhoto']").prettyPhoto({
		deeplinking:false,
		social_tools:false,
		theme:'light_rounded',
		opacity: 0.40,
		show_title: false,
		horizontal_padding: 10,
		markup: '<div class="pp_pic_holder"> \
						<div class="ppt">&nbsp;</div> \
						<div class="pp_content_container"> \
							<a class="pp_close" href="#">Close</a> \
								<div class="pp_content"> \
									<div class="pp_loaderIcon"></div> \
									<div class="pp_fade"> \
										<a href="#" class="pp_expand" title="Expand the image">Expand</a> \
										<div class="pp_hoverContainer"> \
											<a class="pp_next" href="#">next</a> \
											<a class="pp_previous" href="#">previous</a> \
										</div> \
										<div id="pp_full_res"></div> \
										<div class="pp_details"> \
											<div class="pp_nav"> \
												<a href="#" class="pp_arrow_previous">Previous</a> \
												<p class="currentTextHolder">0/0</p> \
												<a href="#" class="pp_arrow_next">Next</a> \
											</div> \
											<p class="pp_description"></p> \
											{pp_social} \
										</div> \
									</div> \
								</div> \
						</div> \
					</div> \
					<div class="pp_overlay"></div>'
	});
	
	// round corners
	$('#primary-nav a').corner('6px');
	$('.inline-form').corner('8px');
	$('.inline-form h2').corner('8px top');
	$('a.more-info').corner('6px');
	$('#key-features').corner('6px');
	$('#in-home-consultation-block').corner('6px');
	$('#tabs li a').corner('8px top');
	$('.tab-content').corner('8px bl right');
	$('.section').corner('8px');
	$('div.pp_content_container').corner('8px br left');
	$('.tooltip-content').corner('8px');
	
	// enable jcarousel
	$('#window-items').jcarousel({
		scroll: 1
	});
	
	// add functionality to the gallery thumbnails
	$('.thumbnail').click(function () {
		return false;
	});
	$('.thumbnail').click(function () {
		$('.thumbnail').removeClass('active');
		$(this).addClass('active');
		swapGalleryMainImage($(this).attr('href'));
	});
	
	// tabs
	$('#tabs li a').click(function() {
		return false;
	});
	$('#tabs li a').click(function() {
		showTab($(this));
	});
	initialTabSelection();
	
	// change location form
	$('#change-location').submit(function() {
		if ($('#zipcode-sidebar').val() != '') {
			customizePageByPostal($('#zipcode-sidebar').val());
		}
		return false;
	});
	$('#change-promo').submit(function() {
		if ($('#zipcode-promo-sidebar').val() != '') {
			customizePageByPostal($('#zipcode-promo-sidebar').val());
		}
		return false;
	});
	
	// add tool tips
	$('#colors li a, #hardware li a, .hardware-finishes td a').tooltip({
		delay: 0,
		fade: 250,
		showURL: false,
		track: true,
		top: 0,
		left: 12,
		fixPNG: true,
		opacity: 1.0,
		bodyHandler: function() { 
        	return $("<img/>").attr("src", this.href); 
    	}
	});
	
	// add quick view
	$('li.item').mouseover(
		function() {
			$('div.quick-view-exterior').hide();
			var divName = $(this).attr('id');
			divName = '#quick-view-' + divName;
			var position = $(this).offset();
			var xLoc = position.left + 'px';
			var yLoc = position.top + 'px';
			$(divName).css('left',xLoc);
			$(divName).css('top',yLoc);
			$(divName).show();
		}
	);
	$('div.jcarousel-next, div.jcarousel-prev, .accordion-header').mouseover(function() {
		$('div.quick-view-exterior').hide();
	});
	$('div.quick-view-exterior').mouseover(
		function() {
			$(this).show();
		}
	);
	$('div.quick-view-exterior, #door-items').mouseout(
		function() {
			$('div.quick-view-exterior').hide();
		}
	);
	
	// configure tooltip
	$('#what-to-expect-link').hover(
		function(){
		  var linkOffset = $(this).offset();
		  var topPosition = linkOffset.top-$('#tooltip-what-to-expect').outerHeight()-22;
		  if (topPosition < 0) {
			  topPosition = linkOffset.top+$(this).outerHeight()+22;
			  $('#tooltip-what-to-expect .notch-top').show();
			  $('#tooltip-what-to-expect .notch').hide();
		  } else {
			  $('#tooltip-what-to-expect .notch-top').hide();
			  $('#tooltip-what-to-expect .notch').show();
		  }
		  topPosition = topPosition + 'px';
		  $('#tooltip-what-to-expect').css('top',topPosition);
		  $('#tooltip-what-to-expect').fadeIn();
		},
		function(){
		  $('#tooltip-what-to-expect').fadeOut();
		}
	);
	
	// set the showroom variable if it is passed in
	var showroomParameter = getURLParameterByName('storeNumber');
	if (showroomParameter != null && showroomParameter != '') {
		showroom = showroomParameter;
	}
	
	// customize page for location by calling the proper code
	if ($.cookie('customization') != null && pageCustomized == false) {
		// customize page for campaigns
		customizePageForCampaign();
	} else if (typeof(showroom) != 'undefined' && showroom != '') {
		customizePageByStore(showroom);
	} else {
		getPostalCode();
	}
});

// find showroom
function findShowroom(formLocation) {
    var f;
    var zipcode;
	
	if (formLocation == 'undefined') {
		f = document.forms["showroom-finder"];
		zipcode = f.elements["zipcode"].value;
	} else if (formLocation == 'sidebar') {
		f = document.forms["showroom-finder-sidebar"];
		zipcode = f.elements["zipcode-sidebar"].value;
	} else {
		f = document.forms["showroom-finder"];
		zipcode = f.elements["zipcode"].value;
	}
    
    if (zipcode.length == 7) {
        //zipcode = (zipcode.length == 6) ? zipcode.substr(0, 3) + " " + zipcode.substr(3, 3) : zipcode;
        zipcode = zipcode.replace(" ", "");
    }
    
    location.href = "http://www.renewalbyandersen.com/showrooms/search.aspx?zipcode=" + zipcode;
}

// initial tab selection
function initialTabSelection() {
	var currentHash = window.location.hash;
	if (currentHash != '') {
		$('#tabs li a[href="' + currentHash + '"]').addClass('active');
		$(currentHash).show();
	} else {
		currentHash = $('#tabs li:first-child a').attr('href');
		$('#tabs li:first-child a').addClass('active');
		$(currentHash).show();
	}
}

// show tab
function showTab(tab) {
	var tabName = tab.attr('href');
	window.location.hash = tabName;
	hideTabs();
	tab.addClass('active');
	$(tabName).show();
}

// hide tabs
function hideTabs() {
	$('#tabs li a').removeClass('active');
	$('.tab-content').hide();
}

// get visitor postal code
function getPostalCode() {
	// define post url
	var url_post = "/apis/ipinfodb/get-zipcode.php";
	// make jquery ajax call
	$.ajax({
		type: "GET",
		url: url_post,
		dataType: "json",
		success: function(data){
			customizePageByPostal(data.postalcode);
		}
	});
}

// customize the page based on postal code
function customizePageByPostal(postal) {
	// define post url
	var url_post = "/apis/bolin/load-showrooms-xml.php";
	// make jquery ajax call
	$.ajax({
		type: "GET",
		url: url_post,
		data: {
			z: postal
		},
		dataType: "xml",
		success: function(xml){
			customizePage(xml);
		}
	});
}

// customize the page based on store number
function customizePageByStore(storeNum) {
	// set store number if not passed in
	if (storeNum == '') {
		storeNum = showroom;
	}
	// define post url
	var url_post = "/apis/bolin/load-showrooms-xml.php";
	// make jquery ajax call
	$.ajax({
		type: "GET",
		url: url_post,
		data: {
			sn: storeNum
		},
		dataType: "xml",
		success: function(xml){
			customizePage(xml);
		}
	});
}

// customize page based on the returned xml
function customizePage(xml) {
	// if error display error message and default promo else parse data and customize page
	if ($(xml).find('error').text() != '') {
		// update the showroom list div
		$('#showroom-list').html('<p class="error">Renewal by Andersen does not currently have a showroom in your immediate area. In the interim, please <a href="http://www.renewalbyandersen.com/showrooms/view-all.aspx" onclick="_gaq.push([\'_link\', \'http://www.renewalbyandersen.com/showrooms/view-all.aspx\']); return false;">click here</a> to check for a Renewal by Andersen location in a neighboring area that might be able to assist you with your window and door replacement needs. Otherwise, please fill out the consultation form above and we will contact you when we come to your area.</p>');
		// hide the current promotion div and show the default promotion div
		$('#current-promotion').hide();
		$('#current-promotion').html('');
		$('#default-promotion').show();
		// set discliamer text
		$('#disclaimers').html('');
	} else {
		// set the showroom so the cookie isn't blank
		if (showroom == '') {
			var storeNumber = $(xml).find('market storeNumber').text();
			logToConsole('xml storeNumber: ' + storeNumber);
			showroom = storeNumber;
			writeCookieForSiteCustomization();
		}
		var promotions = $(xml).find('market promotions promotion');
		var locations = $(xml).find('market locations item');
		var today = new Date();
		var year = today.getFullYear();
		var month = today.getMonth()+1;
		var day = today.getDate();
		var areaText = $(xml).find('market area').text();
		logToConsole('areaText: ' + areaText);
		//set h1 text based on market name
		var fullMarketText = ' in ' + areaText;
		$('#h1_market_name').text(fullMarketText);
		// show the promotions else show no promotion text
		if (promotions.length > 0 && customPromo == '') {
			var promotionData = '';
			var disclaimerData = '';
			promotions.each(function () {
				var startDate = $(this).find('startDate').text();
				var endDate = $(this).find('endDate').text();
				disclaimerData += '<p>The information on this page has been provided by the ' + areaText + ' Renewal by Andersen Showroom and has been reprinted with their permission. This retailer is solely responsible for the content of the information provided and Renewal by Andersen Corporation assumes no responsibility in this regard. Some Renewal by Andersen locations are independently owned and operated. License number available upon request.</p>';
				disclaimerData += '<p>*DETAILS OF OFFER: Offer valid ' + startDate + ' - ' + endDate + '. Not valid with other offers or prior purchases. Ask for complete details. Approved credit for qualified buyers. Available only at participating locations. "Renewal by Andersen" and the Renewal by Andersen logo are registered trademarks of Andersen Corporation. All other marks where denoted are marks of Andersen Corporation. &copy;2011 Andersen Corporation. All rights reserved.</p>';
				var startDateArray = startDate.split('/');
				var startYear = startDateArray[2];
				var startMonth = startDateArray[0];
				var startDay = startDateArray[1];
				var endDateArray = endDate.split('/');
				var endYear = endDateArray[2];
				var endMonth = endDateArray[0];
				var endDay = endDateArray[1];
				// check to see if the promotion is in the future
				if (endYear >= year && endMonth == month && endDay >= day) {
					promotionData += $(this).find('description').text();
					disclaimerData += '<p>' + $(this).find('disclaimer').text() + '</p>';
				} else if (endYear >= year && endMonth > month) {
					promotionData += $(this).find('description').text();
					disclaimerData += '<p>' + $(this).find('disclaimer').text() + '</p>';
				} else {
					// hide the current promotion div and show the default promotion div
					$('#current-promotion').hide();
					$('#current-promotion').html('');
					$('#default-promotion').show();
				}
			});
			// load and show the current promotion div and hide the default promotion div
			$('#default-promotion').hide();
			$('#current-promotion').html(promotionData);
			$('#current-promotion').show();
			// set discliamer text
			$('#disclaimers').html(disclaimerData);
		} else {
			if (customPromo != '') {
				customizePromotion();
			} else {
				// set the current promotion to reflect that there isn't a promotion
				$('#current-promotion').show();
				$('#current-promotion').html('<h3>Current Offer</h3><p>Contact your local showroom for details.</p>');
				$('#default-promotion').hide();
				// set discliamer text
				$('#disclaimers').html('');
			}
		}
		// show the locations else show no locations message
		if (locations.length > 0) {
			var locationData = '';
			var locationNumber = 1;
			locations.each(function () {
				var className = 'showroom-' + locationNumber;
				locationData += '<div class="showroom ' + className + '">';
				locationData += '<p>';
				locationData += '<strong>' + $(this).find('city').text() + '</strong>';
				locationData += '<br>' + $(this).find('address1').text() + '';
				locationData += '<br>' + $(this).find('city').text() + ', ' + $(this).find('state').text() + ' ' + $(this).find('zipcode').text() + '';
				if ($(this).find('landMark').text() != '') {
					locationData += '<br><span class="landmark">' + $(this).find('landMark').text() + '</span>';
				}
				locationData += '</p>';
				// append store hours if there are any
				if ($(this).find('storeHours1').text() != '') {
					locationData += '<p>';
					locationData += '<strong>Store Hours:</strong>';
					locationData += '<br>' + $(this).find('storeHours1').text() + '';
					if ($(this).find('storeHours2').text() != '') {
						locationData += '<br>' + $(this).find('storeHours2').text() + '';
					}
					if ($(this).find('storeHours3').text() != '') {
						locationData += '<br>' + $(this).find('storeHours3').text() + '';
					}
					locationData += '</p>';
				}
				locationData += '</div>';
				locationNumber++;
			});
			// update the showroom list div
			$('#showroom-list').html(locationData);
		} else {
			// update the showroom list div
			$('#showroom-list').html('<p class="error">Renewal by Andersen does not currently have a showroom in your immediate area. In the interim, please <a href="http://www.renewalbyandersen.com/showrooms/view-all.aspx" onclick="_gaq.push([\'_link\', \'http://www.renewalbyandersen.com/showrooms/view-all.aspx\']); return false;">click here</a> to check for a Renewal by Andersen location in a neighboring area that might be able to assist you with your window and door replacement needs. Otherwise, please fill out the consultation form above and we will contact you when we come to your area.</p>');
		}
	}
}

// load the promotion from api
function loadPromotion() {
	var url_post = "/apis/bolin/load-showrooms-xml.php";
	
	// load sample data if the showroom is set to nan
	// used for testing all functionality
	if (showroom == 'nan') {
		url_post = "/apis/bolin/sample-data.xml";
	}
	
	$.ajax({
		type: "GET",
		url: url_post,
		data: {
			sn: showroom
		},
		dataType: "xml",
		success: function(xml){
			var events = $(xml).find('market events item');
			var promotions = $(xml).find('market promotions promotion');
			var locations = $(xml).find('market locations item');
			var today = new Date();
			var year = today.getFullYear();
			var month = today.getMonth()+1;
			var day = today.getDate();
			// show the promotions when there are promotions
			if (promotions.length > 0) {
				var promotionData = '';
				promotions.each(function () {
					var startDate = $(this).find('startDate').text();
					var endDate = $(this).find('endDate').text();
					var startDateArray = startDate.split('/');
					var startYear = startDateArray[2];
					var startMonth = startDateArray[0];
					var startDay = startDateArray[1];
					var endDateArray = endDate.split('/');
					var endYear = endDateArray[2];
					var endMonth = endDateArray[0];
					var endDay = endDateArray[1];
					// check to see if the promotion is in the future
					if (endYear >= year && endMonth == month && endDay >= day) {
						promotionData += $(this).find('description').text();
					} else if (endYear >= year && endMonth > month) {
						promotionData += $(this).find('description').text();
					}
				});
				// update the current promotion div with the promotion data
				$('#current-promotion').html(promotionData);
			}
		}
	});
}
// swap gallery main image
function swapGalleryMainImage(filePath) {
	$('#main-gallery-image').attr('src',filePath);
}
// navigate to the previous or next gallery photo
function gotoGalleryImage(direction) {
	var currentPhotoPath = $('#main-gallery-image').attr('src');
	var photoList = $('#thumbnails').find('a');
	var currentPhotoNumber = 0;
	var swapPhotoNumber = 1;
	photoList.each(function () {
		if ($(this).attr('href') == currentPhotoPath) {
			return false;
		}
		currentPhotoNumber++;
	});
	if (direction == 'next' && currentPhotoNumber < photoList.length-1) {
		swapPhotoNumber = currentPhotoNumber+1;
	} else if (direction == 'prev' && currentPhotoNumber > 0) {
		swapPhotoNumber = currentPhotoNumber-1;
	} else if (direction == 'prev' && currentPhotoNumber == 0) {
		swapPhotoNumber = photoList.length-1;
	} else {
		swapPhotoNumber = 0;
	}
	var newPhotoPath = photoList[swapPhotoNumber];
	newPhotoPath = newPhotoPath.toString();
	var newPhotoPathArray = newPhotoPath.split('/');
	swapGalleryMainImage('/'+newPhotoPathArray[newPhotoPathArray.length-2]+'/'+newPhotoPathArray[newPhotoPathArray.length-1]);
}
// 
function setLocationValue(which) {
	if (which != 0 || which != "") {
		var dropDownList = document.inquiry.regarding;
		
		for (i = 0; i< dropDownList.options.length; i++) {    
			if (dropDownList.options[i].value == which) {
				dropDownList.options[i].selected = true;
				break;
			}
		}
	}
}

function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
	}
}

function clickrecall(thisfield, defaulttext) {
	if (thisfield.value == "") {
		thisfield.value = defaulttext;
	}
}

function submitSearch() {
	YY_checkform('searchform','searchkeywords','#q','0','Please enter your search terms in the field below.');	
	if (document.MM_returnValue) {
		if (curPageType == 0) {
			if (curClientType == 1) { //SEO Network
				document.searchform.action = "/search/";
				document.searchform.submit();
			}
			if (curClientType == 2) { //Product Based
				document.searchform.action = "/srch/";
				document.searchform.submit();
			}
		} else {
			document.searchform.action = "/search-custom/";
			document.searchform.submit();
		}
	}
}

function setSlideStyle(current) {
	if (current == promotionHeadlines.length) {
		current = 0;
	}
	for (i = 0; i < promotionHeadlines.length; i++) {
		document.getElementById(promotionHeadlines[i]).className = 'div_feature';
	}
	document.getElementById(promotionHeadlines[current]).className = 'div_feature_selected';
}
// set a rolling date
function setRollingDates() {
	getServerDate();
}
// load the server date
function getServerDate() {
	var scriptURL = '/ajax/get-date.php';
	$.ajax({
	  url: scriptURL,
	  success: function(data) {
		parseServerDate(data);
	  }
	});
}
// parse a date return from the server
function parseServerDate(dateString) {
	serverDateArray = dateString.split('/');
	calculateRollingDate(serverDateArray);
}
// calculate a rolling date
function calculateRollingDate(dateArray) {
	var currentTime = new Date(dateArray[2],dateArray[0],dateArray[1]);
	var date = currentTime.getDate();
	var month = currentTime.getMonth();
	var year = currentTime.getFullYear();
	// check to see if the date is within 7 days of the end of the year
	if (date+7 >= daysInMonth(month,year) && month == 11) {
		year = year+1;
		month = 0;
		date = 15;
	} else if (date+7 >= daysInMonth(month,year)) {
		month = month+1;
		date = 15;
	} else if (date+7 >= 15) {
		date = daysInMonth(month,year);
	} else {
		date = 15;
	}
	rollingDate = month+'/'+date+'/'+year;
	$('.rolling-date').text(rollingDate)
}
// calculate the days in the month
function daysInMonth(month,year) {
	var dd = new Date(year, month+1, 0);
	return dd.getDate();
} 
// track an event with GA
function trackEvent(elementRef, param1, param2, param3) {
	// get the href from the link
	virtualLink = $(elementRef).attr('href');
	// push an event to track external links
	_gaq.push(['_trackEvent', param1, param2, param3]);
}
// track a page view with GA
function trackPageview(elementRef) {
	// get the href from the link
	virtualLink = $(elementRef).attr('href');
	// push a page view to GA
	_gaq.push(['_trackPageview', virtualLink]);
}
// track an external link with GA
function trackExternalLink(elementRef, param1, param2) {
	// get the href from the link
	redirectLink = $(elementRef).attr('href');
	// get the target from the link
	linkTarget = $(elementRef).attr('target');
	// push an event to track external links
	if (param1 == undefined && param2 == undefined) {
		_gaq.push(['_trackEvent', 'Outgoing links', 'Click', redirectLink]);
	} else if (param2 == undefined) {
		_gaq.push(['_trackEvent', param1, 'Click - Outgoing links', redirectLink]);
	} else {
		_gaq.push(['_trackEvent', param1, param2, redirectLink]);
	}
	// if the link is not opening in a new window delay the link
	if (linkTarget != '_blank') {
		setTimeout('document.location = "' + redirectLink + '"', 100);
	}
}

function sendSiteTunerConversion(stConversionType, stCconversionValue, callbackURL) {
	var url_post = "/apis/sitetuners/postConversion.php";
	
	$.ajax({
		type: "POST",
		url: url_post,
		data: "stConversionType="+ stConversionType +"& stCconversionValue="+ stCconversionValue,
		success: function(msg){
			if (callbackURL != undefined) {
				var target = callbackURL.target;
				if (target == '_blank') {
					window.open(callbackURL);
				} else {
					location.href = callbackURL;
				}
			}
		}
	});
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function getParameterByName(name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null) {
	var cookieValue = $.cookie('RBAShowroom');
	logToConsole('RBAShowroom cookieValue: ' + cookieValue);
	if (cookieValue != '' && cookieValue != null && cookieValue != 'undefined' && typeof(cookieValue) != 'undefined') {
		return cookieValue;
	}
  } else {
    var showroom_value = decodeURIComponent(results[1].replace(/\+/g, " "));
	createCookie("RBAShowroom", showroom_value, 30);
	return showroom_value;
  }
}

function getURLParameterByName(name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if (results != null) {
	var showroomValue = decodeURIComponent(results[1].replace(/\+/g, " "));
  	return showroomValue;
  } else {
	return '';
  }
}

//Macromedia Functions
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
// form validator
function YY_checkform() { //v4.71
//copyright (c)1998,2002 Yaromat.com
  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+4){
    if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
    o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
    o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
    v=o.value;t=a[i+2];
    if (o.type=='text'||o.type=='password'||o.type=='hidden'){
      if (r&&v.length==0){err=true}
      if (v.length>0)
      if (t==1){ //fromto
        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
      } else if (t==2){
        rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
      } else if (t==3){ // date
        ma=a[i+1].split("#");at=v.match(ma[0]);
        if(at){
          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
          dte=new Date(cy,cm,cd);
          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
        }else{err=true}
      } else if (t==4){ // time
        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
      } else if (t==5){ // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){err=true}
      } else if (t==6){ // the same
            if(v!=MM_findObj(a[i+1]).value){err=true}
      }
    } else
    if (!o.type&&o.length>0&&o[0].type=='radio'){
          at = a[i].match(/(.*)\[(\d+)\].*/i);
          o2=(o.length>1)?o[at[2]]:o;
      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
      if (t==2){
        oo=false;
        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
        if(!oo){s+='* '+a[i+3]+'\n'}
      }
    } else if (o.type=='checkbox'){
      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
    } else if (o.type=='select-one'||o.type=='select-multiple'){
      if(t==1&&o.selectedIndex/1==0){err=true}
    }else if (o.type=='textarea'){
      if(v.length<a[i+1]){err=true}
    }
    if (err){s+='* '+a[i+3]+'\n'; err=false}
  }
  if (s!=''){alert('The required information is incomplete or contains errors:\t\t\t\t\t\n\n'+s)}
  document.MM_returnValue = (s=='');
}
// parse a parameter from a string
function parseStrForParam(param1, param2) {
	var str = param2;
	if ((str == null) || (str == "")) {
		return "";
	} else {
		if (str.indexOf(param1) == -1) {
			return "";
		}
		var startString = str.substr(str.indexOf(param1) + (param1.length + 1));
		var end = (startString.indexOf("&") != -1) ? (startString.indexOf("&")) : startString.length;
		var answer = startString.substr(0,end);
		return answer;
	}
}

// log something to the console
function logToConsole(aValue) {
	if (typeof(console) != 'undefined') {
		console.log(aValue);
	}
}

/* 
 * Use for redirecting to other sites when GA UTM needs to be passed
 */
function redirectForGAWithParams(theURL) {
	_gaq.push(['_link', theURL]);
}

/*
 * 
 * Page Customization Code
 * Copyright 2011 Mosquito Interactive
 * Original developer Michael Burrows
 * Version 1.0 - 24 August 2011
 * 
 */
// write a cookie for site customization
function writeCookieForSiteCustomization() {
	if (typeof(drtvPromoCode) != 'undefined' && typeof(phoneNumber) != 'undefined') {
		var cookieValue = drtvPromoCode + '|' + phoneNumber + '|' + showroom;
		logToConsole('cookieValue: ' + cookieValue);
		$.cookie('customization', cookieValue, { expires: 30, path: '/' });
	} else if(typeof(showroom) != 'undefined') {
		var cookieValue = '||' + showroom;
		logToConsole('cookieValue: ' + cookieValue);
		$.cookie('customization', cookieValue, { expires: 30, path: '/' });
	}
	if (pageCustomized == false) {
		customizePageForCampaign();
	}
}

// write a cookie for a custom promotion
function writeCookieForCustomPromo() {
	if (typeof(customPromo) != 'undefined' && customPromo != '') {
		var cookieValue = customPromo;
		logToConsole('promo cookieValue: ' + cookieValue);
		$.cookie('customPromotion', cookieValue, { expires: 30, path: '/' });
	}
}

// customize the phone number in all locations wrapped by a class of phone-number
function customizePhoneNumber() {
	$('.phone-number').html(phoneNumber);
}

// customize the form company referrer value
function customizeFormReferrer() {
	$('#consultation-form #company-referrer').val(drtvPromoCode);
}

// customize the promotion and disclaimer
function customizePromotion() {
	var promoArray = customPromo.split('|');
	$('#current-promotion').load('/content-block.php?ajax=true&id=' + promoArray[0]);
	$('#disclaimers').load('/content-block.php?ajax=true&id=' + promoArray[1]);
}

// parse customization values from a cookie
function parseCustomizationFromCookie() {
	var cookieValue = $.cookie('customization');
	logToConsole('cookieValue: ' + cookieValue);
	if (cookieValue != '' && cookieValue != null) {
		var cookieArray = cookieValue.split('|');
		drtvPromoCode = cookieArray[0];
		phoneNumber = cookieArray[1];
		showroom = cookieArray[2];
	} else {
		return false;
	}
}

// parse custom promotion from cookie
function parseCustomPromoFromCookie() {
	var cookieValue = $.cookie('customPromotion');
	logToConsole('promo cookieValue: ' + cookieValue);
	if (cookieValue != '' && cookieValue != null) {
		customPromo = cookieValue;
	} else {
		return false;
	}
}

// customize page for a given campaign
function customizePageForCampaign() {
	pageCustomized = true;
	// if there are no values for the campaign variable attempt parsing from the cookie
	if (phoneNumber == '' || drtvPromoCode == '' || showroom == '') {
		parseCustomizationFromCookie();
	}
	// if there isn't a value for custom promo
	if (customPromo == '') {
		parseCustomPromoFromCookie();
	}
	// customize phone
	if (typeof(phoneNumber) != 'undefined' && phoneNumber != '') {
		customizePhoneNumber();
	}
	// customize referrer
	if (typeof(drtvPromoCode) != 'undefined' && drtvPromoCode != '') {
		customizeFormReferrer();
	}
	// customize for showroom
	if (typeof(showroom) != 'undefined' && showroom != '') {
		customizePageByStore(showroom);
	}
	// customize promo
	if (typeof(customPromo) != 'undefined' && customPromo != '') {
		customizePromotion();
	}
}

