//*************************************************************
// GLOBAL.JS
//*************************************************************
//global javascript vars
var processor = "common/get_data.php";
var getId = '';			// Carry selector id/name	
var getUrl = '';		// media/web path string
var getTxt = '';		// Get custom txt attribute for caption 
var getBrand = '';
var lastParentId = 0;	// Set previous carousel item id for goback function
var parentId;			// Set id of selected parent nest item
var parentElem;			// Set name of category/kind for div element to fill
var tmr = 0;			// Global timer object
var isExposeActive;
var pSelectorVal;
var menuIsLoaded = 0;
var content = '';
var contentAlt = '';
var portal_tray_state;  // Stateful Var to track if portal app/login tray is open or closed
var storeBg = '';
var brandMenuWidget = "<div id='brand_list_menu'>" +
								"<img id='brandListToggle' class='bl_title_r0' src='/media/images/blist_arrow_left.gif'/>"+
								"<!-- h2 id='list_title'>&nbsp;</h2 -->" +
								"<div id='qs_wrapper' style='overflow:hidden;'>&nbsp;</div>" +
								"<div id='request_bro_link'>" +
									"<a href='javascript:void(0);' rev='0' title='Brochures' rel='all_pdfs' class='active' onclick='activeItemLink(this,event);'>Request a Brochure</a>" +
								"</div>" +
							"</div>";
//*************************************************************

//* do it this way instead so that all the jQuery plugins work together .. can not use the $ var by itself. *//
jQuery(document).ready(function($){
	
	// Ajax progress loader animation
	$("#footer_wrapper").ajaxStart(function() {
		$(this).prepend("<div id='loader'><div style='float:left;height:32px;'><img src='media/images/loading.gif'></div><span style='float:left;margin-left:8px;'>Loading...Please Wait</span></div>"); }); 
	$("#footer_wrapper").ajaxSuccess(function() { $("#loader").detach(); });

	// this keeps the menu from displaying at all until the page is fully loaded
	$('#Container').html(urldecode(topMenu));
	
	$(".MegaMenuLink").megamenu(".MegaMenuContent");
	$("#carousel_tabs .carousel_menu").corner("keep top 10px");

	// Safely inject CSS3 and give the search results a shadow 
	var turnOnObj = {
		'display' : 'block' 
		}; // 

	var suggestionsCssObj = {
		'display' : 'block', 'box-shadow' : '#333333 5px 10px 10px', // Added when CSS3 is standard 
		'-webkit-box-shadow' : '#333333 5px 10px 10px', // Safari 
		'-moz-box-shadow' : '#333333 5px 10px 10px'}; // Firefox 3.5+ 

	$("#slideshow").css(turnOnObj);
	$("#suggestions").css(suggestionsCssObj);

	// Fade out the suggestions box when not active
	 $("input").blur(function(){

		$('#suggestions').fadeOut();
		$('#gallery').css({'display':'block'}); // Show strip

	 });  

	if(jQuery.browser.msie && jQuery.browser.version.substr(0,1)<"7") {
		jQuery(document).pngFix($);
	}	

	// Add rounded corners to tooltip element and set trigger selector
	$('div#tooltip p').corner('keep 5px');
	
	if(navigator.appName != "Microsoft Internet Explorer") {
		$("#overlay_main").corner("keep");
	}

	// Load and configure sidebar Brand List Menu
	if(!isMobile){
		$("#Container").append(brandMenuWidget);
	} else {
		brandMenuWidget = '<div>test</div>';
		$("#subpg_container").append(brandMenuWidget);
	}

	if(brandListState && !isMobile) {
		$('#brandListToggle').addClass('bl_title_r0').removeClass('bl_title_r90');
		$("#brand_list_menu").css({width:"160px"});
		$('#qs_wrapper,#request_bro_link').css({display:"block"});
		document.getElementById('brandListToggle').src = "/media/images/blist_arrow_left.gif";		
	}else if(!brandListState && !isMobile){
		$('#brandListToggle').addClass('bl_title_r90').removeClass('bl_title_r0');
		$("#brand_list_menu").css({width:"40px"});													   
		$('#qs_wrapper,#request_bro_link').css({display:"none"});
		document.getElementById('brandListToggle').src = "/media/images/blist_arrow_right.gif";
	}

	$.ajax({url: processor,
			cache: true,
			dataType: "json",
			async: true,
			data: {cmd:"quickSearch", sessionid:session_id, cache: ""+new Date().getTime()+"" } ,
			success: function(data,status) {
				$('#qs_wrapper').html(data.contentdata);
				
				$("#brand_quick_list div").hover(							 
					function(){ 
						$(this).css({background:"#"+$(this).attr("rel")});
						if(pagename == 'index') {
							cf._stopSlideshow();
							$("#contentFlow_prodSelect, #class_blurb, #brand_blurb").css({display:"none"});
							var getDisplay = $(this).attr('rev').split("|");
							var setDisplay = "<div id='tempFlow' style='width:100%;height:auto;margin:100px 0 0 30px;'>"+
											 "<img src='/media/products/brands/"+getDisplay[0]+"' style='display:inline;margin-right:10px;'/>"+
											 "<img src='/media/products/logos/"+getDisplay[1]+"' style='display:inline;width:350px;margin-bottom:50px;' /></div>";
							storeBg = $("#pimg_hold").css("backgroundImage");
							$("#pimg_hold").css({display:"block",background: "transparent url(/media/backgrounds/"+getDisplay[2]+") center top no-repeat" ,height:'100%'});
							$("#contentFlow_prodSelect").before(setDisplay);
						}
					}, 
					function(){ 
						$(this).css({background:"#000000 url('/media/images/bar_shade2.png') center center repeat-x"});
						if(pagename == 'index') {
							cf._startSlideshow();
							$("#contentFlow_prodSelect, #class_blurb, #brand_blurb").css({display:"block"});
							$("#tempFlow").detach();
							$("#pimg_hold").css({display:"block",background: "transparent "+storeBg+" center top no-repeat" ,height:'100%'})
						}
					}
				);
			}
	});
	
	
	if(navigator.appName != "Microsoft Internet Explorer") {
		$("#brand_list_menu").corner("right 10px");
		$("#dealer_loc_link").corner("bottom 10px");
	}
		
	/************************** Footer Widget Functions & Controls **********************/	
	
	// Setup initial count/variables on document ready
	$("#recent_view").html(recent_view);
	$("#saved_view").html(saved_view);
	$("#compare_product").html(compare_product);
	//$("#show_featured").html(show_featured).css({color:"#ee8a28"});
	$("#show_featured").html("");

	// Carousel Show/Hide function - Revised 05/31/2011 (Carousel moved to mega menu and always on. Made visible by megamenu)
	//document.getElementById("carousel_section").style.display = "block";
	var getDisplay = "block";

	// Show/Hide Recently Viewed, Wish List, and Compare Products Slide
	$("#footer_widget_links li a").click(function() {
		$("#footer_widget_links li a").css({color:"#ffffff"});
		var selected_link = $(this).attr("class");

		if(selected_link != 'show_featured') {
			$(this).css({color:"#ee8a28"});

			if( $("#footer_widget_display").css("display") == "none" ) {
				$("#footer_widget_display").animate({bottom:'28px'}, 500, function(){
					$(this).css({display: "block"});
				});
			}

			$(".displayitems").each(function(i) {
				if( $(this).attr('id') != "display_"+selected_link ) {
					$(this).css("display","none");
				} else {
					$(this).css("display","block");
				}
			});		
		}
	});
	
	$("#footer_widget_display .close").click(function() {
		$("#footer_widget #footer_widget_display").animate({bottom:'-300px'}, 500, function(){
			$("#footer_widget_display .displayitems").css("display","none");
			$("#footer_widget_display").css("display","none");
			$("#footer_widget_links li a").css({color:"#ffffff"});
		});
	});

	$("#comparenow_btn").click(function() {
		var btnState = $(this).attr('rel');
		if(btnState == 'true') {
			$("#footer_panel").animate({bottom: '28px'}, 500, function(){
				$(this).css({display:"block"});
				$("#footer_wrapper").prepend("<div id='expose_overlay'></div>");			
			});

			$.getJSON(processor, {cmd:"displayCompare", sessionid:session_id} , function(data) {			
				$("#footer_panel").html(data.contentdata);
			});	
		}
	});

	$("span#portal_btn, #portal_btn_topbar").click(function() {
		var btnState = $(this).attr('rel');
		if(btnState != 'true') {
			$("#portal_login").animate({top: '-235px'}, 500, function(){
				$("span#portal_btn, #portal_btn_topbar").attr('rel','true');
			});		
		} else {
			$("#portal_login").animate({top: '2px'}, 500, function(){
				$("span#portal_btn, #portal_btn_topbar").attr('rel','false');
			});	
		}		
	});
	
	$("#portal_logout").click(function() {
		document.logmeout.submit();	
	});

	$("#dashboard_logout").click(function() {
		document.dashlogmeout.submit();	
	});
		
	$("#user_reset").click(function() {
		document.userreset.submit();	
	});	
	
	$("#user_reset_dash").click(function() {
		document.userresetdash.submit();	
	});			
	/***************************** Print/Share Action Script **************************/
	$("#pgActions div.printme").live("click", function() {
		// Get page vars from button for processing logic
		var pageTitle = $(this).attr('title');
		var pageClass = $(this).attr('rel');
		var pageBrand = $(this).attr('rev');
		var pageLogo = $("#logo_holder_brands").attr('src');
		
		$("#pgActions").prepend('<img id="preparePrint" src="media/images/proc.gif" alt="processing" style="position:absolute;left:-15px;"/>');
		
		//Strip and clean up unecessary DOM elements and styles
		$("#subpg_container").css({top:"-10px"});
		$("#subpg_header, #subpg_header_med, #subpg_header_sm").css("display","none");		
		$("#page_wedge,#footer_wrapper").detach();
	
		//Replace current page header with printer friendly one depending on if product or general page
		if(pageTitle == "prodselect" || pageBrand.length == 0) {
			$("#header_wrapper").html("<div style='width:950px;height:130px;text-align:center;background:url(media/images/main_bg.png) center center repeat-y;'><img src='media/images/heartland_logo.png'/></div>").css({height:"auto"});
		} else {
			var setHeader = "<div style='width:950px;height:220px;background:url(media/images/main_bg.png) center center repeat-y;position:relative;margin-bottom:10px;top:0;left:0;'>"+	 
						  "<img src='media/images/heartland_logo.png' style='float:left;margin:10px 0 0 100px;'/>" + 
						  "<img src='"+ pageLogo +"' style='float:left;margin-left:100px;width:330px;'/>" +
						  "<h1 style='width:300px;text-align:center;clear:both;font-size:2.6em;color:#ccc;position:absolute;top:130px;left:110px;'>" + pane_title + "</h1>" +
						  "</div>";
			$("#header_wrapper").html(setHeader).css({height:"auto"});			
		}
		
		//Check to see if page is a product page then set appropriate page/pane name. Otherwise leave it alone.
		setpagename = (pageBrand.length == 0) ? pageTitle : pagename;
		if(pageTitle == "prodselect") { setpagename = "prodselect"; }
		
		//Configure layout based on what page it is
		switch(setpagename) {
			case "privacy" :
				$("#accordion .pane").css({display:"block"});	
			break;
			//*************************************************************************
			case "green" :
				var scanTxt1 = $("div#scan1").text();
				scrollStop = true;				
				$("#green-wrapper").html("<p style='margin:10px 30px;'><img src='media/images/icons/green.png' style='float:right;' />"+scanTxt1+"</p>").css({fontSize:"2.0em",color:"#333333"}).css({background:"none",height:"auto"});
			break;
			//*************************************************************************
			case "links" :
				$("#accordion .pane").css({display:"block"});			
			break;
			//*************************************************************************
			case "overview" :
				
				$("#contentFlow_displayVert,#brand_slidecaption,#brand_control_bar,#brand_mediaview label").css({display:"none"});
				$(".breadcrumb_top, .breadcrumb_bottom").css({display:"none",top:"0px"});
				$("#subpg_main, #brand_overview").css({float:"none",position:"relative",top:"0px",left:"0px"});
				
				$("#view_slideshow").cycle('destroy');	
				
				var chkOpenView = $("#view_slideshow").width();
				
				if(chkOpenView == 0) { 
					$("#view_slideshow").css({display:"none"}); 
				} else { 
					$("#view_view360").css({display:"none"});
					$("#view_slideshow").css({width:"885px",height:"auto",border:"0"}); 
				}
				
				$("#view_slideshow img").css({display:"block",width:'280px',height:'auto',float:'left',position:'relative',margin:'7px',zIndex:5,opacity:1});
				
				$("#nsTitle").click();
				
				var fplanImg = "";
				var overlayInfo = "";
				
				$(".prodselect .floorplanInfo").each(function(i) {
					$(this).css({fontSize:"1.0em"});										  
					$(this).find("b:first").css({display:"none"});
					$(this).find("br").css({display:"none"});
					$(this).find(".floorplanImg").css({margin:"5px",width:"250px"});
					$(this).find(".model_info");
					$(this).find(".detail_txt").css({display:"none"});
					
					fplanImg = $(this).find("a:first").html();
					overlayInfo = $(this).find(".overviewLayer").html();
					
					$(this).html(fplanImg+"<br/>"+overlayInfo);	
				});
				
			break;
			//*************************************************************************
			case "prodselect" :	
				if(pageClass.length != 0) {				
					$("#contentFlow_displayVert").detach();
					$("#view_slideshow").cycle('destroy');
					$("#brand_control_bar").css({display:"none"});
					$("#brand_slideimg").css({display:"none"});
					$("#nsTitle").click();
				} else {
					$("#contentFlow_prodSelect").css({display:"none"});
				}
				
				var fplanImg = "";
				var overlayInfo = "";
				
				$(".prodselect .floorplanInfo").each(function(i) {
					$(this).css({fontSize:"1.0em"});										  
					$(this).find("b:first").css({display:"none"});
					$(this).find("br").css({display:"none"});
					$(this).find(".floorplanImg").css({margin:"5px",width:"250px"});
					$(this).find(".model_info");
					$(this).find(".detail_txt").detach();
					
					fplanImg = $(this).find("a:first").html();
					overlayInfo = $(this).find(".overviewLayer").html();
					
					$(this).html(fplanImg+"<br/>"+overlayInfo);	
				});				
				
			break;
		}
		
		document.getElementById("content_wrapper").focus();		
		/*$.getJSON(processor, {cmd:"printFriendly", sessionid:session_id} , function(data) {			
			if(data.response == 'done') { window.print(); self.location.reload(true); }
		});*/		
		//window.print();
		setTimeout("$('#preparePrint').detach();window.print();self.location.reload(true)",5000);
			
	});

	$("#pgActions div.shareme").live('click', function() {
		// This button triggers AddtoAny Widget function where applicable
	});

	/****************************** Accordion Control Script **************************/
	$("#accordion").tabs("#accordion div.pane", {
		tabs: 'h3', 
		effect: 'slide', 
		initialIndex: 0
	});

	/*$("#guideWrapper").tabs("#guideWrapper div.pane", {
		tabs: 'h3', 
		effect: 'slide', 
		initialIndex: null
	});*/


	if (language != 'en') setTimeout("nativeTreeWalker(document.body);",1000);
}); // End of document ready function

