/*
	
	Project Name Global Javascript Functions
	By  - ISITE Design

*/

// jquery no conflict. use $j or jQuery outside of ready function
var $j = jQuery.noConflict(); 


// jQuery document ready
jQuery(function ($) {

	// JS enabled
	$('html').addClass('js');

	// Few setups for IE6
	if (document.all) {
		//add class to drop downs and buttons 
		$('#nav li, button').hover(
			function () { $(this).addClass('over'); },
			function () { $(this).removeClass('over'); }
		);
	} // if document.all
	
	//Alt clean up
	$('img').each(function(){
		$(this).attr('alt',$(this).attr('alt').replace(/&amp;#8209;/g,'-'));
		$(this).attr('alt',$(this).attr('alt').replace(/&#8209;/g,'-'));
	});
	
	$('#nav-utility input[type=text]').inputSetter();
	$('.color-chips').imageSwitcher();
	$('.tabs').IX_tabs();
	$('#flash').swfobjActivate();
	$('#message-scripting-errors').reportErrors();
	$('ul.tree').enableTree();
	$('.slideshow').slideshow();


	$("a[rel=external]").attr("target", "_blank");
	
	//product nav sibling ul hide condition
	$('#nav-sub a.on').each(function(){
		if($(this).parents('ul.pages').length > 0){
			$('ul.pages').toggle();
			$(this).parents('ul.pages').toggle();
		}else{
			$(this).siblings('ul').find('ul.pages').toggle();
		}
	});
		//product nav collapse and expand
		$('#nav-sub .active a:not(ul.pages a)').each(function(){
			$(this).click(function(event){
				if($(this).parents('ul').length > 1 && $(this).next('ul.pages').length > 0){
					$('ul.pages').not($(this).next('ul.pages')).hide();
					$(this).next('ul.pages').toggle();
					event.preventDefault();
				}
			});
		});	
	
	//popup window control
	$('a.popup').live('click', function(){
		var uri = $(this).attr('href'),
			redirect = jQuery(this).attr('href'),
			params = getQueryParams(uri);
		var	newwindow=window.open(redirect,'','status=yes,scrollbars=yes,resizable=yes,width='+params["width"]+',height='+params["height"]);
		if (window.focus) {newwindow.focus()}
		return false;
	});

});    // document ready


// application logic



//plugin function for DenTrek Product Videos
function TutorialPopup( TutorialID )
{
    var aurl = 'http://www.dentrek.com/console/flashConsole.asp?x_slidetype=4&x_classid=' + TutorialID
             + '&x_url=' + escape(document.location.href) + '&dummy=' + (new Date).getTime();
var GetConsoleWindow = window.open( aurl, '_blank', 'width=700,height=500,scrollbars=no,status=no,resizable=no,directories=no');
}    



// jQuery plugins

jQuery.fn.swfobjActivate = function(){
	return this.each(function() {
		// get the url of the resource and set height and width based on get query, if present.
		var e = jQuery(this),
			f = e.find('a').attr('href'),
			o = f.substr(f.indexOf('?')+1).split('&'),
			h = 0,
			w = 0;
		for(var i=0;i<o.length;i++) {
			if (o[i].match(/height/)) { h = parseInt(o[i].substr(o[i].indexOf('=')+1)); }
			if (o[i].match(/width/)) { w = parseInt(o[i].substr(o[i].indexOf('=')+1)); }
		}
		// if no get query we'll assume some default settings.
		h = (h === 0) ? 390 : h;
		w = (w === 0) ? 780 : w;
		e.flash({
			swf: f,
			height:h,
			width:w,
			wmode: 'transparent'
		});
	});
};
jQuery.fn.reportErrors = function() {
	var $o = jQuery(this);
	setCookie('ixTest', true);
	if (getCookie('ixTest')) { $o.remove(); }
	else { $o.text('You must have cookies enabled to use this site'); }
	deleteCookie('ixTest');
};

jQuery.fn.inputSetter = function(lower) {	
	return this.each(function() {
		var $input = jQuery(this);
		var $label = jQuery("label[for='"+$input.attr("id")+"']");
		var labeltext = lower && lower==1 ? $label.text().toLowerCase() : $label.text();
		$label.hide();	
		$input.val(labeltext).addClass('preset');		
		$input.focus(function() { if (this.value == labeltext) { this.value = ""; jQuery(this).removeClass('preset'); }	})
			  .blur(function() { if (!this.value.length) { this.value = labeltext; jQuery(this).addClass('preset'); } });		
	});
};

jQuery.fn.imageSwitcher = function() {
	var $label		= jQuery('<div id="color-name"><strong></strong></div>'),
		$labelText	= $label.find('strong');
	return this.each(function(){ 
		var $list	= jQuery(this),
			$links	= $list.find('a'),
			$hero 	= jQuery('#lead .hero img');
		// function called from tabs to update hero when tab is opened.
		$list.bind('updateImage', function(){ 
			jQuery('#lead').append($label);
			jQuery('.default a').trigger('mouseenter');
		});
		$links.each(function(){
			var $o 			= jQuery(this),
				colorName	= $o.find('span').text();
			$o.data('image', this.href);
			$o.data('alt', $o.find('img').attr('alt'));
			this.href = '#';
			$o.bind( {
				mouseenter: function(e){
								if(!$j('#color-name').length){
									jQuery('#lead').append($label);
								}	
								jQuery('.default').removeClass('default');
								$o.parent('li').addClass('default');
								$hero.attr('src', $o.data('image')).attr('alt',$o.data('alt')); 
								$labelText.text(colorName); 
								e.preventDefault();
							},
				click:		function(e){ e.preventDefault(); }
			});
		});
	});
};

// generic tab builder
jQuery.fn.IX_tabs = function (tab) {

	// prevents scroll on page load. yucky but effective
	if (location.hash) { jQuery('html, body').animate({ scrollTop: 0 }, 0); }
	return this.each(function () {
		var $container = jQuery(this),
			$tabs = jQuery("a", this),
			$hero = jQuery('#lead .hero'),
			$heroimg = jQuery('#lead .hero img'),
			$heroflash = jQuery('#lead .hero .flash'),
			panes = new Array();
		
		if($heroimg.length < 1) { 		
			$hero.append('<img />');
			$heroimg = jQuery('#lead .hero img');
		}
		if($heroflash.length < 1) {
			$hero.append('<div class="flash" />');
			$heroflash = jQuery('#lead .hero .flash');
		}

		$tabs.each(function () {
			var $this = jQuery(this);

			// using the href to make the collection of panes			
			var pane = $this.attr('href');
			if (pane.indexOf("#") != 0) {
				return true;
			}
			panes.push(pane);

			$this.bind("click", function (){
				var $pane = jQuery(pane);
				//build the jq selector. cheap.
				jQuery(panes.join(",")).hide();

				//do some class switching
				$container.find('.active').removeClass('active');
				$this.parent("li").addClass("active");

				//change out the hero image and show the pane
				if ($pane.data('hero')) {
					$heroimg.attr('src', $pane.data('hero')).attr('alt',$pane.data('alt'));
					$heroflash.html('');
				} 
				else if ($pane.data('flash')) {
					$heroimg.attr('src', '');
					$heroflash.flash({
						swf: $pane.data('flash'),
						height: 278,
						width: 520,
						wmode: 'transparent'
					});
				}
				else {

					$heroimg.attr('src', '');
					$heroflash.html('');
				}

				$pane.show();

				// if $pane contains color chips, initialize hero image and text, otherwise remove the text.
				if ($pane.find('ul.color-chips').length) { 
					$pane.find('ul.color-chips .default').parents('.color-chips').trigger('updateImage'); }
				else { 					
					jQuery('#color-name').remove(); 
				}

				// strip the id from the current pane long enought to write the hash, then add it back. prevents page scroll.
				$pane.attr('id', '');
				//window.location.hash = pane; Causing issuse, please see Paul.
				$pane.attr('id', pane.substr(1));

				// track the tab click with google analytics
				var title = $this.html();
				var url = window.location.pathname.substr(0, window.location.toString().lastIndexOf("#"));

				_gaq.push(['_trackPageview', url + "?" + title]);

				return false;
			});
		});

		// pre-format the panes
		jQuery(panes.join(",")).each(function () {
			var $this = jQuery(this),
				$image = jQuery('img.hero', this),
				$flash = jQuery('a.hero', this);
			if ($image.length) {
				$this.data('hero', $image.attr('src'));
				$this.data('alt', $image.attr('alt'));
				$image.hide();
			} else if ($flash.length) {
				$this.data('flash', $flash.attr('href'));
			}
		});

		// set which tab to show
		var urltab = window.location.hash;
		var show = urltab != "" || jQuery('a.default', $container).length ? urltab != "" ? $tabs.index(jQuery('a[href=' + urltab + ']')) : $tabs.index(jQuery('a.default')) : tab || 0;

		// make sure the tab we think we can show is actually there. if so, click it. else click the first tab
		$tabs.eq(show).length ? $tabs.eq(show).click() : $tabs.eq(0).click();
	});
};

// tree-expander for use with nested lists.
jQuery.fn.enableTree = function() {
	var obj = jQuery(this);
	
	// hide children and set up css
	obj.addClass("expander").find("li ul").hide();
		
	// insert the button to open/close and attach click event
	jQuery("li",obj).each(function(i){ 
		if(jQuery("li",this).length>0) {
			jQuery(this).addClass('toggle').prepend('<a class="btn" href="#">+</a>');
			jQuery("a.btn",this).click(function(){                                                                                                                                                     
				var textinsert = jQuery(this).text() == "+" ? "-" : "+";
				jQuery(this).text(textinsert).toggleClass("open").parent("li").find("ul:first").slideToggle("fast");                                                                
				return false;                                       
			});
		} 
	});

	return this;	
};

jQuery.fn.slideshow = function (opts) {
    var $slidedeck,
		slides,
		preload = [],
		options = {
		    delay: 16000,
		    transition: 3000
		}, // if required

		templates = '<li style="background-image:url(<%image%>);"><div class="content"><h2><%title%></h2><%content%></div></li>',

    // methods
    cycle = function () {


        $slides.filter('.current').fadeOut('3000', function () {

            var nextindex = $slides.filter('.next').index();
            jQuery(this).removeClass('current').show();
            $slides.filter('.next').removeClass('next').addClass('current');

            $slides.eq(nextindex === ($slides.length - 1) ? 0 : nextindex + 1).addClass('next');

        });

    };

    options = jQuery.extend(options, opts);

    this.each(function () {
        var $this = jQuery(this);

        $slidedeck = jQuery('.slides', this);
        

        for (i = 0; i < slidedata.length; i++) {

            preload[i] = jQuery('<img />').attr('src', slidedata[i].image);

            $slidedeck.append(templates.replace(/<%image%>/, slidedata[i].image).replace(/<%title%>/, slidedata[i].title).replace(/<%content%>/, slidedata[i].content));
        }

        $this.append($slidedeck);


        // at this point, we have a clone of the slideshow in memory, not in the DOM yet.

        // add a class to the currently visible item in the array, and to the second item in the array.  the others should be hidden by CSS.
        // all li's should be positioned absolutely, and the .slideshow container should have a position relative to create a positioning context
        // the next class should give the li a low z-index and a position inside the slideshow
        // the current class should give the li a high z-index and a position inside the slideshow

        $slides = $this.find('li');

        $slides.eq(1).addClass('next');

        setInterval(cycle, options.delay);

    });
};



// etc

//uri value gatherer
function getQueryParams(strUri)   {
 var paramMap = {};
 if(!strUri)   {
	return paramMap;
 }
 var strQuery = strUri.substring(strUri.indexOf("?"));
 if(strQuery.lastIndexOf("#") !== -1) {
	strQuery = strQuery.substring(0, strQuery.lastIndexOf("#"));
 }
 if(strQuery && strQuery.indexOf("?") === 0 && strQuery.length > 1) {
	strQuery = strQuery.substring(1);
	var paramValArr = strQuery.split("&");
	for(var i = 0, len = paramValArr.length; i < len; i++)   {
	   var paramVal = paramValArr[i];
	   var delimIdx = paramVal.indexOf("=");
	   var param = null;
	   var val = null;
	   if(delimIdx >= 0) {
		  param = unescape(paramVal.substring(0, delimIdx));
		  val = unescape(paramVal.substring(delimIdx + 1));
	   }else {
		  param = unescape(paramVal);
	   }
	   paramMap[param] = val;
	}
 }
 return paramMap;
}

// cookie functions
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null;	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; }
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "/" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "/") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


// clean console.log
function cl(){ if(window.console&&window.console.firebug) { var args = [].splice.call(arguments,0); console.log(args.join(" ")); } }//cl()
// example: cl("If you use cl() instead of console.log(), it won't break IE when you forget to take it out.");


// IE6 fixes
// make sure IE has the abbr and acronym tag
if(document.all){
	document.createElement("abbr");
	document.createElement("acronym");
}
// prevent IE6 flicker
try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}


//ie6 specifics trigger from conditional comment
var initIE6 = function() {
	// old browser
	$j('body').prepend('<div class="browser-notice"><p>Hi! Looks like you are using an old browser. Things may look a little off around here. For a better internet experience, consider <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">upgrading your browser</a> or <a href="http://www.alternativebrowseralliance.com/browsers.html">trying a new one</a>.</p></div>');
	$j('html').addClass('ie6');
}

