//<!--
/*********** Code from others *******************/
/*
    Written by Jonathan Snook, http://www.snook.ca/jonathan
    Add-ons by Robert Nyman, http://www.robertnyman.com
*/

function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}
/************************************************
* Emulate the IE link.click method.
* plnkNode - The link object to emulate the click on.
************************************************/

function BrowserLinkClick(plnkNode) {

/*    if (plnkNode.click){
      //return;
    }
*/
    // Emulate click on Mozilla
    var bolFollowLink = false;
    var strTarget = null;
    // Run the link onClick event.
    if (plnkNode.onclick) {
        if (plnkNode.onclick() == false){
            bolFollowLink = false;
        }
    }

    // Get the link target.
    if (plnkNode.target) {
        strTarget = plnkNode.target;
    }
    if (bolFollowLink){
        if (strTarget == null) {
            // Open using the default target if not set on the link.
            window.open(plnkNode.href);
        } else {
            // Open using the link target.
            window.open(plnkNode.href, strTarget);
        }
    }
}


function OldMozillaLinkClick(plnkNode) {
    // Emulate click on Mozilla
    var bolFollowLink = false;
    var strTarget = null;
    // Run the link onClick event.
    if (plnkNode.onclick) {
        if (plnkNode.onclick() == false){
            bolFollowLink = false;
        }
    }

    // Get the link target.
    if (plnkNode.target) {
        strTarget = plnkNode.target;
    }
    if (bolFollowLink){
        if (strTarget == null) {
            // Open using the default target if not set on the link.
            window.open(plnkNode.href);
        } else {
            // Open using the link target.
            window.open(plnkNode.href, strTarget);
        }
    }
}


/*****************************************************
Written by Lee Pumphret
*****************************************************/

/* GLOBALS #########################################*/
var wwepopimCSS = 'popwin.css'; /* CSS for im popup */




var wweImWin; // our image pop win
var wweImWinOpen = 0;
var wwepopimLoading = '';
var wweMainImageWindowLink;
var wwePreloads;

/* CONTENTS SORT CONFIG ############################*/
var sort_attrib = 'title'; /* default sort by */
var sort_direction = 0;    /* 0 = asc, 1 = desc */
var sort_numeric   = 0;    /* 0 = alpha, 1 = numeric */


/* SLIDESHOW CONFIG ################################*/
var slideShow;  /* Slide show obj */
var slideShowSleepMS = 3500; /* Default delay before image advance */

var tempIm;                  // for pausing until loaded
//var PopIm;
//var mPop;


/* PRODUCT SPEC CONFIG #############################*/
var specTargName = ''; /* if specified, will change wweLinkScrub to this target onload */
var SpecDivMinHeight = 150;   /* min spec height */
var SpecDivMaxHeight = 500;   /* max before scroll */

var minSpecDivHeightFound = 8000;/* Height of smallest div, set in init */
var maxSpecDivHeightFound = 0;   /* Height of tallest div, set in init  */
var maxSpecDivHeightDiff = 300;  /* If the diff between specs divs < maxSpecDivHeightDiff, make them equal size */
var selectedSpecDiv;             /* Ref to last  spec highlighted       */

var FoundSpecsHeaders = new Array();  /* Storage for spec headers */
var FoundSpecs = new Array();         /* Storage for specs found  */

/*** Functions ***/


/******************************************/

/* TODO, srcdivid no longer needed, not for slides anyway */

function wweChangeIm(imgid,imgurl,fulltarg, x,y,srcdivid){
    /* changes the main product image */
    /* Used by slideshow and normal images */

    var el = document.getElementById(imgid);
    /* add error check*/
    tempIm = new Image(x,y);
    tempIm.onload = function() {
        el.src=tempIm.src;
        el.width=x;
        el.height=y;
        var target = document.getElementById(imgid + 'link');
        target.href= fulltarg;
    }

    tempIm.src= imgurl;


    if (srcdivid){
        var hl = document.getElementById(srcdivid);
        if (hl){
            //hl.className = 'wweSlideDivHL';
        }
    }

}