var flagBlist = false;
$("#brandListToggle").live('click', function() { 
	if(!flagBlist) { flagBlist = true; $(this).click(); $('#qs_wrapper,#request_bro_link').css('display','none');} else
	toggleBrandList(); 
});

/*************************************************************************************/
/*                                                                                   */
/*                           Javascript Functions Library                            */
/*                                                                                   */
/*************************************************************************************/

// Internet Explorer ver 6/7/8 Black Halo Fix
$.fn.pngFix = function() {
  if (!$.browser.msie || $.browser.version >= 9) { return $(this); }

  return $(this).each(function() {
	var img = $(this),
		src = img.attr('src');

	//img.attr('src', '/media/images/blank.gif')
		//.css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='" + src + "')");
		img.css('filter', "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)");
  });
};

function chkVar(a) {
	if(typeof(a) != "undefined" && typeof(a) != "unknown" && a) {
		return true;
	} else { 
		return false; 
	}
} // exist 

function toggleBrandList() {	
	if(brandListState) {
		brandListState = false;
		document.getElementById('brandListToggle').src = "/media/images/blist_arrow_right.gif";
		$('#brandListToggle').addClass('bl_title_r90').removeClass('bl_title_r0');
		$('#qs_wrapper,#request_bro_link').fadeOut('fast');		
		$("#brand_list_menu").animate({width:"40px"},1400, function(){			
			$.getJSON(processor, {cmd:"saveBrandListState", sessionid:session_id, fn:brandListState } , function(data) { thisBtn = data.response; });
		});
		
	} else if(!brandListState) {
		brandListState = true;
		document.getElementById('brandListToggle').src = "/media/images/blist_arrow_left.gif";
		$('#brandListToggle').addClass('bl_title_r0').removeClass('bl_title_r90');
		$("#brand_list_menu").animate({width:"160px"},600, function(){
			$('#qs_wrapper,#request_bro_link').fadeIn('slow');							
			$.getJSON(processor, {cmd:"saveBrandListState", sessionid:session_id, fn:brandListState } , function(data) { thisBtn = data.response; });
		});	
		
	}
}

