if(!window.jQuery){throw("jQuery must be referenced before using the 'onImagesLoad' plugin.");}



/*
 * jQuery 'onImagesLoaded' plugin v1.1.0
 * Fires callback functions when images have loaded within a particular selector.
 *
 * Copyright (c) Cirkuit Networks, Inc. (http://www.cirkuit.net), 2008.
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * For documentation and usage, visit "http://includes.cirkuit.net/js/jquery/plugins/onImagesLoad/1.1/documentation/"
 */
(function($){
    $.fn.onImagesLoad = function(options){
        var self = this;
        self.opts = $.extend({}, $.fn.onImagesLoad.defaults, options);

        self.bindEvents = function($imgs, container, callback){
            if ($imgs.length === 0){ //no images were in selection. callback based on options
                if (self.opts.callbackIfNoImagesExist && callback){ callback(container); }
            }
            else {
                var loadedImages = [];
                if (!$imgs.jquery){ $imgs = $($imgs); }
                $imgs.each(function(i, val){
                    $(this).bind('load', function(){
                        if (jQuery.inArray(i, loadedImages) < 0){ //don't double count images
                            loadedImages.push(i); //keep a record of images we've seen
                            if (loadedImages.length == $imgs.length){
                                if (callback){ callback(container); }
                            }
                        }
                    }).each(function(){
                        if (this.complete || this.complete === undefined){ this.src = this.src; } //needed for potential cached images
                    });
                });
            }
        };

        var imgAry = []; //only used if self.opts.selectorCallback exists
        self.each(function(){
            if (self.opts.itemCallback){
                var $imgs;
                if (this.tagName == "IMG"){ $imgs = this; } //is an image
                else { $imgs = $('img', this); } //contains image(s)
                self.bindEvents($imgs, this, self.opts.itemCallback);
            }
            if (self.opts.selectorCallback){
                if (this.tagName == "IMG"){ imgAry.push(this); } //is an image
                else { //contains image(s)
                    $('img', this).each(function(){ imgAry.push(this); });
                }
            }
        });
        if (self.opts.selectorCallback){ self.bindEvents(imgAry, this, self.opts.selectorCallback); }

        return self.each(function(){}); //dont break the chain
    };

	//DEFAULT OPTOINS
    $.fn.onImagesLoad.defaults = {
        selectorCallback: null,        //the function to invoke when all images that $(yourSelector) encapsultaes have loaded (invoked only once per selector. see documentation)
        itemCallback: null,            //the function to invoke when each item that $(yourSelector) encapsultaes has loaded (invoked one or more times depending on selector. see documentation)
        callbackIfNoImagesExist: false //if true, the callbacks will be invoked even if no images exist within $(yourSelector).
                                       //if false, the callbacks will not be invoked if no images exist within $(yourSelector).
    };




 

        
        
        
        
        
        
        
        
        
        
        
        
$.fn.jCarouselLite = function(o) {
    o = $.extend({
        btnPrev: null,
        btnNext: null,
        btnGo: null,
        mouseWheel: false,
        auto: null,

        speed: 200,
        easing: null,

        vertical: false,
        circular: true,
        visible: 3,
        start: 0,
        scroll: 1,

        beforeStart: null,
        afterEnd: null
    }, o || {});

    return this.each(function() {                           // Returns the element collection. Chainable.

        var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
        var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

        if(o.circular) {
            ul.prepend(tLi.slice(tl-v-1+1).clone())
              .append(tLi.slice(0,v).clone());
            o.start += v;
        }

        var li = $("li", ul), itemLength = li.size(), curr = o.start;
        div.css("visibility", "visible");

        li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
        ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
        div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});

        var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
        var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
        var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

        li.css({width: li.width(), height: li.height()});
        ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));

        div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images

        if(o.btnPrev)
            $(o.btnPrev).click(function() {
                return go(curr-o.scroll);
            });

        if(o.btnNext)
            $(o.btnNext).click(function() {
                return go(curr+o.scroll);
            });

        if(o.btnGo)
            $.each(o.btnGo, function(i, val) {
                $(val).click(function() {
                    return go(o.circular ? o.visible+i : i);
                });
            });

        if(o.mouseWheel && div.mousewheel)
            div.mousewheel(function(e, d) {
                return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
            });

        if(o.auto)
            setInterval(function() {
                go(curr+o.scroll);
            }, o.auto+o.speed);

        function vis() {
            return li.slice(curr).slice(0,v);
        };

        function go(to) {
            if(!running) {

                if(o.beforeStart)
                    o.beforeStart.call(this, vis());

                if(o.circular) {            // If circular we are in first or last, then goto the other end
                    if(to<=o.start-v-1) {           // If first, then goto last
                        ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                        curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
                    } else if(to>=itemLength-v+1) { // If last, then goto first
                        ul.css(animCss, -( (v) * liSize ) + "px" );
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                        curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
                    } else curr = to;
                } else {                    // If non-circular and to points to first or last, we just return.
                    if(to<0 || to>itemLength-v) return;
                    else curr = to;
                }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                running = true;

                ul.animate(
                    animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
                    function() {
                        if(o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );
                // Disable buttons when the carousel reaches the last/first, and enable when not
                if(!o.circular) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (curr-o.scroll<0 && o.btnPrev)
                        ||
                       (curr+o.scroll > itemLength-v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                }

            }
            return false;
        };
    });
};