/******************************************/
/* START SLIDESHOW FUNCTIONS #############*/
/******************************************/

/* Slide Show Object */
function wweSlideShow(title){
   this.title = title ? title : 'Gallery';
   this.Slides = new Array();
   this.LastSlide;
   this.CurrentSlide = 0;
   this.playing = 0;
   this.imPauseMS = 3000;
   this.NumSlides = 0;
   this.changer = function (){
      window.alert('Error:You haven\'t registered an Advance function!');
   }


}

wweSlideShow.prototype.changer = function (){
      window.alert('Error:You haven\'t registered an Advance function!');
}

wweSlideShow.prototype.slideCount = function (){
      return this.NumSlides;
}
wweSlideShow.prototype.start = function (){
     this.playing = 1; this.advance();
}
wweSlideShow.prototype.stop = function (){
     this.playing = 0;
}
wweSlideShow.prototype.isPlaying = function (){
     return this.playing;
}
wweSlideShow.prototype.previousSlide = function(){
     return this.Slides[this.LastSlide];
}
wweSlideShow.prototype.allSlides = function(){
   	 return this.Slides;
}
wweSlideShow.prototype.currentSlide = function(){
     return this.Slides[this.CurrentSlide];
};
wweSlideShow.prototype.setSpeed = function (speed){ // speed is in milliseconds
			if (!speed) return;
			this.imPauseMS = speed < 500 ? 500 : speed;
};

wweSlideShow.prototype.addSlide = function (sid, container,img,text) {
         var sl = { sid:sid, container:container,img:img, text:text};
   		// add element to slide, assign id which is the index
   		this.Slides[sl.container.slideID =  this.Slides.length] = sl;
   		this.NumSlides ++;
   		return sl;
};

wweSlideShow.prototype.setAdvance = function (func){
   		this.changer = func;

}

wweSlideShow.prototype.gotoSlide = function(slide) { // expects an index
        this.stop(); // stop the slide show if it running.
        if (slide < this.NumSlides ){
        	this.LastSlide = this.CurrentSlide;
        	this.CurrentSlide = slide;
        }
   	  this.changer(); /*??? why did I put this outside?*/
}

wweSlideShow.prototype.advance = function () {
         var tr = this;
   		var nextfunc = function(){
   			tr.LastSlide = tr.CurrentSlide;
	   		tr.CurrentSlide++;
				tr.CurrentSlide %= tr.Slides.length;
				if (tr.playing){
 					tr.changer();
   		    	tr.advance();
   		    }
   		}

   		setTimeout(nextfunc,tr.imPauseMS);


};

   /* For debugging only */
wweSlideShow.prototype.PrintSlides = function (Alert){
        var nl = Alert ? '\n' : '<br>';
   	    var debug = 'Title of Slide Show [' + this.title + ']'+nl;
   	    debug += 'Contains [' + this.Slides.length + '] slides'+nl;
   		debug += 'Playing is [' + this.isPlaying() + '] and speed is ['+this.imPauseMS+'ms], current is '+this.CurrentSlide+nl;
       for (var i in this.Slides){
			debug += '  Slide #'+i+' in ['+this.container+'] src='+this.Slides[i].img + ' and caption [' + this.Slides[i].text+']'+nl;
       }
       if (Alert){
         window.alert(debug);
       } else {
         document.write(debug);
       }
}


