$(window).load(function()
{
    $('[rel^=lightbox]').boxit(this);
});

(function($)
{
    $.fn.boxit = function()
    {
        //Default settings
        var overlayOpacity = 0.8;       //Overlay opacity 0.0 - 1.0
        var toolTipOpacity = 0.9;       //Opacity of tooltip 0.0 - 1.0 matches frame png opacity!!
        var toolTipWidth = 240;
        var toolTipImageWidth = 100;    //Width of image to display in tooltip
        var minimumSize = 200;          //Set minimum size to display boxit content
        var animationSpeed = 300;
        var loop = 1;
        
        var allMatches = this;
        var totalMatches = 0;
        var itemArray = [];
        var activeItem = 0;
        var addDesc = 0;
        var mouseX = 0;
        var mouseY = 0;
        var groupArray = [];
        var groupTotal = 0;
        var groupPosition = 0;
        var newLeft;
        var newTop;
        var newWidth;
        var newHeight;
        var startSizes = [];
        var snapChange = 1;
        var boxWidth = 0;
        var boxHeight = 0;
       // var position = 0;
        
        // HTML for overlay, containers and content
        var overlay = $('<div id="overlay"></div>'); // Dimming overlay
        var container = $('<div id="boxit"></div>'); // Window container
        var frame = $('<div id="tL">&nbsp;</div><div id="t">&nbsp;</div><div id="tR">&nbsp;</div><div id="l">&nbsp;</div><div id="r">&nbsp;</div><div id="bL">&nbsp;</div><div id="b">&nbsp;</div><div id="bR">&nbsp;</div>');
        var contentHolder = $('<div id="outer"></div><div id="inner"></div>'); // inner container for content
        var next = $('<a href="#" id="next" class="button"><img src="/i/lightbox/images/next.gif" width="63" height="32" alt="Next &raquo;" /></a>'); // next button
        var previous = $('<a href="#" id="previous" class="button"><img src="/i/lightbox/images/prev.gif" width="63" height="32" alt="&laquo; Previous" /></a>'); // previous button

        // an image
        var image = $('<img src="" alt="" id="boxImage" />');
        // an iframe
        var iframe =  $('<iframe src="#" width="200" height="200" frameborder="no" id="external"></iframe>');
        // an tooltip
        var tooltip = $('<p id="tip_desc"><img src="" alt="" id="tip_image" /><span></span><br /><br /></p><a href="#" id="tip_link">Go to product page</a>');
        // description container set to 40px high with css
        var desc = $('<p id="desc"></p>');
        // close button link image
        var close = $('<a href="#" id="close"><img src="/i/lightbox/images/close.gif" width="66" height="22" alt="close" /></a>');
        // close button link image
        var xclose = $('<a href="#" id="xclose"><img src="/i/lightbox/images/x.gif" width="12" height="12" alt="close" /></a>');

        // Deal with Window/Keyboard events
		$(window).scroll(function(){_reposition();});
		$(window).resize(function(){snapChange = 1; _scale(); _reposition();});
		
		
		var _browser = {
          version: function() {
            var version = 999; // we assume a sane browser
            if (navigator.appVersion.indexOf("MSIE") != -1)
            {
              // bah, IE again, lets downgrade version number
              version = parseFloat(navigator.appVersion.split("MSIE")[1]);
            }
            return version;
          }
        };

        function _init(e) {
            //alert ('init');
            //Get mouse position and make a number!
            mouseX = e.pageX*1;
            mouseY = e.pageY*1;
            _start($(this),allMatches);
            return false; // Stop browser using link
        }

        function _start(clicked,allMatches) {
            //alert ('start');
            activeItem = 0;
            totalMatches = allMatches.length
            itemArray = [];
            
            for (var i = 0; i < totalMatches; i++)
            {
                var currentItemRel = allMatches[i].getAttribute('rel').split("|");
                var currentItemGroupName = currentItemRel[1];
                var fileUrl = allMatches[i].getAttribute('href');
                itemArray.push([fileUrl, allMatches[i].getAttribute('title'), allMatches[i].getAttribute('rel'), i, currentItemGroupName, _getFileType(allMatches[i].getAttribute('rel'))])
            }
           // alert(itemArray);
            activeItem = $('[rel^=lightbox]').index(clicked);
      			if(activeItem==-1)
      			{
      			 
      				activeItem=$('[rel^=survey]').index(clicked);
      				//itemArray[activeItem][5]="survey";
      				
      			}
            _buildBox(); //Put the boxes on the page
            _setContent(); //Set the content to display
        }

        function _buildBox() {
            //alert ('buildbox');
            //Add overlay and container to body of page
            if (!$('#boxit').length)
            {
                $("body").append(overlay);
                $("body").append(container);
                var overlayHeight = $(document).height();
                var overlayWidth = $(document).width();
                $("#overlay").css({height: overlayHeight, width: overlayWidth, opacity: overlayOpacity});
                $("#boxit").css({filter: ''}).append(contentHolder);
                $("#boxit").append(frame);
                // If browser can't show png's use gif corners and add a light border
                if (_browser.version() < 7)
                {
                    $("#tL, #tR, #bL, #bR").css('background-image', 'url(/i/lightbox/images/corners.gif)');
                    $("#t").css({'background':'#fff', 'border-top':'1px solid #666'});
                    $("#b").css({'background':'#fff', 'border-bottom':'1px solid #666'});
                    $("#l").css({'background':'#fff', 'border-left':'1px solid #666'});
                    $("#r").css({'background':'#fff', 'border-right':'1px solid #666'});
                    $("#outer").css('background', '#fff');
                }
            }
        }

        function _showBox(hasOverlay) {
            //alert ('showbox');
            if (hasOverlay == 1)
            {
                $("#boxit, #outer").css({opacity: 1});
                $("select").css({visibility: 'hidden'});
                $("#NearestDepot").css({visibility: 'hidden'});
                $("#overlay").click(function(){
                    _closeBox(1);
                    return false;
                }).fadeIn(animationSpeed);
                $("#boxit, #inner").fadeIn(animationSpeed);
                $("#boxit").css({filter: ''});
            }
            else
            {
                $("#boxit, #inner").show();
                if (_browser.version() < 7)
                {
                    $("#outer").css({opacity: 1});
                }
                else
                {
                    $("#outer").css({opacity: toolTipOpacity});
                }
                $("#inner").css({opacity: 1});
                $("#inner").css({filter: ''});
				$("#tip_desc").width(toolTipWidth);
				//alert($('#tip_image').height());
				var innerHeight = ($("#tip_desc").height() > $('#tip_image').height())?($("#tip_desc").height() + $('#tip_title').height() + 45):($('#tip_image').height() + $('#tip_title').height() + 45);
				//alert(innerHeight);
                snapChange = 1;
                _resizeToFit(toolTipWidth,innerHeight); // Add a little bit extra due to image positioning
            }
        }

        function _closeBox(hasOverlay) {
            //alert ('closebox');
            if (hasOverlay == 1)
            {
                $("#overlay").fadeOut(animationSpeed);
                $("#previous, #next").remove();
                $("#boxit").hide();
                $("select").css({visibility: 'visible'});
                $("#NearestDepot").css({visibility: 'visible'});
            }
            else
            {
                $("#previous, #next").remove();
                $("#boxit").hide();
            }
			
			$("#quickTime").show();
        }

        function _setContent() {
            snapChange = 0;
            $("#quickTime").hide();
            // Decide what to show
            switch(_getFileType(itemArray[activeItem][2]))
            {
                case 'image':  //If item is an image put that in the box and center in window
                    // Preload the image before display
                    $("#outer").addClass("loading");
                    var imagePreloader = new Image();
                    imagePreloader.onload = function() {
                        $("#boxit").removeClass('tipStyle');
                        $("#inner").empty().append(image);
                        $('#boxImage').attr('src',itemArray[activeItem][0]).css({opacity: 0});
                        //_addDescription();
                        _isGroupMember();
                        //Position in center and resize to fit dimensions
                        startSizes = [imagePreloader.width,imagePreloader.height];
                        _scale();
                        _centerPosition();
                        _showBox(1);
                        $("#boxImage").animate({opacity: 1},animationSpeed);
                        imagePreloader.onload=function(){};
                    };
                    imagePreloader.src = itemArray[activeItem][0];
                break;
                
                case 'noscale':
                    $("#outer").addClass("loading");
                    reposition = 0;
                    // Preload the image before display
                    var imagePreloader = new Image();
                    imagePreloader.onload = function() {
                        $("#boxit").removeClass('tipStyle');
                        $("#inner").empty().append(image);
                        $('#boxImage').attr('src',itemArray[activeItem][0]).css({opacity: 0});
                        //_addDescription();
                        _isGroupMember();
                        //Position in center and resize to fit dimensions
                        startSizes = [imagePreloader.width,imagePreloader.height];
                        _resizeToFit(imagePreloader.width,imagePreloader.height);
                        snapChange = 1;
                        _scale();
                        _centerPosition();
                        _showBox(1);
                        $("#boxImage").animate({opacity: 1},animationSpeed);
                        imagePreloader.onload=function(){};
                    };
                    imagePreloader.src = itemArray[activeItem][0];
                break;
                
                case 'iframe':  //If item is an iframe put that in the box and center in window
                case 'survey':
                    $("#outer").addClass("loading");
                    $("#boxit").removeClass('tipStyle');
                    $("#inner").empty().append(iframe);
                    _isGroupMember();
                    _addDescription();
                    //Get size of iframe from Rel attribute
                    var iframeRel = itemArray[activeItem][2];
                    var iframeDimensions = iframeRel.match(/\d+/g); //Create array of dimensions from Rel attribute values
                    var iframeBoxWidth = parseInt(iframeDimensions[0],10);
                    var iframeBoxHeight = parseInt(iframeDimensions[1],10);
                    //Set size and content of iframe
                    $("#external").attr({width: iframeBoxWidth, height: iframeBoxHeight, src: itemArray[activeItem][0]});
                    //Position in center and resize to fit dimensions
                    startSizes = [iframeBoxWidth,iframeBoxHeight];
                    _scale();
                    _centerPosition();
                    _showBox(1);
                break;
                
                case 'pdf':  //If item is an iframe put that in the box and center in window
                    $("#outer").addClass("loading");
                    $("#boxit").removeClass('tipStyle');
                    $("#inner").empty().append(iframe);
                    _isGroupMember();
                    _addDescription();
                    //Get size of iframe from Rel attribute
                    var pdfRel = itemArray[activeItem][2];
                    var pdfDimensions = pdfRel.match(/\d+/g); //Create array of dimensions from Rel attribute values
                    var pdfBoxWidth = parseInt(pdfDimensions[0],10);
                    var pdfBoxHeight = parseInt(pdfDimensions[1],10);
                    //Set size and content of iframe
                    $("#external").attr({width: pdfBoxWidth, height: pdfBoxHeight, src: itemArray[activeItem][0]});
                    //Position in center and resize to fit dimensions
                    startSizes = [pdfBoxWidth,pdfBoxHeight];
                    _scale();
                    _centerPosition();
                    _showBox(1);
                break;
                
                case 'tooltip':  //If item is an tooltip put that in the box and position under mouse
                    $("#outer").removeClass("loading");
                    addDesc = 0;
                    $("#boxit").addClass('tipStyle');
                    $("#inner").empty().append(tooltip);
                    
                    var tipRel = itemArray[activeItem][2].split("|");
                    var tipTitle =  itemArray[activeItem][1];
                    var tipParts = tipRel[1].split(";");
                    var optionsArray = [];
                    var counter = 0;
                    
                    //Get tip content from rel attribute
                    for (counter in tipParts)
                    {
                        if(tipParts[counter] != "")
                        {
                            var option = tipParts[counter].split("=")[0];
                            var value = tipParts[counter].split("=")[1];
                            optionsArray.push([option, value]);
                        }
                    }
                    
                    var tipPreloader = new Image();
                    tipPreloader.onload = function() {
						//Scale image based on tooltip image width value set in options
                        var ratio = toolTipImageWidth / tipPreloader.width;
                        var imageHeight = tipPreloader.height*ratio;
                        snapChange = 1;
						
                        //Set relevant sections of tooltip
                        $("#tip_image").attr({src: optionsArray[0][1], alt: tipTitle}).attr('width', toolTipImageWidth).attr('height', imageHeight);
                        $("#tip_desc span").html(optionsArray[1][1]);
                        $("#tip_link").attr('href', optionsArray[2][1]);
                        
                        
                        //Add title to top of tooltip
                        $('<p id="tip_title">' + tipTitle + '</p>').prependTo("#inner").css({width: toolTipWidth-10});
                        //Position under mouse pointer and resize to fit
                        _mousePosition();
                        //Add small close button to tooltip container
                        $(xclose).prependTo("#inner").click(function()
                        {
                            _closeBox(0);
                            return false;
                        });
						//alert(imageHeight);
                        _showBox(0); // Don't display overlay
                        //tipPreloader.onload=function(){};
                    };
                    tipPreloader.src = optionsArray[0][1];
                break; 
            }
        }
        
        function _isGroupMember() {
            // alert ('isgroup');
            if (itemArray.length > 0)
            {
                groupTotal = 0;
                groupPosition = 0;
                groupArray = [];
                //Get group name and page position for currently selected/active item
                var activeItemGroup = itemArray[activeItem][4];
                var activeItemPagePosition = itemArray[activeItem][3];
                // Loop through all items on current page
                for (x=0; x < totalMatches; x++)
                {
                    var currentItemType = itemArray[x][5]
                    // If group name is the same as currently selected item add item to group array
                    if(currentItemType != "tooltip" && currentItemType != "pdf" && activeItemGroup == itemArray[x][4])
                    {
                        groupArray.push(x);
                    }
                }
                //  Get total number of images in current group
                groupTotal = groupArray.length;
                //  Get selected image position from known group images
                for (pos = 0; pos < groupTotal; pos++)
                {
                    if (activeItemPagePosition == groupArray[pos])
                    {
                        groupPosition = parseInt(pos,10);
                    }
                }
				_addNavigation(groupTotal,groupPosition);
			}
			_addDescription();
        }
        
        //Add previous and next buttons if part of an image set
        function _addNavigation(total,position) {
            // alert ('addnavigation');
            if (loop == 1)
            {
                if (position >= 0 && total > 1)
                {
                    $(previous).appendTo("#boxit").click(function(){
                        activeItem = (position > 0)?groupArray[position-1]:groupArray[total-1];
                        _changeContent();
                        return false;
                    });
                }
                if (position <= total-1 && total > 1)
                {
                    $(next).appendTo("#boxit").click(function() {
                        activeItem = (position < total-1)?groupArray[position+1]:groupArray[0];
                        _changeContent();
                        return false;
                    });
                }
            }
            else
            {
                if (position > 0)
                {
                    $(previous).appendTo("#boxit").click(function(){
                        activeItem = groupArray[position-1];
                        _changeContent();
                        return false;
                    });
                }
                if (position < total-1)
                {
                    $(next).appendTo("#boxit").click(function() {
                        activeItem = groupArray[position+1];
                        _changeContent();
                        return false;
                    });
                }
            }
        }
        
        //Change the content if more than one in the set
        function _changeContent() {
            // alert ('changeContent');
            $("#previous, #next").remove();
            $("#inner").css('filter', 'alpha(opacity=100)');
            $("#inner").fadeOut(animationSpeed, function(){
                _setContent();
            });
        }
        
        //Add the description to the boxit container if available
        function _addDescription() {
			if(allMatches[activeItem].getAttribute('rel').match("survey")==null)
			{
				// alert ('add description');
				addDesc = 40;
				$(desc).appendTo("#inner").fadeIn(animationSpeed);
				//  Output description text and position in group if more than one image in this group
				if (groupArray.length > 1) { $("#desc").html(itemArray[activeItem][1] + '<br />(' + ( groupPosition+1 ) + ' ' + 'of' + ' ' + groupTotal + ')'); }
				else { $("#desc").html(itemArray[activeItem][1]);}
        $("#inner").append(close);
				$("#close").click(function(){_closeBox(1); return false;});
			}
            
        }
        
        function _scale() {
            // alert ('scale');
            if ($("#boxit").length && itemArray[activeItem][5] != "tooltip")
            {
                //Get window size and reduce a little
                var maxWidth = $(window).width()-60;
                var maxHeight = $(window).height()-100;
                
                //Make sure boxit cannot go smaller than minimumSize value
                
                maxWidth = (maxWidth > minimumSize)?maxWidth:minimumSize;
                maxHeight = (maxHeight > minimumSize)?maxHeight:minimumSize;
                
                var resizeByWidth = 0;
            
                var originalWidth = startSizes[0];
                var originalHeight = startSizes[1];
                 
                if (itemArray[activeItem][5] != "iframe")
                {
                    if (originalWidth > maxWidth || originalHeight > maxHeight)
                    {
                        resizeByWidth = ((originalWidth/maxWidth) > (originalHeight/maxHeight));
                        var ratio = resizeByWidth ? originalWidth/maxWidth : originalHeight/maxHeight;
                        newWidth = originalWidth/ratio;
                        newHeight = originalHeight/ratio;
                    }
                    else
                    {
                        newWidth = originalWidth;
                        newHeight = originalHeight;
                    }
                }
                else
                {
                    if (originalWidth > maxWidth) {newWidth = maxWidth;}
                    else {newWidth = originalWidth;}
                    if (originalHeight > maxHeight) {newHeight = maxHeight;}
                    else {newHeight = originalHeight;}
                }
    
                boxWidth = newWidth;
                boxHeight = newHeight;
                _resizeToFit(boxWidth,boxHeight);
            }
        }

        //Center the boxit container on the screen
        function _centerPosition() {
            // alert ('centerposition');
            var winWidth = $(window).width();
            var winHeight = $(window).height();
            var sTop = $(window).scrollTop();
            var sLeft = $(window).scrollLeft();
            newLeft = (winWidth/2) - (boxWidth/2) + sLeft - 20;
            newTop = (winHeight/2) - (boxHeight/2) - (addDesc) + sTop;
            $("#boxit").animate({left: newLeft ,top: newTop},animationSpeed);
        }
        
        function _reposition() {
            //Only reposition container if the container exists and if it's not a tooltip!
            if(itemArray[activeItem]==null)
            {
              return;
            }
            if(activeItem!=-1)
            {
            
              if ($("#boxit").length && itemArray[activeItem][5] != 'tooltip' && itemArray[activeItem][5] != 'noscale')
              {
                  var winWidth = $(window).width();
                  var winHeight = $(window).height();
                  $("#overlay").css({width: winWidth});
                  var sTop = $(window).scrollTop();
                  var sLeft = $(window).scrollLeft();
                  newLeft = (winWidth/2) - (boxWidth/2) + sLeft - 20;
                  newTop = (winHeight/2) - (boxHeight/2) - (addDesc) + sTop;
                  $("#boxit").css({top: newTop, left: newLeft});
              }
            }
        }

        //Resize inner container and set relevant edge widths and heights to match
        function _resizeToFit(newWidth,newHeight) {
            //alert ('resizetofit:'+newWidth+";"+newHeight);
            if (snapChange != 1)
            {
                $('#boxImage, #external').animate({width: newWidth-2, height: newHeight-2},animationSpeed);
                $('#outer, #inner').animate({width: newWidth, height: newHeight+addDesc},animationSpeed);
                $("#t, #b").animate({width: newWidth+1},animationSpeed);
                $("#l, #r").animate({height: newHeight+addDesc+2},animationSpeed);
            }
            else
            {
                $('#boxImage, #external').css({width: newWidth, height: newHeight});
                $('#outer, #inner').css({width: newWidth, height: newHeight + addDesc});
                $("#t, #b").css({width: newWidth});
                $("#l, #r").css({height: newHeight + addDesc});
            }
            snapChange = 0;
        }
        
        //Put boxit container under mouse pointer
        function _mousePosition() {
            $("#boxit").css({left: mouseX-(toolTipWidth/2) ,top: mouseY});
        }
        
        //Select which type of data to show in boxit
        function _getFileType(type) {
            // alert ('getfiletype');   
      			if(type.indexOf('iframe') != -1)
                  {
      				return 'iframe';
      			}
            else if(type.indexOf('pdf') != -1)
            {
				      return 'pdf';
			      }
            else if(type.indexOf('tooltip') != -1)
            {
                return 'tooltip';
            }
            else if(type.indexOf('noscale') != -1)
            {
                return 'noscale';
            }
            else if(type.indexOf('survey') != -1)
            {
                return 'survey';
            }
            else
            {
      				return 'image';
      			}
		}
        return this.unbind('click').click(_init); //Start the boxit function processes
    };
})(jQuery);
