/*
Simple Image Trail script- By JavaScriptKit.com
Visit http://www.javascriptkit.com for this script and more
This notice must stay intact
*/

var offsetfrommouse=[50,50]; //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var displayduration=0; //duration in seconds image should remain visible. 0 for always.
var controlDim=20;//dimension for synchronising with preview-div padding, normally padding*2

var defaultimageheight = 390;	// maximum image size.
var defaultimagewidth = 300;	// maximum image size.

var largeImageMultiplyFactorHeight=4;
var largeImageMultiplyFactorWidth=4;
var largeImageLoaded=false;
var timer;

var imgName;
var imgTitle;
var imgModel;

function gettrailobj()
{
    if (document.getElementById)
    return document.getElementById("preview_div").style;
}

function gettrailobjnostyle()
{
    if (document.getElementById)
    return document.getElementById("preview_div");
}


function truebody(){
    return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function hidetrail(){
	dontProcessMouseTrack=true;
	gettrailobj().display= "none";
	gettrailobj().innerHTML="";
	gettrailobj().left="-500px"
	clearTimeout(timer);
    largImageLoaded=true;
}

function showFaddingImage()
{
    //dontProcessMouseTrack=false;
    clearTimeout(opacityTimer);
    followmouse(mouseXPos,mouseYPos);
    if (largImageLoaded)
    {
        document.getElementById('imageloading').style.display="none";
        changeOpac(objectOpacity,'preview_divimg');
        //clearTimeout(opacityTimer);
        opacity("preview_divimg", objectOpacity, 100, 1000);
    }
    else
    {
        largImageLoaded=true;//set flag to execute code block in if when large image is loaded
        changeOpac(0,'preview_divimg');
        opacity("preview_divimg",0,80, 1000);//set opacity to 80 till large image is loaded
        //calculate the position loading image.
        var startWidth=document.getElementById('imageloading').style.width;
        var startHeight=document.getElementById('imageloading').style.height;
        var loadingWidth=startWidth.substring(0,startWidth.indexOf('px'));
        var loadingHeight=startHeight.substring(0,startHeight.indexOf('px'));
        var loadingLeft=Math.round((document.getElementById('imagewidth').value*1-loadingWidth+controlDim)/2*100)/100;
        var loadingTop=Math.round((document.getElementById('imageheight').value*1-loadingHeight+controlDim)/2*100)/100;
        document.getElementById('imageloading').style.left=loadingLeft+'px';
        document.getElementById('imageloading').style.top=loadingTop+'px';
        document.getElementById('imageloading').style.display="block";//show loading image
    }
}

function showtrail(imagename,title,model)
{
    divLastWidth=0;
    divLastHeight=0;
    dontAdjustSize=true;
    largImageLoaded=false;
    imgName=imagename;
    imgTitle=title;
    imgModel=model;
    document.getElementById('imageloadlarge').style.display='none';

    if (document.getElementById('imageloadlarge').src==document.getElementById('largeimagebase').value+imgName)//dont process the trail process if process is requested for same image
    {
        largImageLoaded=true;
        document.getElementById('imagelarge').style.display="none";
        document.getElementById('imageloadlarge').style.display="block";
        timer = setTimeout('getImageSize("'+document.getElementById('imageloadlarge').src+'",true);',200);
        return;
    }
    
    var imagesrc=document.getElementById('smallimg'+imgModel).src;
    timer = setTimeout('getImageSize("'+imagesrc+'",false);',200);//show small image as large image
    document.getElementById('imagelarge').style.display="inline";
}

function adjustSize(millisec)
{
    var id='preview_div';
    var speed = Math.round(millisec / 100);
    var timerSlide=0;
    var time4Slide=0;
   if (dontAdjustSize===false)
   {
        var divNewWidth=document.getElementById('imagewidth').value*1;
        var widthdiff=divNewWidth-divLastWidth;

        if (widthdiff>5)//increase width
        {
            for(i = divLastWidth; i <= divNewWidth; ++i)
            {
                setTimeout("adjustWidth(" + i + ",'" + id + "')",(timerSlide * speed));
                timerSlide++;
            }
        }
        else if (widthdiff<-5)//descrease width
        {
            for(i = divLastWidth; i >= divNewWidth; --i)
            {
                setTimeout("adjustWidth(" + i + ",'" + id + "')",(timerSlide * speed));
                timerSlide++;
            }
        }
        time4Slide=(timerSlide * speed);
        timerSlide=0;
   }
   else if (divLastWidth==0)//set preview div size only for thumb1
   {
        document.getElementById('imageloadlarge').width=document.getElementById('imagewidth').value*1;
        document.getElementById('imagelarge').width=document.getElementById('imagewidth').value*1;
        gettrailobj().width=defaultimagewidth+"px";
   }
   
   if (dontAdjustSize===false)
   {
        var divNewHeight=document.getElementById('imageheight').value*1;
        var heightdiff=divNewHeight-divLastHeight;
        if (heightdiff>5)//increase height
        {
            for(i = divLastHeight; i <= divNewHeight; ++i)
            {
                setTimeout("adjustHeight(" + i + ",'" + id + "')",(timerSlide * speed));
                timerSlide++;
            }
        }
        else if (heightdiff<-5)//descrease Height
        {
            for(i = divLastHeight; i >= divNewHeight; --i)
            {
                setTimeout("adjustHeight(" + i + ",'" + id + "')",(timerSlide * speed));
                timerSlide++;
            }
        }
        if (time4Slide<(timerSlide * speed))
        {
            time4Slide=(timerSlide * speed);
        }
   }
   else if (divLastHeight==0)//set preview div size only for thumb1
   {
       document.getElementById('imageloadlarge').height=document.getElementById('imageheight').value*1;
       document.getElementById('imagelarge').height=document.getElementById('imageheight').value*1;
       gettrailobj().height=defaultimageheight+"px";
   }

    divLastWidth=document.getElementById('imagewidth').value*1;
    divLastHeight=document.getElementById('imageheight').value*1;
    return time4Slide;
}

function resumeMouseTrack(dontProcessMouseTrackVal)
{
    dontProcessMouseTrack=dontProcessMouseTrackVal;
    //followmouse(mouseXPos,mouseYPos);
}

function adjustWidth(width) {
	document.getElementById('preview_div').style.width=width+'px';
    //document.getElementById('preview_divimg').style.width=width+'px';
	document.getElementById('imagelarge').width=width;
    document.getElementById('imageloadlarge').width=width;
}

function adjustHeight(height) {
	document.getElementById('preview_div').style.height=height+divImgHeightDiff+'px';
    //document.getElementById('preview_divimg').style.height=height+divImgHeightDiff+'px';
    document.getElementById('imagelarge').height=height;
    document.getElementById('imageloadlarge').height=height;
}

var divLastWidth=0;
var divLastHeight=0;
var divImgHeightDiff=0;
var dontAdjustSize=true;

function getImageSize(imagesrc,keepSameSize)
{
    dontProcessOnLoad=false;
    document.getElementById('imagelarge').src=imagesrc;
    gettrailobj().display='block';
    dontProcessMouseTrack=false;
	getSizeImageResponse(imagesrc,keepSameSize);

    var imageobj = new Image();
    imageobj.onload = function() {//execute when large image completely loads
        if (document.getElementById('largeimagebase').value+imgName==imageobj.src)//display if the loaded image and the last image requested are same
        {
            var dontProcessMouseTrackVal=dontProcessMouseTrack;
            dontProcessMouseTrack=true;
            dontAdjustSize=false;
            document.getElementById('imageloadlarge').src=imageobj.src;
            largImageLoaded=true;
            var time4Slide=getSizeImageResponse(document.getElementById('imageloadlarge').src,true);
            document.getElementById('imagelarge').style.display="none";
            setTimeout("resumeMouseTrack("+dontProcessMouseTrackVal+");",time4Slide);
            document.getElementById('imageloadlarge').style.display="block";
        }
    };
    imageobj.src = document.getElementById('largeimagebase').value+imgName;//sart loading large image
}

function getSizeImageResponse(imagesrc,keepSameSize)
{
    var newImg = new Image();
    newImg.src = imagesrc;
    var height;
    var width;
    if (keepSameSize)
    {
        height = newImg.height;
        width = newImg.width;
    }
    else
    {
       /* if (height>width)
        {
            largeImageMultiplyFactorHeight=4.15;
            largeImageMultiplyFactorWidth=4;
        }
        else if (height<width)
        {
            largeImageMultiplyFactorHeight=4.15;
            largeImageMultiplyFactorWidth=4;
        }
        else
        {*/
            largeImageMultiplyFactorHeight=3.63;
            largeImageMultiplyFactorWidth=3.63;
        //}
        //alert (newImg.width);
        height = Math.round(newImg.height*largeImageMultiplyFactorHeight);
        width = Math.round(newImg.width*largeImageMultiplyFactorWidth);
        //alert (width+ '    ' +height);
    }
            
    //Maaintain expect ration after reducting height or widht for preview div by controlDim factor
    if (width>height)
    {
        document.getElementById('imagewidth').value=Math.round((width/height)*(height-controlDim));//maintain widht for reduced height
        document.getElementById('imageheight').value=height-controlDim;//reduce height
    }
    else if (width<height)//e.g 500x900
    {
        //alert(width);
        document.getElementById('imagewidth').value=width-controlDim;//reduce width
        document.getElementById('imageheight').value=Math.round((width-controlDim)/(width/height));//maintain height for reduced height
        //alert(document.getElementById('imagewidth').value);
    }
    else//both width and height are equal
    {
        document.getElementById('imagewidth').value=width-controlDim;
        document.getElementById('imageheight').value=height-controlDim;
    }

    titletext=imgTitle;//+" ("+imgModel+")";
    titletextlength=titletext.length*10;

    defaultimagewidth = document.getElementById('imagewidth').value*1;

    //at a rough idea, each character occupies approx. 9-10 px
    //find number of lines, the text will occupy
    //approx each line occupies 7px in FF
    titleHeight=(Math.ceil(titletextlength/defaultimagewidth))*7;
    defaultimageheight = document.getElementById('imageheight').value*1+controlDim+titleHeight;
    divImgHeightDiff=controlDim+titleHeight;
    var time4Slide=adjustSize(500);
    /*document.getElementById('imageloadlarge').width=document.getElementById('imagewidth').value*1;
    document.getElementById('imagelarge').width=document.getElementById('imagewidth').value*1;
    document.getElementById('imageloadlarge').height=document.getElementById('imageheight').value*1;
    document.getElementById('imagelarge').height=document.getElementById('imageheight').value*1;*/

    document.getElementById('imagetext').innerHTML=imgTitle;//+" ("+imgModel+")";
    showFaddingImage();
    return time4Slide;
}
var mouseXPos;
var mouseYPos;
var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)