function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
	if(!el[0]) return 150;
	return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
	if(!el[0]) return 150;
   return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};        
     




   	/*****************************************************/
    	/******************Nav rollovers**********************/
    	/*****************************************************/
        $.fn.cross = function (options) {
            return this.each(function (i) {
                // cache the copy of jQuery(this) - the start image
                var $$ = $(this);

                // get the target from the backgroundImage
                /*
                var target = $$.attr("src").split(".png").join("-over.png");
*/
                // nice long chain: wrap img element in span
                $$.wrap('<span style="position: relative;"></span>')
                    // change selector to parent - i.e. newly created span
                    .parent()
                    // prepend a new image inside the span
                   
                    // change the selector to the newly created image
                    .find(':first-child');
                  
        

                var text = $$.parent().parent().attr("title");
               
                $$.parent().parent().attr("title", '');
                $$.parent().prepend("<em></em>");
                $$.parent().find("em").text( text );

				$$.parent().find("em").css({opacity:0});
				$$.parent().find("em").css({"display":"block"});


                $$.hoverIntent(function () {

                	var tip = $$.parent().find("em");
                	tip.animate({opacity: 1, top: "-130"}, "slow");
                    $$.dequeue().animate({opacity: 0}, 250);
                }, function () {
                	 
                	var tip = $$.parent().find("em");
                	tip.animate({opacity: 0, top: "-100"}, "fast");
                    $$.dequeue().animate({opacity: 1}, 250);
                });
	
            });
        };







	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 200,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};







    $.fn.annotateImage = function(options) {
        ///	<summary>
        ///		Creates annotations on the given image.
        ///     Images are loaded from the "getUrl" propety passed into the options.
        ///	</summary>
        var opts = $.extend({}, $.fn.annotateImage.defaults, options);
        var image = this;

        this.image = this;
        this.mode = 'view';

        // Assign defaults
        this.getUrl = opts.getUrl;
        this.saveUrl = opts.saveUrl;
        this.menuUrl = opts.menuUrl;
        this.deleteUrl = opts.deleteUrl;
        this.cartUrl = opts.cartUrl;
        this.editable = opts.editable;
        this.useAjax = opts.useAjax;
        this.notes = opts.notes;
        


        // Add the canvas
        this.canvas = $('<div class="image-annotate-canvas"><div class="image-annotate-view"></div><div class="image-annotate-edit"><div class="image-annotate-edit-area"></div></div></div>');
        this.canvas.children('.image-annotate-edit').hide();
        this.canvas.children('.image-annotate-view').hide();
        this.image.after(this.canvas);

        // Give the canvas and the container their size and background
        this.canvas.height(this.height());
        this.canvas.width(this.width());
        this.canvas.css('background-image', 'url("' + this.attr('src') + '")');
        this.canvas.children('.image-annotate-view, .image-annotate-edit').height(this.height());
        this.canvas.children('.image-annotate-view, .image-annotate-edit').width(this.width());

        // Add the behavior: hide/show the notes when hovering the picture
        this.canvas.hover(function() {
            if ($(this).children('.image-annotate-edit').css('display') == 'none') {
                $(this).children('.image-annotate-view').show();
            }
        }, function() {
            $(this).children('.image-annotate-view').hide();
        });

        this.canvas.children('.image-annotate-view').hover(function() {
            $(this).show();
        }, function() {
            $(this).hide();
        });

        // load the notes
        if (this.useAjax) {
            $.fn.annotateImage.ajaxLoad(this);
        } else {
            $.fn.annotateImage.load(this);
        }

        // Add the "Add a note" button
        if (this.editable) {
            this.button = $('<a class="image-annotate-add" id="image-annotate-add" href="#">Add Note</a>');
            this.buttoni = $('<a class="image-annotate-add" href="#">Add Note</a>');

            this.button.click(function() {
                $.fn.annotateImage.add(image);
            });
            
            if($('#controls').length > 0){
            	$('#controls').append(this.buttoni); //button for new in menu.
            	
            	$(".needs").live("click", function(){ //MENU LIST
            		//#label
            		//$(this).buttoni.attr("title", )
            		partno = $(this).children(':first').attr("title");
            		text = $(this).text();
            		image.attr("title", text);
            		image.attr("alt", partno);
            		//image.attr("longdesc", )
            		$.fn.annotateImage.add(image);
            		$('body').animate({scrollTop:0}, 'fast'); 
            	});
            }else{
            	this.canvas.after(this.button);
            }
        }

        // Hide the original
        this.hide();

        return this;
    };

    /**
    * Plugin Defaults
    **/
    $.fn.annotateImage.defaults = {
        getUrl: 'your-get.rails',
        saveUrl: 'your-save.rails',
        deleteUrl: 'your-delete.rails',
        cartUrl: '',
        editable: true,
        useAjax: true,
        notes: new Array()
    };

    $.fn.annotateImage.clear = function(image) {
        ///	<summary>
        ///		Clears all existing annotations from the image.
        ///	</summary>    
        for (var i = 0; i < image.notes.length; i++) {
            image.notes[image.notes[i]].destroy();
        }
        image.notes = new Array();
    };

    $.fn.annotateImage.ajaxLoad = function(image) {
        ///	<summary>
        ///		Loads the annotations from the "getUrl" property passed in on the
        ///     options object.
        ///	</summary>
        $.getJSON(image.getUrl + '&ticks=' + $.fn.annotateImage.getTicks(), function(data) {
            image.notes = data;
            
            $.fn.annotateImage.load(image);
        });
    };

    $.fn.annotateImage.load = function(image) {
        ///	<summary>
        ///		Loads the annotations from the notes property passed in on the
        ///     options object.
        ///	</summary>
    
        for (var i = 0; i < image.notes.length; i++) {
            image.notes[image.notes[i]] = new $.fn.annotateView(image, image.notes[i]);
            
        }
    };

    $.fn.annotateImage.getTicks = function() {
        ///	<summary>
        ///		Gets a count og the ticks for the current date.
        ///     This is used to ensure that URLs are always unique and not cached by the browser.
        ///	</summary>        
        var now = new Date();
        return now.getTime();
    };

    $.fn.annotateImage.add = function(image) {
        ///	<summary>
        ///		Adds a note to the image.
        ///	</summary>        
        if (image.mode == 'view') {
            image.mode = 'edit';
			
            // Create/prepare the editable note elements
            var editable = new $.fn.annotateEdit(image);

            $.fn.annotateImage.createSaveButton(editable, image);
            $.fn.annotateImage.createCancelButton(editable, image);
        }
    };

    $.fn.annotateImage.createSaveButton = function(editable, image, note) {
        ///	<summary>
        ///		Creates a Save button on the editable note.
        ///	</summary>
        var ok = $('<a class="image-annotate-edit-ok">OK</a>');

        ok.click(function() {
            var form = $('#image-annotate-edit-form form');
            var text = $('#image-annotate-text').val();
            var number = $('#image-annotate-number').val();
            $.fn.annotateImage.appendPosition(form, editable)
            image.mode = 'view';

            // Save via AJAX
            if (image.useAjax) {
                $.ajax({
                    url: image.saveUrl,
                    data: form.serialize(),
                    error: function(e) { alert("An error occured saving that note.") },
                    success: function(msg){
                    	$.ajax({
                    	 url: image.menuUrl,
                    	 dataType: "html",
                    	 success: function(data){
                    	 	//$("#btns").html("");
                    	 	//$('#btns').empty().remove();
                    	 	
                    	 	$("#btns").empty().html(data);
                    	 }
                    	
                    	 
                    	 //Being sent. When you get back, first load the parts in the menu, then when it, have this ajax call do an update.
                    	});
                    }
                    	//JDM update the listing in the menu.
                    
                     
                });
            }

            // Add to canvas
            if (note) {
                note.resetPosition(editable, text);
            } else {
                editable.note.editable = true;
                note = new $.fn.annotateView(image, editable.note)
                note.resetPosition(editable, text);
                image.notes.push(editable.note);
            }

            editable.destroy();
        });
        editable.form.append(ok);
    };

    $.fn.annotateImage.createCancelButton = function(editable, image) {
        ///	<summary>
        ///		Creates a Cancel button on the editable note.
        ///	</summary>
        var cancel = $('<a class="image-annotate-edit-close">Cancel</a>');
        cancel.click(function() {
            editable.destroy();
            image.mode = 'view';
        });
        editable.form.append(cancel);
    };

    $.fn.annotateImage.saveAsHtml = function(image, target) {
        var element = $(target);
        var html = "";
        for (var i = 0; i < image.notes.length; i++) {
            html += $.fn.annotateImage.createHiddenField("text_" + i, image.notes[i].text);
            html += $.fn.annotateImage.createHiddenField("top_" + i, image.notes[i].top);
            html += $.fn.annotateImage.createHiddenField("left_" + i, image.notes[i].left);
            html += $.fn.annotateImage.createHiddenField("height_" + i, image.notes[i].height);
            html += $.fn.annotateImage.createHiddenField("width_" + i, image.notes[i].width);
        }
        element.html(html);
    };

    $.fn.annotateImage.createHiddenField = function(name, value) {
        return '&lt;input type="hidden" name="' + name + '" value="' + value + '" /&gt;<br />';
    };

    $.fn.annotateEdit = function(image, note) {
        ///	<summary>
        ///		Defines an editable annotation area.
        ///	</summary>
        
        this.image = image;

        if (note) {
            this.note = note;
        } else {
            var newNote = new Object();
            newNote.id = "new";
            newNote.top = 30;
            newNote.left = 30;
            newNote.width = 30;
            newNote.height = 30;
            newNote.text = "";
            newNote.number="";
            this.note = newNote;
        }

        // Set area
        var area = image.canvas.children('.image-annotate-edit').children('.image-annotate-edit-area');
        this.area = area;
        this.area.css('height', this.note.height + 'px');
        this.area.css('width', this.note.width + 'px');
        this.area.css('left', this.note.left + 'px');
        this.area.css('top', this.note.top + 'px');

        // Show the edition canvas and hide the view canvas
        image.canvas.children('.image-annotate-view').hide();
        image.canvas.children('.image-annotate-edit').show();

        if(!this.note.text && !this.note.number) this.note.text = this.image.attr("title");
        if(!this.note.number) this.note.number = this.image.attr("alt");
        
        
        // Add the note (which we'll load with the form afterwards)
        var url = window.location
        var form = $('<div id="image-annotate-edit-form"><a class="override" href="/catalog/crop/part/'+this.note.id+'/back/'+escape(location.href)+'">Image</a><br /><form><textarea id="image-annotate-text" name="text" rows="3" cols="30">' + this.note.text + '</textarea><br />Part Number<input type="text" id="image-annotate-number" name="number" value="' + this.note.number+'" /><br /></form></div>');
        this.form = form;

        $('body').append(this.form);
        this.form.css('left', this.area.offset().left + 'px');
        this.form.css('top', (parseInt(this.area.offset().top) + parseInt(this.area.height()) + 2) + 'px');

        // Set the area as a draggable/resizable element contained in the image canvas.
        // Would be better to use the containment option for resizable but buggy
        area.resizable({
            handles: 'all',
            resize: function(e, ui) {
                if (parseInt(area.position().top) + parseInt(area.height()) + 2 > parseInt(image.canvas.height())) {
                    area.height(parseInt(image.canvas.height()) - parseInt(area.position().top) - 2);
                }
                if (parseInt(area.position().left) + parseInt(area.width()) + 2 > parseInt(image.canvas.width())) {
                    area.width(parseInt(image.canvas.width()) - parseInt(area.position().left) - 2);
                }
                if (parseInt(area.position().top) < 0) {
                    area.height(parseInt(image.canvas.height())).css('top', 0);
                }
                if (parseInt(area.position().left) < 0) {
                    area.width(parseInt(image.canvas.width())).css('left', 0);
                }
                form.css('left', area.offset().left + 'px');
                form.css('top', (parseInt(area.offset().top) + parseInt(area.height()) + 2) + 'px');
            },
            stop: function(e, ui) {
                form.css('left', area.offset().left + 'px');
                form.css('top', (parseInt(area.offset().top) + parseInt(area.height()) + 2) + 'px');
            }
        })
        .draggable({
            containment: image.canvas,
            drag: function(e, ui) {
                form.css('left', area.offset().left + 'px');
                form.css('top', (parseInt(area.offset().top) + parseInt(area.height()) + 2) + 'px');
            },
            stop: function(e, ui) {
                form.css('left', area.offset().left + 'px');
                form.css('top', (parseInt(area.offset().top) + parseInt(area.height()) + 2) + 'px');
            }
        });
        return this;
    };

    $.fn.annotateEdit.prototype.destroy = function() {
        ///	<summary>
        ///		Destroys an editable annotation area.
        ///	</summary>        
        this.image.canvas.children('.image-annotate-edit').hide();
        this.area.resizable('destroy');
        this.area.draggable('destroy');
        this.area.css('height', '');
        this.area.css('width', '');
        this.area.css('left', '');
        this.area.css('top', '');
        this.form.remove();
    }

    $.fn.annotateView = function(image, note) {
        ///	<summary>
        ///		Defines a annotation area.
        ///	</summary>
        this.image = image;

        this.note = note;
		this.number = note.number;
        this.editable = (note.editable && image.editable);

        
		
        // Add the area
        this.area = $('<div id="p-'+this.number+'" class="image-annotate-area' + (this.editable ? ' image-annotate-area-editable' : '') + '">'+'<div></div></div>');
      
        image.canvas.children('.image-annotate-view').prepend(this.area);
        

        // Add the note
        this.form = $('<div class="image-annotate-note">' + note.text + '</div>');
        if(note.part_thumb)this.form.append('<br /><img src="/'+note.part_thumb+'">');
        
        this.cartform = $('<span id="'+note.number+'" class="add_part"></span>');
        
        
        
        this.form.hide();
        image.canvas.children('.image-annotate-view').append(this.form);
        this.form.children('span.actions').hide();

        // Set the position and size of the note
        this.setPosition();

        // Add the behavior: hide/display the note when hovering the area
        var annotation = this;
        this.area.hover(function() {
            annotation.show();
        }, function() {
            annotation.hide();
        });

        // Edit a note feature
        if (this.editable) {
            var form = this;
            this.area.click(function() {
                form.edit();
            });
        }
    };

    $.fn.annotateView.prototype.setPosition = function() {
        ///	<summary>
        ///		Sets the position of an annotation.
        ///	</summary>
        this.area.children('div').height((parseInt(this.note.height) - 2) + 'px');
        this.area.children('div').width((parseInt(this.note.width) - 2) + 'px');
        this.area.css('left', (this.note.left) + 'px');
        this.area.css('top', (this.note.top) + 'px');
        this.form.css('left', (this.note.left) + 'px');
        this.form.css('top', (parseInt(this.note.top) + parseInt(this.note.height) + 7) + 'px');
    };

    $.fn.annotateView.prototype.show = function() {
        ///	<summary>
        ///		Highlights the annotation
        ///	</summary>        
        this.form.fadeIn(250);
        var annotation = this;
        if (!this.editable) {
            this.area.addClass('image-annotate-area-hover');
			var thing = $(this.area).children(':first');
			var areadiv = $(this.area);
			$(thing).unbind();
			$(thing).one("click", function(event){
				 //event.stopPropagation();
				var part_no = $(areadiv).attr("id").split("p-").join("");
				window.location.replace(annotation.image.cartUrl+part_no+"/qty/1");			
			});
        
        } else {
            this.area.addClass('image-annotate-area-editable-hover');
        }
    };

    $.fn.annotateView.prototype.hide = function() {
        ///	<summary>
        ///		Removes the highlight from the annotation.
        ///	</summary>      
        this.form.fadeOut(250);
        this.area.removeClass('image-annotate-area-hover');
        this.area.removeClass('image-annotate-area-editable-hover');
    };

    $.fn.annotateView.prototype.destroy = function() {
        ///	<summary>
        ///		Destroys the annotation.
        ///	</summary>      
        this.area.remove();
        this.form.remove();
    }

    $.fn.annotateView.prototype.edit = function() {
        ///	<summary>
        ///		Edits the annotation.
        ///	</summary>      
        if (this.image.mode == 'view') {
            this.image.mode = 'edit';
            var annotation = this;

            // Create/prepare the editable note elements
            var editable = new $.fn.annotateEdit(this.image, this.note);

            $.fn.annotateImage.createSaveButton(editable, this.image, annotation);

            // Add the delete button
            var del = $('<a class="image-annotate-edit-delete">Delete</a>');
            del.click(function() {
                var form = $('#image-annotate-edit-form form');

                $.fn.annotateImage.appendPosition(form, editable)

                if (annotation.image.useAjax) {
                    $.ajax({
                    url: annotation.image.deleteUrl,
                        data: form.serialize(),
                        error: function(e) { alert("An error occured deleting that note.") },
                        success: function(e){ location.reload()  }
                    });
                }
                
                annotation.image.mode = 'view';
                editable.destroy();
                annotation.destroy();
            });
            editable.form.append(del);

            $.fn.annotateImage.createCancelButton(editable, this.image);
        }
    };

    $.fn.annotateImage.appendPosition = function(form, editable) {
        ///	<summary>
        ///		Appends the annotations coordinates to the given form that is posted to the server.
        ///	</summary>
        var areaFields = $('<input type="hidden" value="' + editable.area.height() + '" name="height"/>' +
                           '<input type="hidden" value="' + editable.area.width() + '" name="width"/>' +
                           '<input type="hidden" value="' + editable.area.position().top + '" name="top"/>' +
                           '<input type="hidden" value="' + editable.area.position().left + '" name="left"/>' +
                           '<input type="hidden" value="' + editable.note.id + '" name="id"/>');
        form.append(areaFields);
    }

    $.fn.annotateView.prototype.resetPosition = function(editable, text) {
        ///	<summary>
        ///		Sets the position of an annotation.
        ///	</summary>
        this.form.html(text);

        // Resize
        this.area.children('div').height(editable.area.height() + 'px');
        this.area.children('div').width((editable.area.width() - 2) + 'px');
        this.area.css('left', (editable.area.position().left) + 'px');
        this.area.css('top', (editable.area.position().top) + 'px');
        this.form.css('left', (editable.area.position().left) + 'px');
        this.form.css('top', (parseInt(editable.area.position().top) + parseInt(editable.area.height()) + 7) + 'px');

        // Save new position to note
        this.note.top = editable.area.position().top;
        this.note.left = editable.area.position().left;
        this.note.height = editable.area.height();
        this.note.width = editable.area.width();
        this.note.text = text;
        this.note.id = editable.note.id;
        this.editable = true;
    };


	
