var bannerVis = "show",
	jr = null;

// make the AJAX call by passing the URL they were going to load (this should be root relative)
function callAjax(id) {
	// abort any uncompleted AJAX requests
	if( jr !== null ) jr.abort();

	if( id !== undefined && id.toString() !== "" ) {
		// show the loader
		$("#rightCol").html('<div id="loader" />');

		// add/remove the 'is-view' class to the body for individual product/technology views
		if( location.href.indexOf("/view") !== -1 ) {
			$("body").addClass("is-view");
		} else {
			$("body").removeClass("is-view");
		}

		// grab new data for the left nav, banner and rightCol
		jr = $.getJSON("/ajaxLoad/?url="+id, null, function(data) {
			// add a view in google analytics
			_gaq.push(["_trackPageview", id]);
			initMetrics(id);

			// update the page title
			if( typeof(data.pageTitle) === "string" && data.pageTitle !== "" ) {
				document.title = data.pageTitle;
			}

			// load the menu
			$("#leftCol").html(data.navData);

			// individual item, hide the banner image
			if( data.bannerImg === "" ) {
				if( bannerVis !== "hide" ) {
					$("#guideContainer").slideUp("slow");
					bannerVis = "hide";
				}
			// we have a banner image for this category
			} else {
				if( bannerVis === "hide" ) {
					$("#guideContainer").html(data.bannerImg).slideDown("slow");
					bannerVis = "show";
				} else {
					$("#guideContainer").html(data.bannerImg);
				}
			}

			// load the item data
			$("#rightCol").html(data.itemData);

			// reload iFrames
			reloadIframe();

			// recall cufon after new product title and sub-title are inserted
			Cufon.replace("h1#title, h2#subtitle, .quick-video span");

			// add lens scrolling if needed
			initLensScrolling();

			if( $("#also ul:first").hasClass("hide-group") ) {
				$("#also .listHeader").hide();
			}

			if (!$("#also ul:first").length)
			{
				$("#also .listHeader").hide();
			}


			// setup tab support on refresh
			$("#product-quick-tabs, #product-detail-tabs").tabs();
		});
	}
}

function ajaxUpdateURL(url) {
	var sections = ["/products/", "/technology/","/pro/"];
	
	// rewrite the URL with the #, we'll update the URL after we rewrite it
	if( url.indexOf("/#/") === -1 ) {
		// make sure the URL ends with a /
		if( url.charAt(url.length - 1) !== "/" ) {
			url += "/";
		}

		for(s in sections) {
			// inject a # between the section and category portion of the URL
			url = url.replace(sections[s], sections[s]+"#/");
		}

		var newURL =  location.protocol + "//" + location.hostname + url;
		//------------------------------- DEV STUFF -----------------------------------//
		if( newURL.match("smith.tecture.net") != null ) {
			newURL = newURL.replace("smith.tecture.net", "smith.tecture.net:8080");
		} else if( newURL.match("smithqa.tecture.net") != null ) {
			newURL = newURL.replace("smithqa.tecture.net", "smithqa.tecture.net:8080");
		}

		// update URL in browser
		window.location.href = newURL;
	}
}

//make ajax call to change background image
function callAjaxBackgroud(id){
	if( id !== undefined && id.toString() !== "" ) {
		$.getJSON("/ajaxLoadBackground/?backgroundUrl="+id, null, function(data) {
			if(data === '../../images/bgs/'){
				data = "../../images/bgs/Branding_Background.jpg"
			}
			$("body").css({"background" : "url('" + data + "') no-repeat top center", "background-color" : "#000000"});
		});	
	}
}

function ajaxPageLoad() {
	// strip out things we don't want (<protocol>//<hostname></#/>)
	var url = location.pathname + location.hash.replace("#/", "");

	// pass the URL to our normal event handler for clicks
	ajaxUpdateURL(url);

	// load AJAX content
	callAjax(url);
}

