var rh_imgcount;
var rh_currentimg = 0;
var rh_nextimg = 1;

$(function() {

	// round corners for IE
	if (_browser.indexOf("IE") == 0) {
		$(".rounded").each(rounded);
	}

	// Add appointment form div to body
	$("body").append('<div class="AppointmentModal aptform"></div>');

	// Functions for IE7 only
	if (_browser.indexOf("IE7") == 0) {
		incCSS("/_CSS/ie7.css");
		$(".genericcontent .CMSTreeMenuTable").each(function() {
			$("td", $("tbody tr", $(this)).last()).css("padding-bottom", "30px");
		});

		$(".productInStockTable").each(function() {
			$("td", $("tbody tr", $(this)).last()).css("padding-bottom", "30px");
		});
	}

	// rotator image module
	var rotatorPtr = $(".rotator");
	$(".browse", rotatorPtr).live("click", function() {
		var leftBool = $(this).hasClass("left");
		var imgPtr = $(".items img", rotatorPtr);
		var img = $(".items img.active", rotatorPtr);
		img = (leftBool) ? img.prev("img") : img.next("img");
		if (img.length == 0) {
			img = (leftBool) ? imgPtr.last() : imgPtr.first();
		}
		img.click();
	});
	$(".rotator .items img").click(function() {
		if ($(this).hasClass("active")) { return; }
		var url = $(this).attr("src").replace("_thumb", "");
		var wrap = $(".rotator .image").fadeTo("medium", 0.5);
		var img = new Image();
		img.onload = function() {
			wrap.fadeTo("fast", 1);
			wrap.html("<img src=\"" + url + "\" alt=\"\" />");
		};
		img.src = url;
		$(".items img").removeClass("active");
		$(this).addClass("active");
	}).filter(":first").click();

	// color profile
	var colorProfilePtr = $(".filter .panes .colorProfile");
	var colorProfileTabsPtr = $(".filter .tabs .colorProfile div");
	$("a", colorProfilePtr).click(function(e) {
		e.preventDefault();
		$("option", colorProfilePtr).removeAttr("selected").eq(0).attr("selected", "selected");
	});
	$("li", colorProfilePtr).click(function() {
		$("li", colorProfilePtr).removeClass("active");
		$(this).toggleClass("active");
		$("option", colorProfilePtr).removeAttr("selected").eq($(this).index() + 1).attr("selected", "selected");
	});

	// filter tabs
	$(".filter .tabs").tabs(".filter .panes > div:not(.button)");
	var filterPanesPtr = $(".filter .panes");
	$(".button", filterPanesPtr).click(function(e) {
//		e.preventDefault();
		var filterTxtPtr = $(".filter .tabs li h4");
		var filterValPtr = $("form select", filterPanesPtr);
		filterValPtr.each(function(index) {
			filterTxtPtr.eq(index).html($(this).val());
		});
		if ($("option:selected", colorProfilePtr).index() == 0) {
			colorProfileTabsPtr.hide();
		} else {
			colorProfileTabsPtr.show();
			$("img", colorProfileTabsPtr).css("top", (-15 * $(".active", colorProfilePtr).index()) + "px");
		}
	});
	
	// filter options - toggle between less/more
	$("#view_less").click(function() {
		$(".pane_more").hide();
		$("#view_less").hide();
		$("#view_more").show();
	});
	$("#view_more").click(function() {
		$(".pane_more").show();
		$("#view_more").hide();
		$("#view_less").show();
	});

	// About Our Pricing Codes
	$(".aboutPricing h2").add(".aboutPricing .close").click(aboutPricingToggle);
	function aboutPricingToggle() {
		$(".aboutPricing h2").toggleClass("contract");
		$(".aboutPricing > div").toggle();
	}

	// Product Detail Make Appointment
	$(".modAppt .button a[rel]").overlay({
		mask: {
			color: "#000",
			loadSpeed: 200,
			opacity: 0.5
		}
	});

	// Global Make Appointment
	$(".miniNav .button a[rel]").overlay({
		mask: {
			color: "#000",
			loadSpeed: 200,
			opacity: 0.5
		}
	});

	// Hero Make Appointment
	$(".hero .herobutton a[rel]").overlay({
		mask: {
			color: "#000",
			loadSpeed: 200,
			opacity: 0.5
		}
	});

	$(".miniNav .button a").click(function(e) {
		//e.preventDefault();
		closeAptForm();
	});

	$(".hero .herobutton a").click(function(e) {
		//e.preventDefault();
		closeAptForm();
	});

	$(".modAppt .button a").click(function(e) {
//		e.preventDefault();
		closeAptForm();
	});

	function closeAptForm() {
	    $("div.aptform").load("/MarbleAndGranite/CMSTemplates/FindAFabricator/RequestQuote.aspx .formmodal", function() {
			$("div.aptform a[rel]").overlay({
				mask: {
					color: "#000",
					loadSpeed: 200,
					opacity: 0.5
				},
				closeOnClick: false
			});
			$("div.aptform a.close, #exposeMask").click(function() {
				$("div.aptform").html("").css("display", "none");
			});
		});
	}

	// Product Detail More Photos
	$(".morePhotosModal").each(function(){$(this).appendTo("form"); });
	$(".morePhotos a[rel]").overlay({
		mask: {
			color: "#000",
			loadSpeed: 200,
			opacity: 0.5
		}
	});
	$(".morePhotosModal .button a").click(function(e) {
		e.preventDefault();
	});
	$(".modalPrevNext p").click(function() {
		if ($(this).hasClass("disabled")) {
			return;
		}
		var parentPtr = $(this).closest(".morePhotosModal");
		var prevBool = $(this).hasClass("prev");
		var imgPtr = $("li", parentPtr);
		var img = $("li.active", parentPtr);
		imgPtr.removeClass("active");
		img = (prevBool) ? img.prev("li") : img.next("li");
		if (img.length == 0) {
			img = (prevBool) ? imgPtr.last() : imgPtr.first();
		}
		var imgIndex = img.index();
		img.addClass("active");
		if (imgIndex == 0) {
			$(".prev", parentPtr).addClass("disabled");
		} else {
			$(".prev", parentPtr).removeClass("disabled");
		}
		if (imgIndex == imgPtr.length - 1) {
			$(".next", parentPtr).addClass("disabled");
		} else {
			$(".next", parentPtr).removeClass("disabled");
		}
		$(".photoNum", parentPtr).html((imgIndex + 1) + " of " + imgPtr.length + " Photos");
		var url = img.html();
		var wrap = $(".image", parentPtr).fadeTo("medium", 0.5);
		var img = new Image();
		img.onload = function() {
			wrap.fadeTo("fast", 1);
			wrap.html("<img src=\"" + url + "\" alt=\"\" />");
		};
		img.src = url;
	}).filter(".next").click();

	// Product Detail Expand Contract
	$(".productInStockHeader").each(function(index) {
		if (index == 0) {
			$("p", $(this)).addClass("contract");
		} else {
			$(".productInStockTable", $(this).closest(".productDetailMod")).toggle();
		}
		$("p", $(this)).each(toggleInStockText);
		$(this).click(function() {
			$("p", $(this)).toggleClass("contract");
			$(".productInStockTable", $(this).closest(".productDetailMod")).toggle();
			$("p", $(this)).each(toggleInStockText);
		});
	});
	function toggleInStockText() {
		$(this).html(($(this).hasClass("contract")) ? "Collapse to hide" : "Expand to see available sizes and locations");
	}

	// Add files to homepage only
	if ($("body").hasClass('homepage')) {
		$(RotatingHeroConfig);

		if (!!$(".hero")) {
			$('.hero .slider').cycle({
				fx: 'scrollHorz',
				timeout:9000
			});
		}

		if (!!$(".trustedby")) {
			$('.trustedby .slider').cycle({
				fx: 'fade',
				timeout:3000
			});
		}

	}

	if (!!$("body.genericContent .genericcontent .faq")) {
		$(document).ready(function($) {
			$(".answer").hide();
			$(".show-answer").show();
			$(".hide_show").show();
			if ($(".show-answer").length < 1) {
				$(".answer:first").show();
			} else {
				// Slide Down to "show-answer" FAQ
				var targetOffset = $('.show-answer:first:visible').offset().top - 6;
				$('html,body').animate({ scrollTop: targetOffset }, 1000);
			}
			$(".hide_show a").toggle(function() {
				$('.answer').show();
				$(this).html("Hide All Answers");
				return false;
			}, function() {
				$('.answer').hide();
				$(this).html("Show All Answers");
				return false;
			});

			$(".question").click(function() {
				$(this).parent().next().slideToggle();
				return false;
			});
		});
	}
	
	//replace text registered
	$(document).ready(function($) {
		//$('body *').find(':not(textarea)').replaceText( /\b\&reg;\b/gi, '<sup>&reg;<\/sup>' );
	//	alert($('body *').find('&reg;').length);
		//$("body").html(
			//$("body").html().replace("®", "<sup>&reg;</sup>")
		//); 
		//$('body *').replace('&reg;', "<sup>&reg;</sup>");

	});

	
	
	// breadcrumbs
	if (!!$(".breadcrumbid")) {
		try {
			$(".breadcrumbid li").last().addClass('active');
		} catch (e) {
			//fail silently
		}
	}

	if (!!$(".callOutNav table")) {
		$(".callOutNav table").last().addClass("last");
		if (_browser.indexOf("IE7") == 0) {
			$(".CMSTreeMenuTable.last").each(function() {
				$("td", $("tbody tr", $(this)).last()).css("padding-bottom", "30px");
			});
		}
	}

	if (!!$("#siteSearchBox")) {
		var searchBox = $("input.siteSearchBox");
		var searchBoxValue;

		searchBox.focus(function() {
			searchBox = this;
			window.searchBoxValue = $(this).attr("value");
			$(searchBox).attr("value", "");
		});

		searchBox.blur(function() {
			searchBox = this;
			searchTemp = $(this).attr("value");
			searchTemp == "" ? "" : window.searchBoxValue = searchTemp;
			$(searchBox).attr("value", window.searchBoxValue);
		});
	}
	
	// ------------------------------------------------------------------------------
	// BEGIN: Default Input Value
	// On load - remove clear_value_off class if text box is pre-loaded with non-default value
	if($(".clear_value").length) {
		$(".clear_value").focus(function() {
			if ($(this).val() == $(this).attr("title")) {
				$(this).val("");
				$(this).removeClass("clear_value_off");
			}
		}).blur(function() {
			if ($(this).val() == "") {
				$(this).val($(this).attr("title"));
				$(this).addClass("clear_value_off");
			}
		});
	}
	// END: Default Input Value
	
	

	if (!!$(".results.fabricators")) {
		$(".fabricator.results .product:odd").addClass('odd');
		$(".fabricator.results .product p").parent().addClass('medium');
		$(".fabricator.results .product .logo").parent().removeClass('medium').addClass('full');
	}

	if (!!$(".copyright")) {
		var newDate = new Date();
		$(".copyright p.container").prepend("&copy; " + newDate.getFullYear() + " ");
	}

	// default input text
	$("input[type='text']", ".pageTitle").defaultText();
	
	
	$(".tooltip_link_wrapper a[rel]").overlay({
		mask: {
			color: "#000",
			loadSpeed: 200,
			opacity: 0.5
		},
		fixed: false
	});
	
	if ($.browser.msie && $.browser.version < 9) { 
		$('select.ie_expand').bind('focus mouseover', function() { 
			$(this).addClass('expand').removeClass('clicked'); 
		}).bind('click', function() { 
			$(this).toggleClass('clicked'); 
		}).bind('mouseout', function() { 
			if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }
		}).bind('blur', function() { 
			$(this).removeClass('expand clicked'); 
		});
	}
	/*
	if ($.browser.msie && $.browser.version < 9) $('select.wide')
    .bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); })
    .bind('click', function() { $(this).toggleClass('clicked'); })
    .bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }})
    .bind('blur', function() { $(this).removeClass('expand clicked'); });

	*/
	
	
	if(window.location.hash) {
		var hash = window.location.hash.substring(1);
		if($('.productInStockTable').length) {
			$('a', 'table.productInStockTable').each(function() {
				if($(this).attr('name') == hash) {
					if(!$(this).parents('table.productInStockTable').prev('div.productInStockHeader').find('p').hasClass('contract')) {
						$(this).parents('table.productInStockTable').prev('div.productInStockHeader').click();
					}
				}
			});
		}
	}
});