$.fn.collapsor = function(settings) { 
	$.fn.collapsor.defaults.closeOthers = true;
	$.fn.collapsor.defaults.speed = 250;
	// override default settings
	settings = $.extend({}, $.fn.collapsor.defaults, settings);
	var triggers = this;
	// for each element
	return this.each(function() {
		
		// occult the collapsing elements
		$(this).find('+ ' + settings.sublevelElement).hide();
		//show the opened
		if($(this).hasClass(settings.openClass)){
			$(this).find('+ ' + settings.sublevelElement).show();
			
		}
		// event handling
	  $(this).click(function() {

	  	
	  
			// if the new active have sublevels && they are not the closed type (jmh addition)
			if ($(this).next().is(settings.sublevelElement) && !$(this).is('.closed')){
				
				
				//if($(this).find('+ ' + settings.sublevelElement).is(':hidden') && $(this).is('.open')){
				
				
				// blur and add the open class to the clicked
				$(this).blur().toggleClass(settings.openClass);
				var img = $(this).find("img");
						
				if(img.attr("src") == settings.arrowr) $(img).attr("src",settings.arrowd)
				else $(img).attr("src",settings.arrowr);
				
				
				
				// close others
				if (settings.closeOthers == true) {
					
				  var other = $(this).parent().parent().children().find('.'+settings.openClass).not(this).find("img");
				  $(other).attr("src",settings.arrowr);
				  $(this).parent().parent().children().find('.'+settings.openClass).not(this).removeClass(settings.openClass).next().animate({height:'toggle', opacity:'toggle'}, settings.speed, settings.easing);
				  
				}
				
				
				
				// toggle the clicked
				$(this).next().animate({height:'toggle', opacity:'toggle'}, settings.speed, settings.easing);
				//}
				return false;
			}
	   });
	});
};
// default settings
$.fn.collapsor.defaults = {
	openClass:'open',
	sublevelElement: 'ul',
	closeOthers: true,
	speed: 500,
	easing: 'swing',
	arrowr: '/catalog/assets/images/arrowr.png',
	arrowd: '/catalog/assets/images/arrowd.png'
	
};

        
        
})(jQuery);