function initMetrics(id){
	var s=s_gi(s_account);
	
	
	s.prop1 = s.prop2 = s.prop3 = s.prop4 = s.prop5 = undefined;
	purgeVars({prop:"prop",eVar:"eVar",events:"events"});
	
	
	str = id;
	//alert("str = " + str);
	// remove beginning and trailing slashes
	str = str.substring(1,str.length-1);
	// replace all +s from string
	str = str.replace(/\+/g," ");
	// split the string using slashes
	var arr = str.split("/");
	
	// get the channel
	var channel = arr[0].substring(0,1).toUpperCase()+arr[0].substring(1,arr[0].length-0);
	var prop = [];
	// hard coded
	prop[0] = "SOP";
	// get the rest of the propX values
	for(var i=1;i<arr.length;i++) {
		if (arr[i] == "view") { break; }
		prop[i] = arr[i]; 
	}
	 
	// init pagename variable
	var pagename = "";
	// start populating the pagename variable
	for(var i=0;i<prop.length;i++) {
		pagename += prop[i];
		// add :, the seperator if not the last element
		if (i != prop.length-1) pagename += ":";
	}
	if (arr.length <= 3) pagename += ":home";
	
	for(var i=0;i<3;i++) {
		eval("s.prop" + (i+1) + " = \"" + prop[i] + "\";");
	}
	if (arr.length == 4) { eval("s.prop4 = \"" + arr[3] + "\";"); }
	if (arr.length == 5) { eval("s.prop4 = undefined;"); eval("s.prop5 = \"" + arr[3] + "\";"); /*alert(arr[3]);*/ }
	if (arr.length == 6) { eval("s.prop4 = \"" + arr[3] + "\";"); eval("s.prop5 = \"" + arr[4] + "\";"); /*alert(arr[3]); alert(arr[4]);*/ }
	// do not delete this line
	//if (arr.length == 5 || arr.length == 6) { eval("s.prop4 = \"" + arr[3] + "\";"); eval("s.prop5 = \"" + arr[4] + "\";"); }
	//alert(pagename);
	eval("s.pageName = \"" + pagename + "\";");
	eval("s.hier1 = \"" + pagename + "\";");
	eval("s.channel = \"" + channel + "\";");
	
	if(s.prop5){ s.events="prodView"; }
	
     //s.prop1 = "Test Prop";
     s.t();
}
function parse(str) {
	// remove beginning and trailing slashes
	str = str.substring(1,str.length-1);
	// replace all +s from string
	str = str.replace(/\+/g," ");
	// split the string using slashes
	var arr = str.split("/");
	
	// get the channel
	var channel = arr[0].substring(0,1).toUpperCase()+arr[0].substring(1,arr[0].length-0);
	var prop = [];
	// hard coded
	prop[0] = "SOP";
	// get the rest of the propX values
	for(var i=1;i<arr.length;i++) {
		if (arr[i] == "view") { break; }
		prop[i] = arr[i]; 
	}
	
	// init pagename variable
	var pagename = "";
	// start populating the pagename variable
	for(var i=0;i<prop.length;i++) {
		pagename += prop[i];
		// add :, the seperator if not the last element
		if (i != prop.length-1) pagename += ":";
	}
	if (arr.length <= 3) pagename += ":home";
	
	for(var i=0;i<3;i++) {
		eval("s.prop" + (i+1) + " = \"" + prop[i] + "\";");
	}
	if (arr.length == 5) { eval("s.prop5 = \"" + arr[4] + "\";"); /*alert(arr[4]);*/ }
	if (arr.length == 6) { eval("s.prop4 = \"" + arr[3] + "\";"); eval("s.prop5 = \"" + arr[4] + "\";"); /*alert(arr[3]); alert(arr[4]);*/ }
	eval("s.pagename = \"" + pagename + "\";");
	eval("s.channel = \"" + channel + "\";");
	
	// return what we have
	return pagename;
}

function purgeVars(variableTypes){
	for (variableType in variableTypes){
		if (variableType == "events"){ 
			s.events="";
		}else {
			for (var i=1;i<=50;i++){
				s[variableType+i] = '';
            }
        }
    }
}