var dontProcessMouseTrack=false;

function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX ;
    tempY = event.clientY ; 
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX;
    tempY = e.pageY;
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY
  mouseXPos = tempX
  mouseYPos = tempY
  followmouse(mouseXPos,mouseYPos);
}

function followmouse(mouseXPos,mouseYPos){
	if (dontProcessMouseTrack) return;
	
	var xcoord=offsetfrommouse[0];
	var ycoord=offsetfrommouse[1];

	var horizontalDistanceFromEdeges=10;
	var verticalDistanceFromEdeges=10;

	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(window.innerHeight)

	if (!IE){
		if (docwidth - mouseXPos < defaultimagewidth + controlDim + 5 + 2*offsetfrommouse[0]){
			xcoord = mouseXPos - xcoord - defaultimagewidth-offsetfrommouse[0]; // Move to the left side of the cursor
		} else {
			xcoord += mouseXPos+offsetfrommouse[0];
		}
		if (docheight - mouseYPos < defaultimageheight + 2*controlDim + 5 + 2*offsetfrommouse[1]){
			ycoord += mouseYPos - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + mouseYPos - docheight - truebody().scrollTop));
		} else {
			ycoord += mouseYPos;
		}

	} else if (IE){
		if (docwidth - mouseXPos < defaultimagewidth + controlDim + 5 + 2*offsetfrommouse[0]){
			xcoord = mouseXPos + truebody().scrollLeft - xcoord - defaultimagewidth-offsetfrommouse[0]; // Move to the left side of the cursor
		} else {
			xcoord += truebody().scrollLeft+mouseXPos+offsetfrommouse[0];
		}
		if (docheight - mouseYPos < (defaultimageheight + 2*controlDim + 5 + 2*offsetfrommouse[1])){
			ycoord += mouseYPos + truebody().scrollTop - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + mouseYPos - docheight));
		} else {
			ycoord += truebody().scrollTop + mouseYPos;
		}
	}

	if (xcoord===0)///if at left edge
	{
		xcoord=horizontalDistanceFromEdeges;
	}
	else if((xcoord+defaultimagewidth*1)>=docwidth)///if at right edge then add a distance
	{
		xcoord-=horizontalDistanceFromEdeges;
	}
	if (ycoord===0)///if at top edge
	{
		ycoord=verticalDistanceFromEdeges;
	}
	else if((ycoord+defaultimageheight*1)>=docheight)///if at bottom edge edge then add a distance
	{
		ycoord-=verticalDistanceFromEdeges;
	}
	gettrailobj().left=xcoord+"px";
	gettrailobj().top=ycoord+"px";
	//gettrailobj().width=defaultimagewidth+"px";
	//gettrailobj().height=defaultimageheight+"px";
}

function opacity(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	counter=0;
	var speed = Math.round(millisec / 100);
	var timer = 0;
	
	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; --i) {
			opacityTimer=setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; ++i)
			{
			opacityTimer=setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}
var opacityTimer;
var objectOpacity;

//change the opacity for different browsers
function changeOpac(opacity, id) {
    objectOpacity=opacity;
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