function RotatingHeroConfig(){

	try {
		window.rh_imgcount = $('.facts div.slide').length;
		$('.facts .slides').before('<span class=\"controller\"></span>');
		for(var i = 0; i < rh_imgcount ; i++) {
			var last = i == rh_imgcount ? last = "last" : last = "";
			$('.facts span.controller').append('<a class="link' + i + ' ' + last + '" href="javascript:RotatingHeroCrossFade(\'' + i + '\')">' + (i+1) + '</a>');
		}
		$('.facts span.controller a.link0').addClass('active');
	} catch (err) {
		// do nothing
	}
}

function RotatingHeroCrossFade(x){
	if ($('.facts div.item' + rh_currentimg).is(':animated')) {
		// do nothing
	}
	else{
		if(x != undefined && x != rh_currentimg){
				var selectedslide = parseFloat(x);
				$('.facts span.controller a').removeClass('active');
				$('.facts span.controller a.link' + selectedslide).addClass('active');
				$('.facts div.slide:eq(' + selectedslide + ')').show();
				$('.facts div.slide:eq(' + rh_currentimg + ')').hide();
		
				window.rh_currentimg = selectedslide;
				selectedslide == rh_imgcount ? window.rh_nextimg = 1 : window.rh_nextimg = selectedslide + 1;
			}
		else if(x == rh_currentimg){ console.log("second condition");
		}
		else{
			if(rh_currentimg != (rh_imgcount-1)){
				$('.facts span.controller a').removeClass('active');
				$('.facts span.controller a.link' + rh_nextimg).addClass('active');
				$('.facts div.slide:eq(' + rh_currentimg + ')').fadeOut(500);
				$('.facts div.slide:eq(' + rh_nextimg + ')').fadeIn(500);	

				window.rh_currentimg = rh_currentimg + 1;
				window.rh_nextimg = rh_nextimg + 1;
			}
			else{
				$('.facts span.controller a').removeClass('active');
				$('.facts span.controller a.link0').addClass('active');
				$('.facts div.slide:eq(' + rh_currentimg + ')').fadeOut(500);
				$('.facts div.slide:eq(0)').fadeIn(500);	
				window.rh_currentimg = 0;
				window.rh_nextimg = 1;
			}
		}
	}
}

function FabricatorResults(x){
	window.location = "?state=" + x.toString();
}

/* jsHandler.js */
function incJS(filename){
var head = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script);
}

function incCSS(filename){
var head = document.getElementsByTagName('head')[0];
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
head.appendChild(fileref);
}

/* Disables Kentico Onclick Event for Default left nav control */
function TreeMenuOnClick(){
  return false;
}