function reloadIframe() {
	if(typeof(loadIframe) === "function") {
		loadIframe();
		fbUpdateURL();
	}
}

function IE9FIX(){
	if(navigator.appName == "Microsoft Internet Explorer"){
		loadIframe();
	}
}


function regionChange(to, current) {
	switch(to) {
		case 'US':
			window.location = 'http://www.smithoptics.com?location=button';
		break;
		case 'CA':
			window.location = 'http://www.smithoptics.ca?location=button';
		break;
		case 'EU':
			window.location = 'http://www.smithoptics.eu?location=button';
		break;
		default:
			window.location = 'http://www.smithoptics.com';
		break;
	}
}

var lensPositions = [];
function initLensScrolling() {
	var maxLensCount = 5,
		lensContainer = $("#also ul.active"),
		lensCount = lensContainer.children("li").length || 0,
		groupId = lensContainer.attr("id"),
		scrollDistance = lensContainer.children("li:first").outerHeight(true) || 100;
		// set the top position of the lens scroller to 0 if we don't have a value stored
		if( typeof(lensPositions[groupId]) === "undefined" ) {
			lensPositions[groupId] = 0;
		}

	// remove any other lens scroller arrows
	$("#lens-scroller").remove();

	// too many lenses, allow user to move the list up and down
	if( lensCount > maxLensCount ) {
		// add the scoller arrows and overlay
		var offset = maxLensCount * scrollDistance;
		// add the overlay
		if( $("#lens-scroller-overlay").length < 1 ) {
			$("#also ul").wrapAll('<div id="lens-scroller-overlay" style="height: '+offset+'px;"/>');
		}
		$("#lens-scroller-overlay").after('<div id="lens-scroller" style="top: '+(offset - 40)+'px;"><a id="lens-scroll-up" href="#"></a><br /><a id="lens-scroll-down" href="#"></a></div>');

		// scroll up handler
		$("#lens-scroll-up").click(function(e) {
			e.preventDefault();
			if( lensPositions[groupId] < 0 ) {
				lensContainer.animate({ top: "+="+scrollDistance }, 150);
				lensPositions[groupId] += scrollDistance;
			}
		});

		// scroll down handler
		$("#lens-scroll-down").click(function(e) {
			e.preventDefault();
			if( lensPositions[groupId] >= -(((lensCount-1) - maxLensCount) * scrollDistance) ) {
				lensContainer.animate({ top: "-="+scrollDistance }, 150);
				lensPositions[groupId] -= scrollDistance;
			}
		});
	}
}
//FB SRC VALUE
function fbUpdateURL(url){
	var url = location.pathname + location.hash.replace("#/", "");
	var newURL =  "http:" + "//" + "www.smithoptics.com" + url;
	$( '#fbSkuLike' ).empty().append( $('<iframe />')
			.attr( 'src', 'http://www.facebook.com/plugins/like.php?app_id=169541869777223&href=' + newURL + '&layout=button_count&show_faces=false&width=450&action=like&colorscheme=light&height=21' )
	        .attr( 'scrolling', 'no' )
	        .attr( 'frameborder', 'no' )
	        .attr( 'style', 'border:none; overflow:hidden; width:450px; height:21px;' )
	        .attr( 'allowTransparency', 'true' )        
	 );
}