function findSlideImages () {
	var sb = document.getElementById('wweSlideBody');
	var ImDescripEl = document.getElementById('wweItemText');

/*	var SlideCtl = document.getElementById('wweSlideCtlPlay');
	var OrigSlideCtlText;

	if (SlideCtl){
		OrigSlideCtlText = SlideCtl.innerHTML;
	}
*/
	//slideImages = new Array();
	if (sb){
		/* We have a gallery, in theory */
		slideShow = new wweSlideShow('Gallery');
		slideShow.setSpeed(slideShowSleepMS)
		/* display callback */
		var func = function (){
                        //slideShow.currentSlide().container.className = 'wweSlideDiv';

                        var current = slideShow.currentSlide();
                        var s = slideShow.allSlides();
                        for (var i in s){
                        	s[i].container.className = s[i] != current ? 'wweSlideDiv' :'wweSlideDivHL';
                        }

                        BrowserLinkClick(current.img);

								if (ImDescripEl){
							    ImDescripEl.innerHTML = current.text;
								}
						};

		slideShow.setAdvance(func); /* Register it */
		wweMainImageWindowLink = document.getElementById('wweItemImagelink');
		var slideDivs = getElementsByClassName(sb, "div", "wweSlideDiv"); /* get the actual slides */
		for (var i in slideDivs){
			/* debugtxt += 'adding events to ['+slideDivs[i].id+']' + '\n';*/
			var im = getElementsByClassName(slideDivs[i], "img", "wweSlide")[0]; /* look for the image in the container */
			if (im){
				/* we found it, add it to the collection */
				var slideref = slideShow.addSlide(slideDivs[i].id,slideDivs[i],im,im.alt);
				/* set the mouse over */
				slideref.container.onmouseover = function(){
													slideShow.gotoSlide(this.slideID);
													return false;
				};
				//window.alert(typeof(document.getElementById('wweItemImagelink')));
//              if (wweMainImageWindowLink){
                  /* FF3 or Javascript bug? This isn't returning true.*/
					slideref.container.onclick = function(){
					                                BrowserLinkClick(wweMainImageWindowLink);
												};




			}
			/* else none found in container */
		}

	}
	if (slideShow && slideShow.slideCount()){
		slideShow.gotoSlide(0);
	}
	//slideShow.PrintSlides(1);
}

/******************************************/
/* END SLIDESHOW FUNCTIONS */
/******************************************/

/******************************************/
/* START PRODUCT SPEC FUNCTIONS */
/******************************************/
/******************************************/
function specs_bound_height (spec){
    if (spec.offsetHeight <= SpecDivMinHeight ){
       /* too small */
       spec.style.height = SpecDivMinHeight+'px';
    }
    else if (spec.offsetHeight > SpecDivMaxHeight ) {
       /* too big */
       spec.style.height = SpecDivMaxHeight+'px';
       spec.style.overflow = 'auto'
    }
    /* update ranges for equalizing */
    if ( spec.offsetHeight > maxSpecDivHeightFound){
        maxSpecDivHeightFound = spec.offsetHeight;
    }
    if ( spec.offsetHeight < minSpecDivHeightFound){
        minSpecDivHeightFound = spec.offsetHeight;
    }


}
/******************************************/
function init_specs (sid) {
    /*!!!needs to be called after the spec table!!!*/
    var spec = document.getElementById(sid);
    if (spec){
        var children = spec.childNodes;
        if (!children){
            return;
        }

        for (var i = 0; i < children.length; i++){
            if (children[i].tagName == 'DIV'){
                FoundSpecs.push(children[i]);

                specs_bound_height(children[i]); /* Check the height and fiddle if needed */

                var h = children[i].offsetHeight;

                if (selectedSpecDiv){
                    children[i].style.display = 'none'; // hide non selected
                }else {
                    selectedSpecDiv = children[i];
                }
            }
            else if (children[i].tagName == 'UL'){
                var headers = children[i].childNodes;
                for (x in headers){
                    if (headers[x].tagName == 'LI'){
                        FoundSpecsHeaders.push(headers[x]);
                        // anchor is stripped off in wweinit
                    }
                }
            }
        }


        if (maxSpecDivHeightFound - minSpecDivHeightFound < maxSpecDivHeightDiff){
            /* close enough, equalize ehights */
            for (var i = 0; i < FoundSpecs.length; i++){
                FoundSpecs[i].style.height = maxSpecDivHeightFound+'px';
            }
        }

        /* set the first to highlight */
        FoundSpecsHeaders[0].className='hlProductSpec';
        for (var i in FoundSpecs){
            /* add ref to header to div, maybe bad form */
            FoundSpecs[i].wweSpecHead = FoundSpecsHeaders[i];
        }
    }
    return;
}