// ************************** Language Translation Functions **********************************
function storeTranslations() {
	if (d != 0) setTimeout(storeTranslations, 500);
	else {
		var params = "";
		for (var i in newTranslations) {
		  //console.log(newTranslations[i]);
		  	if(newTranslations.length > 0){
			  params += i+"="+newTranslations[i].replace(/'/g,"(apostrophe)").replace(/"/g,"(quote)").replace(/&/g,"(ampersan)")+"&";
			}
		}
		var xhreq;
		if (typeof XMLHttpRequest == 'undefined') xhreq = new ActiveXObject("Microsoft.XMLHTTP");
		else xhreq = new XMLHttpRequest();
		xhreq.open("POST", "js/translations.php?action=store&lang="+language, true);
		xhreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xhreq.setRequestHeader("Content-length", params.length);
/*		xhreq.onreadystatechange = function() {
			if (xhreq.readyState == 4 && xhreq.status == 200) {
			}
		}
*/		xhreq.send(params.substr(0, params.length-1));
		for (var i in newTranslations) {
			  translations[i] = newTranslations[i];
		}
		newTranslations = Array();
	}
}

//****************************************************************
var c = 0; var d = 0; var newTranslations = Array();
function translate(node) {
	this.node = node;
	this.translate = function(node) {
		var tt = "t"+node.nodeValue.replace(/[^a-zA-z0-9]|(\_)|(\[)|(\])/g,"");
		//var tt = "t"+node.nodeValue.replace(/[^a-zA-z0-9]/g,"");
		if (typeof(translations[tt]) != 'undefined') {
			var temp = document.createElement("pre"); temp.innerHTML = translations[tt];
			node.nodeValue = temp.innerHTML;
		} else {
			c++; d++;
			google.language.translate(node.nodeValue, "en", language, function(result) {
				d--;
				if (result.translation.length > 0) {
					var tt = "t"+node.nodeValue.replace(/[^a-zA-z0-9]|(\_)|(\[)|(\])/g,"");
					//var tt = "t"+node.nodeValue.replace(/[^a-zA-z0-9]/g,"");
					newTranslations[tt] = result.translation;
					var temp = document.createElement("pre"); temp.innerHTML = result.translation;
					node.nodeValue = temp.innerHTML;
				}
			});
		}
	}
	this.translate(node);
}
//****************************************************************
function anativeTreeWalker(parent) {
  //console.log(NodeFilter.SHOW_TEXT);
    var walker = document.createTreeWalker(
	parent, 
	NodeFilter.SHOW_TEXT,
	null, 
	false
    );
    var node;
    while(node = walker.nextNode()) {
	if (/(SCRIPT)|(STYLE)|(TBODY)|(TR)|(UL)/.test(node.parentNode.tagName)) continue;
	var temp = "t"+node.nodeValue.replace(/[^a-zA-z0-9]|(\_)|(\[)|(\])/g,"");
	//var temp = "t"+node.nodeValue.replace(/[^a-zA-z0-9]/g,"");
	if (temp.length > 3) {
	    var t = new translate(node);
	}
    }
    setTimeout(storeTranslations, 500);
}
//****************************************************************
//function customRecursiveTreeWalker() {
function nativeTreeWalker(parent) { // not native
    var result = [];

    (function findTextNodes(current) {
        for(var i = 0; i < current.childNodes.length; i++) {
            var child = current.childNodes[i];
            if(child.nodeType == 3) {
		if (/(SCRIPT)|(STYLE)|(TBODY)|(TR)|(UL)/.test(child.parentNode.tagName)) continue;
		var temp = "t"+child.nodeValue.replace(/[^a-zA-z0-9]|(\_)|(\[)|(\])/g,"");
		//var temp = "t"+child.nodeValue.replace(/[^a-zA-z0-9]/g,"");
		if (temp.length > 3) {
		    var t = new translate(child);
		}
                //result.push(child.nodeValue);
            }
            else {
                findTextNodes(child);
            }
        }
    })(parent);
    setTimeout(storeTranslations, 500);
}
//****************************************************************
function chgSiteLang(langvar) {
	var currentUrl = window.location.href;
	var mPos = currentUrl.split("#");
	var sPos = currentUrl.indexOf('&lang=');
	var cleanUrl = "";
	
	if(mPos.length > 1) { currentUrl = mPos[0]; }
	
	if(currentUrl.indexOf('&lang=') != -1) {
		cleanUrl = currentUrl.replace(currentUrl.substr(sPos,8),"");
	} else {
		cleanUrl = currentUrl;
	}
	
	self.location.href = cleanUrl+"&lang="+langvar;	
}

/******************************** Flash/Actionscript call Functions *****************************/
function sendFlashVar(setvar){
	if(pagename == 'index' && swfobject.hasFlashPlayerVersion("9")) {
		//document.getElementById("flash_hold").clipControl(setvar);
	}
}

//*************************************************************
function sendImgVar(url){
     if(pagename == 'index' && swfobject.hasFlashPlayerVersion("9")) {
		document.getElementById("flash_hold").setImg(url);
	 }
}

//*************************************************************
function setUrlFromFlash(url, txtcolor) {
     if(pagename == 'index' && swfobject.hasFlashPlayerVersion("9")) {
		if(url.length != 0) {
			//alert( url + " " + txtcolor );
			$("#homepg_container a.bglink").css("display","block");
			$("#homepg_container a.bglink").attr("href",url);
		} else { 
			$("#homepg_container a.bglink").css("display","none"); 
			$("#homepg_container a.bglink").attr("href","javascript:;");
		}

		$("#top_links li a").css("color",txtcolor);
		$("#default_lower_display li a").css("color",txtcolor);
	 }
}

/******************************** Footer Widget Functions *****************************/

function setCarousel() {
var getSize = '';		// Overlay size string 
var getWrapper = '';
var w = '';				// Overlay width var 
var h = '';				// Overlay height var

	// Setup dynamic tabs and panes for carousel
	$("#carousel_tabs ul.tabs").tabs("#carousel_section .pane", {
		tabs: 'li',
		current: 'current',
		effect: 'default',
		initialIndex: 0,
		event: 'click'
	});

	// Carousel Scroller Object
	$("#menu_1 .scrollable").scrollable({ 
		items: '.item',
		circular: false,
		keyboard: true
	});

	// Video Overlay w/Flowplayer from Carousel Object
	$(".lbox").overlay({
		target: '#overlay_main',
		effect: 'apple',
		mask: {
			color: '#000',
			loadSpeed: 200,
			opacity: 0.6
		},
		closeOnClick: false,
		onBeforeLoad: function() {
						getId = this.getTrigger().attr("id");
						getSize = this.getTrigger().attr("rev");
						getTxt = this.getTrigger().children(".captiontxt:hidden").text();
						
						// Check if overlay dimensions where set and if not use default
						if(getSize.length == 0) {
							if(getId == 'vid_btn') { w = '596'; h = '465'; } else { w = '800'; h = '600'; }
						} else {
							var setSize = getSize.split('x');
							w = trim(setSize[0]);
							h = trim(setSize[1]);
						}
						
						var overlay_w = (parseFloat(w))+"px";
						var overlay_h = (parseFloat(h))+"px";
						
						$("#overlay_main").css({width: overlay_w, height: overlay_h });
						
						// Set our content path in the anchor (player) element
						getWrapper = this.getOverlay().find("#player");
						getWrapper.attr("href",this.getTrigger().attr("rel"));
						getUrl = document.getElementById("player").getAttribute("href");
					},
		onLoad: function() {
						if(getId == 'vid_btn') {
							//if trigger is media(i.e. video) use flowplayer in overlay
							var player = $f("player", "js/flowplayer-3.2.2.swf",{clip: getUrl,autoPlay: false}).load();
							
							if(getTxt.length != 0) {
								$("#overlay_main").append("<div class='lbcaption'>"+getTxt+"</div>").slideDown(10000);
							}

						} else if(getId == 'lbox_btn') {
							//if trigger is link, load content into iframe wrapper in overlay;
							$("#overlay_main a#player").css({backgroundColor:'#ebebeb'});

							var chkUrlPath = getUrl.search("/http:///");
							if(chkUrlPath != -1) {
								getUrl += "&amp;sessionid="+session_id;
							}

							getWrapper.html("<iframe src='"+getUrl+"' id='lightbox' allowTransparency='true'></iframe>");
							
							if(getUrl.indexOf("youtube.com/v/") != -1) {
								if(getTxt.length != 0) {
									$("#overlay_main").append("<div class='lbcaption'>"+getTxt+"</div>").slideDown(10000);
								}
							} 
						}

					},
		onBeforeClose: function() {
						if(getId == 'vid_btn') {
							if(getTxt.length != 0) { $("div.lbcaption").detach(); }
							$f("player").close();
						} else if(getId == 'lbox_btn' && getUrl.indexOf("youtube.com/v/") != -1) {
							if(getTxt.length != 0) { $("div.lbcaption").detach(); }							
						}
						
						getWrapper.html(""); // empty contents of overlay on close.
					},
		api: true
	});

	$(".lbox_trim").overlay({
		target: '#overlay_main',
		effect: 'apple',
		mask: {
			color: '#000',
			loadSpeed: 200,
			opacity: 0.6
		},
		closeOnClick: false,
		onBeforeLoad: function() {
						getSize = this.getTrigger().attr("rev"); 
						if(getSize.length == 0) {
							if(getId == 'vid_btn') { w = '596'; h = '465'; } else { w = '800'; h = '600'; }
						} else {
							var setSize = getSize.split('x');
							w = trim(setSize[0]);
							h = trim(setSize[1]);
						}
						var overlay_w = (parseFloat(w))+"px";
						var overlay_h = (parseFloat(h))+"px";

						$("#overlay_main").css({width: overlay_w, height: overlay_h });

						getWrapper = this.getOverlay().find("#player");
						getUrl = this.getTrigger().attr("href");
					},
		onLoad: function() {					
						getWrapper.html("<iframe src='"+getUrl+"' id='lightbox' allowTransparency='true' style='background-color:#fff;'></iframe>");

					},
		onBeforeClose: function() {
						getWrapper.html(""); // empty contents of overlay on close.
					},
		api: true
	});

}

//*************************************************************
function hoverItem() {
	// This funtion controls the links to the brand pages from the product tabs on the carousel.
	$("a.item").mouseover(function() {
		getUrl = $(this).attr("rel");
		getBrand = $(this).attr("rev");
		getId = $(this).attr("id");

		if(!isNaN(getUrl) || getUrl.indexOf("media/") || getId == 'vid_btn') getUrl = "media/backgrounds/2011_welcome_slide_1920x500.jpg";
		/*if(getUrl.length != 0 && pagename == 'index') {			
			sendFlashVar(0);
			$("#pimg_hold").css("display","block");
			$("#pimg_hold img").attr({src: getUrl});

			$(this).mouseout(function() {
				//sendImgVar(getUrl);
				sendFlashVar(1);
				$("#pimg_hold img").attr({src: "media/backgrounds/2011_welcome_slide_1920x500.jpg"});
				$("#pimg_hold").css("display","none");
				
			});
		}*/
	});

}

//*************************************************************
function nestedItem() {
	// Uses ajax function to bring back nest items into feature panel for carousel
	$("a.nest_item").click(function() {
		parentId = $(this).attr("rel");
		parentElem = $(this).parents(".pane").attr("id");

		$.getJSON(processor, {cmd:"nestItems", sessionid:session_id, parentid: parentId, kind: parentElem} , function(data) {
			$("div#"+parentElem).html(data.contentdata);

			setCarousel();
			hoverItem();
			nestedItem();			
			
			lastParentId = (data.level == 0 || data.level == 1) ? 0 : data.response;
	
			goBackLevel(lastParentId, parentElem);

			if(data.level == 0) { $('.goback').css("display","none"); }

			if (language != 'en') nativeTreeWalker(document.getElementById(parentElem));
		});		
	});

	//updateSessionData();
}

//*************************************************************
function goBackLevel(levelId, category) {
	//If goback button is clicked , bring back last pane of items
	$(".goback").click(function() {
		$.getJSON(processor, {cmd:"nestItems", sessionid:session_id, parentid: levelId, kind: category, fn: 'goback'} , function(data) {
			$("div#"+category).html(data.contentdata);
			
			setCarousel();
			hoverItem();
			nestedItem();

			lastParentId = (data.level == 0 || data.level == 1) ? 0 : data.response;
			
			goBackLevel(lastParentId, category);

			if(data.level == 0) { $('.goback').css("display","none"); }

			if (language != 'en') nativeTreeWalker(document.getElementById(category));
		});
	});
}

//*************************************************************
function loadCarousel() {
	// Load carousel with content from ajax when page first loads
	$.getJSON(processor, {cmd:"loadCarousel", sessionid:session_id} , function(data) {
		$("#carousel_section div.panes").html(data.contentdata);

		setCarousel();
		hoverItem();
		nestedItem();

		if (language != 'en') nativeTreeWalker(document.getElementById("carousel_section"));
	});
}

//*************************************************************
function loadWidgetDisplay() {		
	$.getJSON(processor, {cmd:"recent_view", sessionid:session_id} , function(data) {			
		$("#display_recent_view .footer_widget_display_wrapper").html(data["recent_view"]);
	});

	$.getJSON(processor, {cmd:"saved_view", sessionid:session_id} , function(data) {			
		$("#display_saved_view .footer_widget_display_wrapper").html(data["saved_view"]);
		setWidgetCarousel();
	});

	$.getJSON(processor, {cmd:"compare_product", sessionid:session_id} , function(data) {			
		$("#display_compare_product .footer_widget_display_wrapper").html(data["compare_product"]);
		$("#display_compare_product span.widget_title").html(data.contentdata);
		setCompareBtn( data.widgetdata );
	});
}

//*************************************************************
function wishCompare(this_elem,fn,event) {
	var thisBtn = $(this_elem);
	var itemid = $(this_elem).attr('rel');
	var selected_link = fn;
	var linkColor = $("#footer_widget #footer_widget_links li a");
	var fnView,widgetDisplay,widgetState,selector;

	if(fn == 'saved_view') { fnView = '0 -50px no-repeat'; } else if(fn == 'compare_product') { fnView = '0 -25px no-repeat'; }
	
	thisBtn.parent(".wishcompare").css({background:'url("media/images/addWishCompare.png") '+fnView });
	thisBtn.mouseout(function() {
		thisBtn.parent(".wishcompare").css({background:'url("media/images/addWishCompare.png") 0 0 no-repeat'});
	});	

	// Show/Hide Recently Viewed, Wish List, and Compare Products Slide
	thisBtn.click(function() {

		selector = $("."+fn);			
		widgetDisplay = $("#footer_widget #footer_widget_display");
		linkColor.css({color:"#ffffff"});

		widgetState = widgetDisplay.css("display");
		
		$(".displayitems").each(function(i) {
			if( $(this).attr('id') != "display_"+selected_link ) {
				$(this).css("display","none");
			} else {
				$(this).css("display","block");
			}
		});	
		
		$("#display_"+selected_link+" .waitstate").css({display:"block"});
		
		if(event == 'add') {		

			if( widgetState == "none" ) {
				widgetDisplay.css("display","block");
				widgetDisplay.animate({bottom: '28px'}, 500, function(){
					selector.css({color:"#ee8a28"});
				});			
			} else {
				selector.css({color:"#ee8a28"});
			}
			
			// Fills widget with content from get_data ajax processor 
			$.getJSON(processor, {cmd:selected_link, sessionid:session_id, fn: event, itemid: itemid} , function(data) {
				$("#display_"+selected_link+" .footer_widget_display_wrapper").html(data[selected_link]);
				$("#display_"+selected_link+" span.widget_title").html(data.contentdata);
				$("#"+selected_link+"").html(data.widgetdata);
				setCompareBtn(data.widgetdata);
				setWidgetCarousel();
				hideDetailPanel(this);

				//tmr = setTimeout("hideWidgetDisplay('"+fn+"')", 8000);
			});
		} else if(event == 'delete') {
			$.getJSON(processor, {cmd:selected_link, sessionid:session_id, fn: event, itemid: itemid} , function(data) {
				$("#display_"+selected_link+" .footer_widget_display_wrapper").html(data[selected_link]);
				$("#display_"+selected_link+" span.widget_title").html(data.contentdata);
				$("#"+selected_link+"").html(data.widgetdata);
				setCompareBtn(data.widgetdata);
				setWidgetCarousel();
			});
		}
	});
}

//*************************************************************
function deletCompareItem(this_elem,fn,event) {
	var thisBtn = $(this_elem);
	var itemid = $(this_elem).attr('rel');
	var selected_link = fn;
	var linkColor = $("#footer_widget #footer_widget_links li a");
	var fnView,widgetDisplay,widgetState,selector;

	// Show/Hide Recently Viewed, Wish List, and Compare Products Slide
	thisBtn.click(function() {

		selector = $("."+fn);			
		widgetDisplay = $("#footer_widget #footer_widget_display");
		linkColor.css({color:"#ffffff"});

		widgetState = widgetDisplay.css("display");
		
		$(".displayitems").each(function(i) {
			if( $(this).attr('id') != "display_"+selected_link ) {
				$(this).css("display","none");
			} else {
				$(this).css("display","block");
			}
		});	
		
		$("#display_"+selected_link+" .waitstate").css({display:"block"});
		
		if(event == 'delete') {
			$.getJSON(processor, {cmd:selected_link, sessionid:session_id, fn: event, itemid: itemid} , function(data) {
				$("#display_"+selected_link+" .footer_widget_display_wrapper").html(data[selected_link]);
				$("#display_"+selected_link+" span.widget_title").html(data.contentdata);
				$("#"+selected_link+"").html(data.widgetdata);
				setCompareBtn(data.widgetdata);
				setWidgetCarousel();
			});

			$.getJSON(processor, {cmd:"displayCompare", sessionid:session_id} , function(data) {			
				$("#footer_panel").html(data.contentdata);
			});
		}
	});
}

//*************************************************************
function hideWidgetDisplay(fn) {
	$("."+fn).css({color:"#ffffff"});
	$("#footer_widget .footer_widget_display").animate({height: 'toggle', display: 'none'}, 500, function(){});			
}

//*************************************************************
function hideWidgetPanel(this_elem) {
	var thisObj = $(this_elem);
	thisObj.parent().animate({bottom:"-660px"}, 500, function(){
		thisObj.parent().css({display:"none"});
		$("#expose_overlay").detach();
	});			
}

//*************************************************************
function setWidgetCarousel() {
	// Footer Widget Display Scroller Object
	$("#footer_widget_display .fwidget_scroll").scrollable({ 
		items: '.item_slot',
		circular: false,
		keyboard: true
	});
}

//*************************************************************
function setCompareBtn(cntr) {
	var compareBtn = $("#comparenow_btn");

	if(cntr >= 2) {
		compareBtn.addClass("activeCompare");
		compareBtn.attr({rel:'true'});
	} else {
		compareBtn.removeClass("activeCompare");
		compareBtn.attr({rel:'false'});		
	} 
}

//*************************************************************
function hideDetailPanel(this_elem) {
	$("#floorplan_detail_panel").css('display', 'none');
	$("#detail_modelname").html("");
	$("#floorplan_detail_wrapper").html("");
	$("#expose_overlay").detach();		
}

//*************************************************************
function getFloorplanDetail(brandcode,modelname) {
	var modelid = '';
	$("#floorplan_detail_panel").css({display:'block'});
	
	$.getJSON(processor, {cmd:"showFloorplanDetail", sessionid:session_id, bcode: brandcode, itemid: modelname} , function(data) {	
		$("#detail_modelname").html(data.userdata);
		$("#floorplan_detail_control").html(data.response);
		$("#floorplan_detail_wrapper").html(data.contentdata);
		$("#footer_wrapper").prepend("<div id='expose_overlay'></div>");
		modelid = data.widgetdata;
	
		$.getJSON(processor, {cmd:"recent_view", sessionid:session_id, fn: "add", itemid: modelid} , function(data) {
			$("#display_recent_view .footer_widget_display_wrapper").html(data.recent_view);
			$("#display_recent_view span.widget_title").html(data.contentdata);
			$("#recent_view").html(data.widgetdata);
			setCompareBtn(data.widgetdata);
			setWidgetCarousel();
			centerVert($('.bLogo'), '.logo_hold');
		});	
	});
	
}

/**************************** Search Field/Box Functions & Controls ************************/
function lookup(inputString) {
	if(inputString.length == 0) {
		jQuery('#suggestions').fadeOut(); // Hide the suggestions box
		jQuery('#gallery').css({'display':'block'}); // Show strip
	} else {
		jQuery.post("common/getsearch.php", {searchstring: ""+inputString+"", site_base: sitebase, search_id: searchid, session_id: session_id}, function(data) { // Do an AJAX call
			jQuery('#gallery').css({'display':'none'}); // Hide strip
			jQuery('#suggestions').fadeIn(); // Show the suggestions box
			jQuery('#suggestions').html(data); // Fill the suggestions box

		});
	}
}

function sendToLocator() {
	var postalcode = $("#dzipcode").val();	
	window.location.href = "index.php?p=63&next=1&brand=MISC&zipcode="+postalcode;
}

//*************************************************************
function geoLocateIP(ipaddr) {
	//Using hostip.info site database for geolocation lookup. Returns City, State, Lat, Long, and IP
	$.getJSON(processor, {cmd: "geoIPData", sessionid: session_id, clientip: ipaddr} , function(data) {
		$("#closest_dealer").html(data.contentdata);
	});
}

/****************************** Display Modal Confirm Box *********************************/
function cconfirm(title,message, doc, web, msg, addlogic) {
	var rtnLogic = '';
	jQuery('#confirm').modal({
		closeHTML:"<a href='#' title='Close' class='modal-close' style='font-size:3em;left:390px;top:1px;'>&#215;</a>",
		position: ["20%","30%"],
		overlayId:'confirm-overlay',
		containerId:'confirm-container',
		autoPosition:true,
		modal: true,
		onShow: function (dialog) {
			$('.buttons').css({width:'325px'});
			$('.header > span').html(title);
			$('.message').append(message);
			if(!msg) {
				$('.no').css({width:'160px'}).html("Download").click(function () { window.location.href='media/documents/optdownload.php?file='+doc; $.modal.close(); });
				if(web) {
					$('.yes').css({width:'150px'}).html("View").click(function () { windowPop(web,900,640); $.modal.close(); });
				} else {
					$('.yes').css({width:'150px'}).html("View").click(function () { openLbox('media/documents/'+doc,'900','600'); $.modal.close(); });
				}
			} else if(msg && !addlogic) {
				$('.no').css({width:'120px',position:'absolute',top:'95px',right:'20px'}).html("Cancel").click(function () { return false; });
				$('.yes').css({display:"none"});
			} else if(msg && addlogic) {
				$('.no').css({position:'absolute',top:'95px',right:'20px'}).html("NO").click(function () { return false; });
				$('.yes').css({position:'absolute',top:'95px',right:'100px'}).html("YES").click(function () { return true; });				
			}
		}
	});
	
	if(rtnLogic === true) {return true; $.modal.close();}
}

//*************************************************************
function openLbox(locationName,width,height){
	var w,h;
	if(width == '' || height == '') { w = '900'; h = '600'; } else { w = width; h = height; }

    Shadowbox.open({
        player:     'html',
        content:    '<div class="shadowbox_message" style="overflow:hidden;height:'+h+'px;width:'+w+'px;"><iframe src="' + locationName + '" style="width:'+w+'px;height:'+h+'px;"></iframe></div>',
	handleOversize: 'none',
        width: w,
	height: h
    });
}

//*************************************************************
function ask(title,doc,url) {
	cconfirm(title,"Do you want to download or view this owner's manual?",doc, url);
}

//*************************************************************
function loadOverlay(this_elem,getSize,getUrl) {
	var setSize = '';
	$(this_elem).overlay({
		target: '#overlay_main',
		effect: 'apple',
		mask: {
			color: '#000',
			loadSpeed: 200,
			opacity: 0.6
		},
		closeOnClick: true,
		onBeforeLoad: function() {

						getSize = (getSize) ? getSize : this.getTrigger().attr("rev"); 
						if(getSize.length == 0) {
							if(getId == 'vid_btn') { w = '596'; h = '465'; } else { w = '800'; h = '600'; }
						} else {
							setSize = getSize.split('x');
							w = trim(setSize[0]);
							h = trim(setSize[1]);
						}
						var overlay_w = (parseFloat(w))+"px";
						var overlay_h = (parseFloat(h))+"px";

						$("#overlay_main").css({width: overlay_w, height: overlay_h });
								
						getWrapper = this.getOverlay().find("#player");
	
					},
		onLoad: function() {
						getWrapper.html("<iframe src='"+getUrl+"' id='lightbox' allowTransparency='false' style='background-color:#000;width:100%;height:100%;' scrolling='auto'></iframe>");
					},
		onBeforeClose: function() {
						getWrapper.html(""); // empty contents of overlay on close.
					},
		api: true
	});
	$(this_elem).click();
}

/**************** Buyers Guide & Product Page Javascript Functions **********************/
function toggleToolTip(this_elem) {
	if(document.getElementById("dtip").checked) { setToolTips = "CHECKED" } else { setToolTips = '' }
}

//*************************************************************
function toggleNarrowSearchView(this_elem) {
	var getState = $("#narrowSearch td.resultDisplay").css("display");
	var setState = '';
	if(getState == 'none') { 
		setState = "bottom";		
		$("#narrowSearch td.resultDisplay").animate({height:"toggle",opacity:"toggle"}, 500, function() {
			$("#narrowSearch td.selectorDisplay").css("display","block");																						  
			$("#guideControls").fadeIn('fast');
			$(this).css({display:"table-cell"});
			$('table#narrowSearch').corner('keep bottom');
			$('table#narrowSearch td.resultDisplay').corner('keep 5px');
		});

	} else { 
		setState = "top";
		$("#narrowSearch td.resultDisplay").animate({height:"toggle",opacity:"toggle"}, 500, function() {																			
			$("#guideControls").fadeOut('fast');
			$('table#narrowSearch').corner('keep bottom');
			$('table#narrowSearch td.resultDisplay').corner('keep 5px');
		});	
	}	 
	$(this_elem).find("div#nsSlideBtn").css({background:"transparent url(media/images/icons/slider-arrows.gif) "+setState+" left no-repeat"});
}

//*************************************************************
function toggleOverview(this_elem, event) {
	// Convert selected element into jQuery object;
	var thisObj = $(this_elem);

	thisObj.find("img.floorplanImg").mouseover(function() {
		// Get element identifier
		var objId = thisObj.attr("id");
		var objIdx = objId.split("_");

		// Get overviewLayer element and convert to jQuery object
		var layerObj = thisObj.find("#overviewLayer_"+objIdx[1]);

		// Get sizes and positioning of selected elements.
		var objW = thisObj.outerWidth();
		var layerW = layerObj.outerWidth();
		var pageW = pageWidth();
		var getPos = getCursorPosition(event);
		var setPos = 0;
		var setImg = '';
		
		// Figure out mouse location and display layer relative to element and its position in document
		if(getPos.x > (pageW/2)) { 
			setPos = -layerW; 
		} else { 
			setPos = objW;
		}		
		thisObj.css({zIndex:1});
		layerObj.css({display:"block", top:0, left: setPos+"px", zIndex:3000}).corner("keep 5px");
		
		// Hide layer and return element to original state
		thisObj.mouseout(function() {
			thisObj.css({zIndex:0});
			layerObj.css({display:"none"});
		});
	});
}

//*************************************************************
function showToolTip(this_elem,attrib,position) {
	if(setToolTips == 'CHECKED') { return false; }
	//Grab needed elements: hidden tooltip div & content from info element
	var infoTip_elem = document.getElementById('tooltip');
	
	// Specify attribute to get content from using the 'attrib' argument
	var txtTip = this_elem.getAttribute(attrib);
	
	// Make our tip visible and put in our content
	infoTip_elem.style.display = 'block';
	$("#tooltip p").html(txtTip);

	var tipW = infoTip_elem.offsetWidth; 
	var tipH = infoTip_elem.offsetHeight;
	
	// Detect location of mouse and set distance of tip from mouseovered element
	$(document).mousemove(function(e) {
		// Set location of tooltip by "right,left,top,bottom" or if empty, use default with tip to rightside
		switch(position) {
			case "top":
				$("#ttipArrow").attr({src:"media/images/blank.gif"}).css({display:"none"});
				if(navigator.appName == "Microsoft Internet Explorer") {
					infoTip_elem.style.top = (e.clientY + document.documentElement.scrollTop - (tipH + 20)) + "px";
					infoTip_elem.style.left = (e.clientX + document.documentElement.scrollLeft - (tipW/2)) + "px";
				} else {
					infoTip_elem.style.top = (e.pageY - (tipH + 20)) + "px";
					infoTip_elem.style.left = (e.pageX - (tipW/2)) + "px";
				}
				break;
			case "right":
				$("#ttipArrow").attr({src:"media/images/tooltip_right.png"}).css({display:"block"});
				$("#ttipArrow").attr('style',"display:block;position:absolute;left:-20px;top:20px;width:21px;z-index:25;");
				if(navigator.appName == "Microsoft Internet Explorer") {
					infoTip_elem.style.top = (e.clientY + document.documentElement.scrollTop - (tipH/2)) + "px";
					infoTip_elem.style.left = (e.clientX + document.documentElement.scrollLeft + 25) + "px";
				} else {
					infoTip_elem.style.top = (e.pageY - (tipH/2)) + "px";
					infoTip_elem.style.left = (e.pageX + 25) + "px";
				}
				break;
			case "left":
				$("#ttipArrow").attr({src:"media/images/tooltip_left.png"}).css({display:"block"});
				if(navigator.appName == "Microsoft Internet Explorer") {
					$("#ttipArrow").attr('style',"display:block;position:absolute;right:-16px;top:25px;width:25px;");
					infoTip_elem.style.top = (e.clientY + document.documentElement.scrollTop - (tipH/2)) + "px";
					infoTip_elem.style.left = (e.clientX + document.documentElement.scrollLeft - (tipW + 20)) + "px";
				} else {
					$("#ttipArrow").attr('style',"display:block;position:absolute;right:-19px;top:28px;width:20px;");
					infoTip_elem.style.top = (e.pageY - (tipH/2)) + "px";
					infoTip_elem.style.left = (e.pageX - (tipW +20)) + "px";
				}
				break;
			case "bottom":
				$("#ttipArrow").attr({src:"media/images/blank.gif"}).css({display:"none"});
				if(navigator.appName == "Microsoft Internet Explorer") {
					infoTip_elem.style.top = (e.clientY + document.documentElement.scrollTop + 20) + "px";
					infoTip_elem.style.left = (e.clientX + document.documentElement.scrollLeft - (tipW/2)) + "px";
				} else {
					infoTip_elem.style.top = (e.pageY + 20) + "px";
					infoTip_elem.style.left = (e.pageX - (tipW/2)) + "px";
				}				
				break;
			default:
				$("#ttipArrow").attr({src:"media/images/tooltip_right.png"}).css({display:"block"});
				$("#ttipArrow").attr('style',"display:block;position:absolute;left:-20px;top:20px;width:21px;z-index:25;");
				if(navigator.appName == "Microsoft Internet Explorer") {
					infoTip_elem.style.top = (e.clientY + document.documentElement.scrollTop - 20) + "px";
					infoTip_elem.style.left = (e.clientX + document.documentElement.scrollLeft + 25) + "px";
				} else {
					infoTip_elem.style.top = (e.pageY - 20) + "px";
					infoTip_elem.style.left = (e.pageX + 25) + "px";
				}
		}

		//Detect current target under mouse. If it doesnt match our selected element, then hide tip
		if (!e) var e = window.event;
		var tg = (window.event) ? e.srcElement : e.target;
		if (tg.nodeName != 'IMG') {
			infoTip_elem.style.display = 'none';
			$("#ttipArrow").attr({src:"media/images/blank.gif"}).css({display:"none"});
		}
		
	});

}

/************************** Update Session data display function ************************/
function updateSessionData() {
	// update session data when ajax call is made for debugging.
	$.get(processor, {sessionid: session_id, cmd:'showsessiondata'}, 
		function(data){						
			if (data.length > 0){
				$("#showsessiondata").html(data);
			}
		}
	);
}

/******************* Product & Selector Page Specific Functions *************************/
function getProductsArray() {
	$.ajax({url: processor,
		    type: 'GET',
			cache: true,
			dataType: 'json',
			async: false,
			data: {cmd:"displayBrands", sessionid:session_id, cache: ""+new Date().getTime()+"" } ,
			success: function(data,status) {
				//$("#productsDisplay_wrapper").html(data.contentdata);
				content = data.contentdata;
				setTimeout("document.getElementById('productsDisplay_wrapper').innerHTML = content",100);
			}
	});
}

//*************************************************************
function animClassBtnOn(this_elem) {
	var classBtn = $(this_elem);
	classBtn.addClass("current");	

	classBtn.css({width:'200px', height:'20px'}).find("a.caption").css("font-size","1.2em");
}

//*************************************************************
function animClassBtnOff(this_elem) {
	var classBtn = $(this_elem);

	if( classBtn.hasClass("current") ) {
		classBtn.removeClass("current");	
		classBtn.css({width: '160px', height: '15px'}).find("a.caption").css("font-size","1.0em");
	}
}

//*************************************************************
function updateModelResults(htmlStr){
	content = htmlStr;
	setTimeout("$('#productsDisplay_wrapper').html(content).corner('top keep 10px');;$('div.subpg_classheader').corner('top keep 10px');",100);	
}

function updateDisplayResults(htmlStr){
	contentAlt = htmlStr;
	setTimeout("$('#selectorImg_wrapper').html(contentAlt).css('display','block');",100);	
}
//*************************************************************
function updateSearch(content) {
	var newVal;
	var setBGColor = '';
	
	$("#form_filter :input, #form_filter :checkbox, #form_filter :radio").change(function() {
		newVal = $("#form_filter").serializeArray();
		tmr = 1;
		$("#productsDisplay_wrapper").html("");
		$.ajax({url: processor,
			cache: true,
			dataType: "json",
			async: true,
			data: {cmd:"updateBrands", sessionid:session_id, fn: class_id, bcode: bcode, serialarr: newVal, cache: ""+new Date().getTime()+"" } ,
			success: function(data,status) {				
				if(class_id == 'bybrand' || pagename == 'index') { 
					$("#productsDisplay_wrapper").css("background","#e0e0e0").corner('top cc:#000 10px');
					$("#selectorLinks").html(data.level).css("display","block");
					centerVert($('.resultLinkImg'), '.resultLink');
				}
				$("#productsDisplay_wrapper").css({display:"block"});
				content = data.contentdata;
				updateModelResults(content);				
				
				$("table#narrowSearch").corner("keep bottom");
				$("table#narrowSearch td").corner("keep 5px");
				$(".printme").css("display","block");
				$("#selectorImg_wrapper").html(data.userdata).css("display","block");
				$("#narrowSearchCount").html("<b>"+data.widgetdata+"</b>").css("display","block");
				document.location.href = "#models";
			}
		});
	});

	$("img#sl0slider,img#sl1slider,img#sl2slider").mouseup(function() {
		newVal = $("#form_filter").serializeArray();
		tmr = 1;
		$.getJSON(processor, {cmd:"updateBrands", sessionid:session_id, fn: class_id, bcode: bcode, serialarr: newVal} , function(data) {
			if(class_id == 'bybrand' || pagename == 'index') { 
				$("#productsDisplay_wrapper").css("background","#e0e0e0").corner('top cc:#000 10px');
				$("#selectorLinks").html(data.level).css("display","block");
				centerVert($('.resultLinkImg'), '.resultLink');
			}
			$("#productsDisplay_wrapper").css({display:"block"});
				content = data.contentdata;
				updateModelResults(content);
			
			$("table#narrowSearch").corner("keep bottom");
			$("table#narrowSearch td").corner("keep 5px");
			$(".printme").css("display","block");
			$("#selectorImg_wrapper").html(data.userdata).css("display","block");
			$("#narrowSearchCount").html("<b>"+data.widgetdata+"</b>").css("display","block");
			document.location.href = "#models";
		});
	});

	$("#resetfilters").click(function() {
		$.getJSON(processor, {cmd:"displayBrands", sessionid:session_id, fn: class_id, bcode: bcode} , function(data) {
			document.form_filter.reset();
			
			/*$("form#form_filter input").each(function() {
				var getNameVal = $(this).attr("name");
				if( getNameVal.indexOf('dry_weight') != -1) { alert("You found me"); }
			});*/
			$('img[id$="slider"]').css({left:"135px"});
			
			content = data.contentdata;
			updateModelResults(content);
			contentAlt = (data.response == '60') ? data.response+" max" : data.response;
			
			if(class_id == 'bybrand' || pagename == 'index'){ 
				$("#productsDisplay_wrapper").css({display:"none",background:"transparent"}); 
				//$("#subpg_container").css("background","#000000");
				$("#selectorImg_wrapper").html("").css("display","none");
				$("#selectorLinks").html("").css("display","none");
				$("#narrowSearchCount").css("display","none");
				$(".printme").css("display","none");
				current_theme = 'bybrand';
			} 
			
			$("table#narrowSearch").corner("keep bottom");
			$("table#narrowSearch td").corner("keep 5px");
			$("#selectorImg_wrapper").html(data.userdata).css("display","block");
			$("#narrowSearchCount").html("<b> ("+contentAlt+") Models Displayed of ("+data.widgetdata+")</b>");
			document.location.href = "#models";
		});
	});

	if(tmr = 1) { clearInterval(prodSelectTimer); tmr = 0; }
}

//*************************************************************
function activeItemLink(this_elem, event) {
	var setObj = $(this_elem);
	var itemName = setObj.attr("title");
	var linkUrl = setObj.attr("rel");
	var contentid = setObj.attr("rev");
	var isActive = setObj.hasClass("active");
	var needsLead = setObj.hasClass("leads");
	var btnObj;

	if(isActive && itemName == 'Videos') { window.location.href = '#mediaview'; $("#mediaplayer").click();
	} else if(itemName == 'Facebook') { window.location.href = '#mediaview'; $("#facebook").click();
	} else if(itemName == 'Floorplans & Photos') { 
		window.location.href = linkUrl+'#mediaview'; $("#models").click();
	} else if(itemName == 'slideshow' || itemName == 'view360') {

		$("#brand_control_buttons a").each(function(i) {
			if( itemName == $(this).attr("title") && !isActive) {
				$("#view_"+itemName).animate({width:'650px'}, 500, function(){
					$(this).css("display","block");
					setObj.addClass("active");
					setObj.parent().addClass("current");
					if(itemName == 'view360') { 
						load360('load', setObj.attr("rel"));
						$("#view_slideshow").cycle("pause"); 
					} else if(itemName == 'slideshow'){
						$("#view_slideshow").cycle("resume"); 
						$("#view_slideshow").before("<div id='view_slideshow_prevBtn' class='slideshow_btns' alt='Previous Image' title='Previous Image'><img alt='Previous Image' title='Previous Image' src='/media/images/icons/prev.gif'></div> <div id='view_slideshow_nextBtn' class='slideshow_btns' alt='Next Image' title='Next Image'><img alt='Next Image' title='Next Image' src='/media/images/icons/next.gif'></div>");							
					}
				}).css({"display":"block","zIndex":"3"});
			} else if( itemName == $(this).attr("title") && isActive ) {
				// Do Nothing
			} else {
				$("#view_"+$(this).attr("title")).animate({width:'0'}, 500, function(){}).css({"display":"none","zIndex":"2"});
					$(this).css("display","block");
					$(this).removeClass("active");
					$(this).parent().removeClass("current");
					if(itemName == 'view360') { 
						load360('unload');
						$("#brand_slidecaption").css({"display":"none"});
						$("#view_slideshow_prevBtn, #view_slideshow_nextBtn").detach(); 
					}
				
			}
		});
	
	} else if(isActive && (itemName.search(/Brochure/i) !== -1 || needsLead) && linkUrl.match(/.pdf/)) { 		
		openLbox("templates/request_form.php?sessionid="+session_id+"&brochure="+linkUrl,'800','600');
	} else if(isActive && (itemName.search(/Brochures/i) !== -1) && linkUrl.match(/all_pdfs/)) { 		
		openLbox("templates/request_form.php?sessionid="+session_id+"&brochure="+linkUrl,'800','600');		
	} else if(isActive && linkUrl.match(/.pdf/)) {
		cconfirm(itemName,"Would you like to View or Download this document",linkUrl);
	} else if(isActive && (linkUrl.match(/.php/) || linkUrl.match(/.html/)) && itemName != 'Send Us your Ideas' ) {
		openLbox(linkUrl,'800','600');
	} else if(isActive && (linkUrl.match(/.php/) || linkUrl.match(/.html/)) && itemName == 'Send Us your Ideas' ) {
		openLbox(linkUrl,'690','480');
	} else if(isActive && contentid != 0 && linkUrl.length == 0) {
		window.location.href = "index.php?p="+contentid;
	}
}

//*************************************************************
function load360(cmd, url) {
	if(cmd == 'load') {
		//Create empty wrapper and place 360 inside
		document.getElementById("view_view360").innerHTML = "<div id='view_view360_wrapper'></div>";
		var flashvars = {};
		var params = {};
		params.wmode = 'opaque';
		params.allowfullscreen = true;
		params.allowscriptaccess = 'always';
		var attributes = {};

		swfobject.embedSWF(url, 'view_view360_wrapper', '650', '400', '9.0.0','expressInstall.swf', flashvars, params, attributes);
	
	} else if(cmd == 'load') {
		//Clear out wrapper and 360
		document.getElementById("view_view360").innerHTML = "";
	}
}

//*************************************************************
function centerVert($obj, $holder){
	var holder = $obj.parents($holder);
	if($obj.height() < holder.height()){
		$obj.css({'margin-top':(holder.height() - $obj.height()) / 2});
	}
}

//*************************************************************
function loadIOnlyWeigh(modelname){
	var timer;
	$.ajax({
		url: "templates/i-only-weigh.php",
		data: {sid: session_id, model: modelname, cache: ""+ new Date().getTime()+""},
		success: function(data, status){
			Shadowbox.open({			
				content: data,
				title: "I Only Weigh...",
				player: "html",
				height: 610,
				width: 720
			});
			
			if( $("#overlay_contain").length == 0 ) { timer = setTimeout("slideShowControl(); $('#overlay_contain').css({'margin': '5px','height': '600px'});", 2000); }
			
		}
	});
}

//*************************************************************
function moveDiv($this){
		var maker = $('.' + $this);
		var pos = maker.position();
		var manu_info = $('#manu_info').position();
		var cur_scroll = $('#manu_info').scrollTop();
		$('#manu_info').animate({'scrollTop': pos.top + cur_scroll - manu_info.top}, 400);	
}

//*************************************************************
function loadSlideShow(this_elem, modelname) {		
	var timer;

	$.ajax({url: "templates/floorplan-slideshow.php",
		data: {sid: session_id, i: modelname, cache: ""+new Date().getTime()+"" }, 
		success: function(data,status) {
			Shadowbox.open({
				content: data,
				title: unescape(String(modelname).replace(/\+/g, " "))+" Floorplan Slideshow",
				player: "html",
				height: 510,
				width: 710,
				onClose: function() { clearTimeout(timer); $('.slideshow').cycle('destroy'); }
			});
			
			// Sets timer to attach control function to div after is ajaxed into DOM. Timer cleared on shadowbox close.
			if( $("#overlay_contain").length == 0 ) { timer = setTimeout("slideShowControl();", 2000); }
			
		}
	});	

}

//*************************************************************
function slideShowControl() {
	var loc,l,pos;
	var first = true;
	var slideId = '';
	
	$("#overlay_contain").css({overflow:"hidden"});

	$(".slideshow").each(function() {
		if(first){
			createFplanSSPager($(this).attr("id"));

			$(this).css("display","block").cycle({ 
					fx:'fade', 
					sync:true,
					before:function(a,b,c,d) {
						if ( $(b).find("img").attr("id").length > 4 ) {
							loc = $(b).find("img").attr("id");
							l = loc.split("_");
							pos = l[1].split(",");
							if( $("a[rel='"+loc+"']").length > 0 ) {
								$("a[rel='"+loc+"'] img").attr({src:"media/images/point.gif"});
							} 
						} 
						ploc = $(a).find("img").attr("id");							
						$("a[rel='"+ploc+"'] img").attr({src:"media/images/point_off.gif"});
					},
					pager: '#floorplanmap',
					pagerEvent: "mouseover",
					pagerAnchorBuilder: function(idx,slide) {
						return "#floorplanmap a:eq("+(idx+1)+")";
					},
					pauseOnPagerHover: true
			});
			first = false;
		} else {
			$(this).css("display","none");
		}
	});

	first = true;
	$('#album-select li').each(function(){
		if(first){
			$(this).addClass('selected');
			first = false;
		}else{
			$(this).removeClass('selected');
		}
	});

	$('#album-select a').click(function(){
		//Hide other slideshows
		$('.slideshow').each(function(){
			$(this).css({display:'none'});
		});

		//Clear floorplan annotated map
		$("#floorplanmap a[rel^='loc_']").detach();

		//Recreate floorplanmap
		createFplanSSPager($(this).attr('rel'));

		//Begin new slideshow with selected album
		$('#' + $(this).attr('rel')).css({'display':'block'}).cycle({ 
			fx:'fade', 
			sync:true,
			before:function(a,b,c,d) {
				if ( $(b).find("img").attr("id").length > 4 ) {
						
					loc = $(b).find("img").attr("id");
					l = loc.split("_");
					pos = l[1].split(",");

					if( $("a[rel='"+loc+"']").length > 0 ) {
						$("a[rel='"+loc+"'] img").attr({src:"media/images/point.gif"});
					} 
				} 
				
				ploc = $(a).find("img").attr("id");							
				$("a[rel='"+ploc+"'] img").attr({src:"media/images/point_off.gif"});
			},
			pager: '#floorplanmap',
			pagerEvent: "mouseover",
			pagerAnchorBuilder: function(idx,slide) {
				return "#floorplanmap a:eq("+(idx+1)+")";
			},
			pauseOnPagerHover: true
		});
		$('#album-select li').removeClass('selected');
		$(this).parent('li').addClass('selected');
	});
							
}

//*************************************************************
function createFplanSSPager(selector) {
	$("#"+selector+" img").each(function() {
		if ( $(this).attr("id").length > 4 ) {
			loc = $(this).attr("id");
			l = loc.split("_");
			pos = l[1].split(",");
			$("#pinpoint").clone().css({display:'block',left:(pos[0]-8)+"px", top:(pos[1]-8)+"px"}).attr({rel:loc,src:"media/images/point.gif"}).appendTo("#floorplanmap");
		}
	});

}

/*************************** Flowplayer Mediaplayer Functions ****************************/
function onYouTubePlayerReady(playerId) {
	// This function gets called from the youtube API automatically. Gets state change status
	ytplayer = document.getElementById("mediaplayer-ytube");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

//*************************************************************
function onytplayerStateChange(newState) {
	// Callback expose function for youtube state change  
	if(newState == 1 || newState == 5) {
		exposeOverlay(1);
		isExposeActive = true;
	} else {
		exposeOverlay(0);
		isExposeActive = false;
	}
}

//*************************************************************
function exposeOverlay(state) {
	if(state == 0 && isExposeActive) {
		$("#brand_mediaview").css({zIndex:0});
		$("#expose_overlay").detach();
		isExposeActive = false;
	} else if(state == 1 && !isExposeActive) {
		$("#brand_mediaview").css({zIndex:2000}).prepend("<div id='expose_overlay'></div>");
		isExposeActive = true;
	}
}


/***************************** Url encode/decode function *******************************/
function urldecode (str) {
    
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
    
    var replacer = function (search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
    hash_map['%20'] = '+';
    hash_map['\u00DC'] = '%DC';
    hash_map['\u00FC'] = '%FC';
    hash_map['\u00C4'] = '%D4';
    hash_map['\u00E4'] = '%E4';
    hash_map['\u00D6'] = '%D6';
    hash_map['\u00F6'] = '%F6';
    hash_map['\u00DF'] = '%DF';
    hash_map['\u20AC'] = '%80';
    hash_map['\u0081'] = '%81';
    hash_map['\u201A'] = '%82';
    hash_map['\u0192'] = '%83';
    hash_map['\u201E'] = '%84';
    hash_map['\u2026'] = '%85';
    hash_map['\u2020'] = '%86';
    hash_map['\u2021'] = '%87';
    hash_map['\u02C6'] = '%88';
    hash_map['\u2030'] = '%89';
    hash_map['\u0160'] = '%8A';
    hash_map['\u2039'] = '%8B';
    hash_map['\u0152'] = '%8C';
    hash_map['\u008D'] = '%8D';
    hash_map['\u017D'] = '%8E';
    hash_map['\u008F'] = '%8F';
    hash_map['\u0090'] = '%90';
    hash_map['\u2018'] = '%91';
    hash_map['\u2019'] = '%92';
    hash_map['\u201C'] = '%93';
    hash_map['\u201D'] = '%94';
    hash_map['\u2022'] = '%95';
    hash_map['\u2013'] = '%96';
    hash_map['\u2014'] = '%97';
    hash_map['\u02DC'] = '%98';
    hash_map['\u2122'] = '%99';
    hash_map['\u0161'] = '%9A';
    hash_map['\u203A'] = '%9B';
    hash_map['\u0153'] = '%9C';
    hash_map['\u009D'] = '%9D';
    hash_map['\u017E'] = '%9E';
    hash_map['\u0178'] = '%9F';
    hash_map['\u00C6'] = '%C3%86';
    hash_map['\u00D8'] = '%C3%98';
    hash_map['\u00C5'] = '%C3%85';
 
    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}

//*************************************************************
function showSession() {
	 HideShow('session');
}

//*************************************************************
function repeat(s, n){
    var a = [];
    while(a.length < n){
        a.push(s);
    }
    return a.join('');
}

//*************************************************************
function GoBack(url) {
	document.location.href=url;
}

//*************************************************************
function addNewElement(id,type,position) {
	var elem = document.getElementById(id);
	var child = document.creatElement(type); 
	elem.insertBefore(child, elem.getElementsByTagName('type')[position]);
}

//*************************************************************
function removeElement(id) {
	var elem=document.getElementById(id);
	elem.parentNode.removeChild(elem);
}

//*************************************************************
function f_setfocus( aForm )
// set focus on first text input field
{
	if( aForm.elements[0]!=null) {
		var i;
		var max = aForm.length;
		for( i = 0; i < max; i++ ) {
			if( aForm.elements[ i ].type == "text" &&
				!aForm.elements[ i ].disabled &&
				!aForm.elements[ i ].readOnly ) {
				aForm.elements[ i ].focus();
				break;
			}
		}
	}
}

//*************************************************************
function getCursorPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};

    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;

    }  else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }

    return cursor;
}