$(function() {

	// loads iFrames
	reloadIframe();

	// open all external links in a popup window
	$("a[href^=http], a[href^=https], a.external").live("click", function(e) {
		var newDomain = location.protocol+"//"+location.hostname;
		// check just to make sure they aren't linking to this domain
		if( this.href.substr(0, newDomain.length) !== newDomain ) {
			e.preventDefault();
			var widthHeight = $(this).attr("rel").split("|"),
				windowWidth = widthHeight[0] || "800",
				windowHeight = widthHeight[1] || "600",
				popup_window = window.open(this.href, "smith_popup", "width="+windowWidth+", height="+windowHeight+", menubar=yes, scrollbars=yes, status=yes, toolbar=yes, resizable=yes");
		}
	});

	// handle AJAXable clicks (we filter a few types of links)
	$(".mainNav li:not(.lounge) a:not(.no-ajax), .topNav li a:not(.no-ajax), .prodItem a:not(.prodPopup, .read-more, a[href^=http], a[href^=https], a.external)").live("click", function(e) {
		e.preventDefault();
		// IE adds the full path in some versions that we need to strip away
		var href = this.href.replace(location.protocol+"//"+location.hostname, "");
		ajaxUpdateURL(href);
	});

	// this fires when the URL changes, either via ajaxUpdateURL() or a back button click
	$(window).bind("hashchange", function(e) {
		// strip out things we don't want (<protocol>//<hostname></#/>)
		var url = location.pathname + location.hash.replace("#/", "");
		callAjax(url);
		callAjaxBackgroud(url);
	});

	// toggle the feature overlay
	$("#tech-overlay").live("click", function(e) {
		e.preventDefault();
		$(".feature-overlay").toggle();
	});

	// handle frame color/lens combo clicks
	$("#color li a").live("click", function(e) {
		e.preventDefault();

		// clc-<frameColorId>-<defaultLensColorId>
		var IdParts = $(this).parent().attr("id").split("-");

		// clear the active class for the lenses and frame/lens combos
		$("#also ul, #also li a, #color li a").removeClass("active");

		// show the group of available lenses for this frame
		var groupId = "#also ul#lg-"+IdParts[1];
		$(groupId+", "+groupId+" li:first a").addClass("active");
		// show the header if the group is visible
		/*if( $(groupId).hasClass("hide-group") ) {
			$("#also .listHeader").hide();
		} else {
			$("#also .listHeader").show();
		}*/
		
		if (!$(groupId).length)
		{
			$("#also .listHeader").fadeOut(300);
		}else
		{
			$("#also .listHeader").fadeIn(400);
		}

		// highlight what they just clicked
		$(this).addClass("active");

		// add lens scrolling if needed
		initLensScrolling();
	
		// switch out the subtitle text with the new color/lens combo and refresh the cufon
		//$("h2#subtitle").html($(this).children("h3").html().replace("<br>", " ").trim());
		$("h2#subtitle").html($.trim($(this).children("h3").html().replace("<br>", " ")));
		Cufon.replace("h2#subtitle");

		// update the price
		//$("#msrp").text($(this).children(".product-msrp").text());
		$("#msrp").html($(this).children(".product-msrp").html())

		// update the hero image and enlarge image
		var enlargeImgPath = $(this).attr("href"),
			listingImgPath = enlargeImgPath.replace("_enlarge.jpg", "_listing.jpg").replace("D.jpg", "C.jpg"),
			listingAlt = $(this).children("img").attr("alt");
		$("#prodContainer .prodImg").attr({ src: listingImgPath, alt: listingAlt, title: listingAlt });
		$("#enlarge-image").attr({ href: enlargeImgPath }).removeAttr("onclick");
		// add the onclick handler
		var ewh = $(this).attr("rel").split("|") || [500,300];
		//if Available Change Product Description - TM
		if (ewh[2] != undefined)
		{
			$("#prodCopy").html(ewh[2]);
		}
		$("#enlarge-image").click(function(e) {
			e.preventDefault();
			TectureBox.render(enlargeImgPath, ewh[0], ewh[1], '');
		});
	});

	// handle lens color clicks
	$("#also li a").live("click", function(e) {
		e.preventDefault();

		// clear the active class for the lenses and frame/lens combos
		$("#also li a").removeClass("active");

		// highlight what they just clicked
		$(this).addClass("active");

		// switch out the subtitle .sub text with the lens color and refresh the cufon
		// $("h2#subtitle .sub").text($(this).children("h3").text().replace("<br>", " ").trim());
		$("h2#subtitle .sub").html($.trim($(this).children("h3").html().replace("<br>", " ")));
		Cufon.replace("h2#subtitle");

		// update the price
		$("#msrp").text($(this).children(".product-msrp").text());

		// update the hero image and enlarge image
		var enlargeImgPath = $(this).attr("href"),
			listingImgPath = enlargeImgPath.replace("_enlarge.jpg", "_listing.jpg"),
			listingAlt = $(this).children("img").attr("alt");
		$("#prodContainer .prodImg").attr({ src: listingImgPath, alt: listingAlt, title: listingAlt });
		$("#enlarge-image").attr({ href: enlargeImgPath }).removeAttr("onclick");
		// add the onclick handler
		var ewh = $(this).attr("rel").split("|") || [500,300];
		$("#enlarge-image").click(function(e) {
			e.preventDefault();
			TectureBox.render(enlargeImgPath, ewh[0], ewh[1], '');
		});
	});

	// run cufon on page load (we recall this when the text is changed)
	Cufon.replace("h1#title, h2#subtitle, .quick-video span");

	// add tab support on product pages
	$("#product-quick-tabs, #product-detail-tabs").tabs();

	$("#shopSmith a").live("click", function(e) {
		e.preventDefault();
		$("#shopSmith").toggleClass("show-shop");
			if ($("#shopSmith a img").attr("rel") != "exit")
		{
			$("#shopSmith a img").attr("src","images/btns/CloseCartIcon.jpg");			
			$("#shopSmith a img").attr("rel","exit");
		}else
		{
			$("#shopSmith a img").attr("src","images/btns/BuyNowIcon.jpg");
			$("#shopSmith a img").attr("rel","");		
		}
		$("#shop-smith-iframe").toggle();
		IE9FIX();
	});

	// add smooth scrolling for links on an individual technology page
	$("#techLinks a").live("click", function(e) {
		e.preventDefault();
		$.scrollTo(this.hash, 750);
	});
	$("a.techTop").live("click", function(e) {
		e.preventDefault();
		$.scrollTo(0, 750);
	});

	// add the default text to the search input
	$("input[name='search']").toggleVal({
		populateFrom: "custom",
		text: "Product Search"
	});

	// add class to footer for region over state
	$("#region").hover(function() {
		$(this).addClass("region-on");
	}, function() {
		$(this).removeClass("region-on");
	});

	if( $("#contentWrapper").find("#storyboard").length > 0 ) {
		$("#storyboard ul#storyboard_slides").innerfade({
			speed: 1000,
			timeout: 3500,
			type: 'sequence',
			containerheight: 	'370px',
			slide_timer_on: 	'yes',
			slide_ui_parent: 	'storyboard_slides',
			slide_ui_text:      'null',
			pause_button_id: 	'pause_button',
			slide_nav_id:		'storyNav'
		});
		$.setOptionsButtonEvent();
	}

	// search box 
	$(".searchBox").click(function() {
		$(this).val('');
	});

	// quicklook hover
	$(".quickThumbs a").hover(function() {
		$(this).next("p").animate({opacity: "show", bottom: "50"}, "slow");
	}, function() {
		$(this).next("p").animate({opacity: "hide", bottom: "60"}, "fast");
	});

	var timeout = 200,
		closetimer = 0,
		ddmenuitem = 0;

	function mainNav_open() {
		mainNav_canceltimer();
		mainNav_close();
		ddmenuitem = $(this).find("ul").eq(0).css("visibility", "visible");
	}

	function mainNav_close() {
		if( ddmenuitem ) ddmenuitem.css("visibility", "hidden");
	}

	function mainNav_timer() {
		closetimer = window.setTimeout(mainNav_close, timeout);
	}

	function mainNav_canceltimer() {
		if( closetimer ) {
			window.clearTimeout(closetimer);
			closetimer = null;
		}
	}
	$(".mainNav > li").bind("mouseover", mainNav_open);
	$(".mainNav > li").bind("mouseout", mainNav_timer);
	document.onclick = mainNav_close;
});