/******************************************/
function highlight_spec (spec) {
    var hlDiv = document.getElementById(spec);
    if (selectedSpecDiv && (selectedSpecDiv == hlDiv)){
      return;
    }
    hlDiv.style.display = 'block';
    hlDiv.wweSpecHead.className='hlProductSpec';
    selectedSpecDiv.style.display = 'none';
    selectedSpecDiv.wweSpecHead.className = '';
    selectedSpecDiv = hlDiv;

}
/******************************************/
/* END PRODUCT SPEC FUNCTIONS */
/******************************************/

/******************************************/
/* START GENERIC FUNCTIONS */
/******************************************/
//wwepopUrl

//var popLoadUrl = 'popitem.html'
var popImLoadingIm;
//var PopStatus;


function changeIm(el, imurl, doloaded ){
		var PopIm  = new Image();
		PopIm.onerror = function() { window.alert("Error loading Image!") };
		if (doloaded){
			PopIm.onload = doloaded;
		}
	   el.src=PopIm.src;
}


function wwepopwin(imurl,title,x,y,caption){
	if (slideShow && slideShow.isPlaying){
	  slideShow.stop(); // turn off slide show
	}

	if (wweImWin) {
	  wweImWin.close();
	}

   caption = caption ?  caption : "Click image to close";

//<div><img src="http://us.st12.yimg.com/us.st.yimg.com/I/leeland_2029_213297580" id="popim"/></div>
//<span id="PopImText">Click to Close</span>


   if (wweImWinOpen > 0){
   	return falst;
   }

	wweImWin = window.open ('','wwepopwin','width='+x+',height='+y+',resizable=1');


	var d = wweImWin.document;
	if (wwepopimCSS){
		d.write ('<link rel="stylesheet" type="text/css" href="', wwepopimCSS, '" />');
	}

	d.write( "<html><head><title>" ,
					title ,
				'</title>',
				(wwepopimCSS ? '<link rel="stylesheet" type="text/css" href="'+wwepopimCSS+ '" />' : ''),
					'</head><body id="mbody" onclick="window.close();" onload="opener.wweImWinOpen=1;" style="background-color:black" bgcolor="#000000">'
				);
  	d.write( '<div>','<img id="popimg" src="','none.gif" width=1 height="1">' ,'</div>','<span id="PopImText">', caption, '</span>',"</body></html>\n"  );
	d.close();

	var PopIm  = new Image();

	PopIm.onerror = function() { window.alert("Error loading Image!") };
   var maxImWaitMS = 3000;
   var ploaderWait = 0;
	var ploader = function(){
		 //		 window.alert('status is '+wweImWin.wwepopwinstatus);

		 if (!wweImWinOpen) {
		      if (ploaderWait < maxImWaitMS){
		 			setTimeout(ploader,250);
		 			ploaderWait+=250;
		 		}else {
		 		   window.alert(wweImWinOpen);
		 			window.alert('Error loading image!');
		 		}
		 		return;
		 }
       wweImWinOpen = 0;
       var imdiv  = d.getElementById('PopDiv');
       var im = d.getElementById('popimg');
       var capDiv = d.getElementById('PopImText');
       if (caption){
       	d.getElementById('PopImText').style.visibility='visible';
       }

       var iw;
       var ih;
       var capheight = caption ? capDiv.style.height : 0;
       if (d.body.clientWidth){
	       iw = d.body.clientWidth;
	       ih = d.body.clientHeight;
	   }else{
	       iw = d.innerWidth = im.width;
	       ih = d.innerHeight = im.height;
	   }

	   im.src=PopIm.src;

 	   im.width = PopIm.width;
		im.height=PopIm.height;

	   wweImWin.resizeBy(  im.width - iw, im.height -ih + capheight );
	   wweImWin.focus();
	   d.close();


    }


    PopIm.onload = ploader;
    PopIm.src = imurl;

}
/******************************************/