//*************************************************************
function Hide(el_id){
	curdiv = document.getElementById(el_id);
	curdiv.style.display = 'none';
	return;
}

//*************************************************************
function Show(el_id){
	curdiv = document.getElementById(el_id);
	curdiv.style.display = 'block';
	return;

}

//*************************************************************
//  Toggle Hide/Show
function HideShow(el_id){
	curdiv = document.getElementById(el_id);
	if(curdiv.style.display == 'none') curdiv.style.display = 'block';
	else curdiv.style.display = 'none';
	return;
}


//*************************************************************
//Trim left and right space on text string
function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

//*************************************************************
function trimAll(sString)
{
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
return sString;
} 

//*************************************************************
function windowPop(url,width,height) {
 var newwindow = window.open(url,'windowPop','height='+height+', width='+width+', resizeable=1, scrollbars=1, toolbar=0, menubar=0, status=0');
 if(window.focus) { newwindow.focus(); }
 return false;
}

//*************************************************************
function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

//*************************************************************
function getkey(e) {
	if (window.event)
	   return window.event.keyCode;
	else if (e)
	   return e.which;
	else
	   return null;
}

//*************************************************************
function goodchars(e, goods) {
	var key, keychar;
	key = getkey(e);
	if (key == null) return true;

	// get character
	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	goods = goods.toLowerCase();

	// check goodkeys
	if (goods.indexOf(keychar) != -1)
			return true;

	// control keys
	if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
	   return true;

	// else return false
	return false;
}

//*************************************************************
function isValidEmailAddress(emailAddress) {

	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);

	return pattern.test(emailAddress);
}

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

Array.min = function( array ){
    return Math.min.apply( Math, array );
};

//*************************************************************
// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well
function pageWidth() {
	return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
} 

function pageHeight() {
	return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
} 

function posLeft() {
	return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
} 

function posTop() {
	return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
} 

function posRight() {
	return posLeft()+pageWidth();
} 

function posBottom() {
	return posTop()+pageHeight();
}

// *********************** Custom Cursor Script *************************