/***************************************************/
/**************Tooltips for nav*********************/
/***************************************************/

this.tooltip = function(){
		//Menu Tooltip configs
		xOffset = 50;
		yOffset = 20;

		$("a.hoverthumb").hoverIntent(function(e){

		this.t = this.title;
		this.title = ""; //remove so we dont get the default tooltip, put back on mouseout.
		$("body").append("<p id='thumbview'></p>");
		//$('#end').append(this.t + '<br />'); //Add the title to the tooltip

		//Setup the style for the tooltip
		$("#thumbview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.css("text-align","left").css("max-width", "400px")
			.fadeIn("fast");

			span = $(this).find("span");
			simg = $(this).find("img");

				$('#thumbview').append($(span).html());

		},
	function(){

		this.title =  this.t;
		$("#thumbview").remove();
    });

	$("a.hoverthumb").mousemove(function(e){
		$("#thumbview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});


	/************************************************/
	/*****************Left Nav***********************/
	/************************************************/
	$("a.end").hoverIntent(function(e){	//Hover for the deepest menu items
		this.t = this.title;
		this.title = ""; //remove so we dont get the default tooltip, put back on mouseout.
		this.model = $(this).html(); //Get the model
		$("body").append('<p id="end"></p>');
		$('#end').empty();
		//Setup the style for the tooltip
		$("#end").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px").css("text-align","center").fadeIn("fast");
			//Setup the vars needed
			li = $(this).parent();
			span = $(li).find("span");
			simg = $(span).find("img");

			//Fadeout the other items.
			$(li).siblings().fadeTo("fast", 0.3); // Fade other items to 30%
			$(li).parent().siblings().fadeTo("fast", 0.3); // Fade other items to 30%
			//$(li).parent().parent().siblings().fadeTo("fast", 0.3); // Fade other items to 30%



			//Check if it has an image, if it does, just get it from the span next to it to save load time.
			if($(simg).length > 0){
				$('#end').append($(span).html());
			}else{ //No image, so add image to the span
				if($(this).attr("rel")){
					img_src = urlencode($(this).attr("rel")); //Remove junk whitespace
					thumb = '<img src="'+ img_src +'" alt="Loading Image" />';

					$(span).empty();
					$(span).append(this.model +"<br />");
					$(span).append(thumb); //add the thumb image to the span so next time it doesnt load
					$(span).append("<br />"+this.t );


					$("#end").empty();
					$("#end").append(this.model +"<br />");
					$("#end").append(thumb); //add the thumb image to the span so next time it doesnt load
					$("#end").append("<br />"+this.t );

				}
			}

			$(this).parent().siblings().each(function(x, item){
				m = $(item).find("a");
				ispan = $(item).find("span");
				isimg = $(ispan).find("img");
				if($(isimg).length < 1){
					isrc = urlencode($(m).attr("rel"));
					ithumb = '<img src="'+ isrc +'" alt="Loading Image" />';
					$(ispan).empty();
					$(ispan).append(m.text()+'<br />');
					$(ispan).append(ithumb); //add the thumb image to the span so next time it doesnt load
					$(ispan).append('<br />'+m.attr("title"))

				}
			});



    },
	function(){
		this.title =  this.t;
		$(li).siblings().fadeTo("fast", 1);
		$(li).parent().siblings().fadeTo("fast", 1);
		$(li).parent().parent().siblings().fadeTo("fast", 1);


		$("#end").remove();

    });
	$("a.end").mousemove(function(e){
		$("#end")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});

	if($("#left span")) $("#left").hoverIntent(function(e){

		this.t = this.title;
		this.title = ""; //remove so we dont get the default tooltip, put back on mouseout.
		$("body").append("<p id='thumbview'></p>");
		//$('#end').append(this.t + '<br />'); //Add the title to the tooltip

		//Setup the style for the tooltip
		$("#thumbview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.css("text-align","left").css("max-width", "400px")
			.fadeIn("fast");

		$('#thumbview').append($("#left span span").html());

		},
	function(){

		this.title =  this.t;
		$("#thumbview").remove();
    });

    if($('#left')) $('#left').click(function(e){
    	document.location= "/"+this.t;
    });

	if($('#left')) $("#left").mousemove(function(e){
		$("#thumbview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});

	if($("#right span")) $("#right").hoverIntent(function(e){

		this.t = this.title;
		this.title = ""; //remove so we dont get the default tooltip, put back on mouseout.
		$("body").append("<p id='thumbview'></p>");
		//$('#end').append(this.t + '<br />'); //Add the title to the tooltip

		//Setup the style for the tooltip
		$("#thumbview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.css("text-align","left").css("max-width", "400px")
			.fadeIn("fast");

		$('#thumbview').append($("#right span span").html());

		},
	function(){

		this.title =  this.t;
		$("#thumbview").remove();
    });


    if($('#right')) $('#right').click(function(e){
    	document.location= "/"+this.t;
    });

	if($('#right')) $("#right").mousemove(function(e){
		$("#thumbview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};

function urlencode(str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

}



var SEARCH_BOX_DEFAULT_TEXT = 'Search the site';
var AJAX_PENDING_TIMER;
var CURRENT_PAGE = 1;
var CURRENT_LIMIT = 3;

function search_init(){

	var sTextBox   = $("#edit-search-theme-form-1");

	sTextBox.focus(function() {
		if(this.value == SEARCH_BOX_DEFAULT_TEXT) {
			this.value = '';
		}
	});
	sTextBox.blur(function() {
		if(this.value == '') {
			this.value = SEARCH_BOX_DEFAULT_TEXT;
		}
	});
	sTextBox.blur();
}