/******************************************/
function wweinit(){
    /* Generic init called onload, adds popup image enlargments for capable browsers and other init */


    var links = document.links;
    for (var i = 0; i < links.length; i++){
        if (links[i].className == 'imgzoomable'){
			var zoomtext = document.createTextNode("Click to Enlarge");
            //var spantext = document.createElement("span");
            //spantext.class = "jEnlarge";
            //spantext.appendChild(zoomtext);
            //spantext.innerHTML  = '<span style="text-decoration:underline; clear:left;">Click to Enlarge</span>';

            var linebrk = document.createElement("br");
            links[i].appendChild(linebrk);
            links[i].appendChild(zoomtext);
            //links[i].appendChild(spantext);
        }else if (links[i].className =='wweLinkScrub'){
            if (specTargName){
                links[i].href = specTargName;
            }else{
                links[i].href = '';
            }
        }

    }



    /* Restore hidden script dependant elements */
    var els = getElementsByClassName(document, "*", "scriptOnly");
    for (var i = 0; i < els.length; i++){
        els[i].style.visibility="visible";
    }

    if (window.wweImQue){
		preloader(wweImQue);
	}
}



function preloader (imurls){

    var preIm = new Image();
    var i = 0;
    var getter = function () {
        if (i < imurls.length){
        	window.status = 'preloading '+ i+' =>' + imurls[i];
        	preIm.onload = getter;
        	preIm.src=imurls[i++];
        	//setTimeout(getter,500);
        }
        window.status = 'preloading finished';
    };
    setTimeout(getter,1000);
}


/******************************************/
/* CONTENTS SORTING                       */
/******************************************/
function wwe_contents_sort(a, b){
    /* Sorter Function for contents */
    if (sort_numeric){
        if (sort_direction){
            return a.getAttribute(sort_attrib) - b.getAttribute(sort_attrib);
        } else{
            return b.getAttribute(sort_attrib) - a.getAttribute(sort_attrib);
        }
    }else if(sort_direction){
        if (a.getAttribute(sort_attrib).toLowerCase() > b.getAttribute(sort_attrib).toLowerCase()){
            return (-1);
        }
        if (a.getAttribute(sort_attrib).toLowerCase() < b.getAttribute(sort_attrib).toLowerCase()){
            return (1)
        }
        return 0;
    }else{
        if (a.getAttribute(sort_attrib).toLowerCase() < b.getAttribute(sort_attrib).toLowerCase()){
            return (-1);
        }
        if (a.getAttribute(sort_attrib).toLowerCase() > b.getAttribute(sort_attrib).toLowerCase()){
            return (1)
        }
        return 0;
    }
}

/******************************************/
/* Function for sorting contents          */
/******************************************/
function sortcontents(tid,sortT,attrib,numeric){
    sort_numeric = numeric;
    var myTable = document.getElementById(tid);
    if (myTable.getAttribute('data-sorted-by') == attrib ){
        if (sort_direction){
            sort_direction = 0;
        }else{
            sort_direction = 1;
        }
    }else {
        sort_direction = sortT;
    }

    var myCells = new Array();
    var myRows = myTable.rows;
    var foundCells = myRows[0].cells.length;
    for (var i = 0; i < myRows.length; i++) {
        for (var g = 0; g < myRows[i].cells.length; g++){
            myCells.push( myRows[i].cells[g].cloneNode(1));
        }
    }

    sort_attrib = attrib;

    myCells.sort(wwe_contents_sort);
    for (var i = 0; i < myRows.length; i++) {
        for (var g = 0; g < myRows[i].cells.length; g++){
            myRows[i].replaceChild(myCells[(i * foundCells)+g], myRows[i].cells[g] )
        }
    }
    myTable.setAttribute('data-sorted-by',attrib);
}

//-->

