/* Define global variables */
var caption_id = "i1";
var new_caption_id = "";
var current = 0;
var target = 0;
var timer = 0;
var array_images = new Array();
var currentposition = 3;
var currenti = 'i4';
var lookuporder = new Array(7);;
var coverimageurl = new Array(7);

/* This variable must be changed to the used reflection image height in % of the source image */
var reflection_p = 0.5;

function loadImages() {
    show_data2();
 
  }

function step()
{
//    alert(current + ' current; ' + target + ' target');
	switch (target < current-1 || target > current+1) 
	{
		case true:
			moveTo(current + (target-current)/3);
			window.setTimeout(step, 50);
			timer = 1;
			break;

		default:
			timer = 0;
			break;
	}
}

function glideleft() 
{
        if(currenti == 'i2') {
            currenti = 'i1';
            glideTo(-0,currenti);
            currentposition = currentposition - 1;
            getText('i1');
        }
        else if(currenti == 'i3') {
            currenti = 'i2';
            glideTo(-150,currenti);
            currentposition = currentposition - 1;
            getText('i2');
        }
        else if(currenti == 'i4') {
            currenti = 'i3';
            glideTo(-300,currenti);
            currentposition = currentposition - 1;
            getText('i3');
        }
        else if(currenti == 'i5') {
            currenti = 'i4';
            glideTo(-450,currenti);
            currentposition = currentposition - 1;
            getText('i4');
        }
        else if(currenti == 'i6') {
            currenti = 'i5';
            glideTo(-600,currenti);
            currentposition = currentposition - 1;
            getText('i5');
        }
        else if(currenti == 'i7') {
            currenti = 'i6';
            glideTo(-750,currenti);
            currentposition = currentposition - 6;
            getText('i6');
        }     
}

function glideright() 
{
        if(currenti == 'i1') {
            currenti = 'i2';
            glideTo(-150,currenti);
            currentposition = currentposition - 6;
            getText('i2');
        }
        else if(currenti == 'i2') {
            currenti = 'i3';
            glideTo(-300,currenti);
            currentposition = currentposition - 6;
            getText('i3');
        }
        else if(currenti == 'i3') {
            currenti = 'i4';
            glideTo(-450,currenti);
            currentposition = currentposition - 6;
            getText('i4');
        }
        else if(currenti == 'i4') {
            currenti = 'i5';
            glideTo(-600,currenti);
            currentposition = currentposition - 6;
            getText('i5');
        }
        else if(currenti == 'i5') {
            currenti = 'i6';
            glideTo(-750,currenti);
            currentposition = currentposition - 6;
            getText('i6');
            
        }
        else if(currenti == 'i6') {
            currenti = 'i7';
            glideTo(-900,currenti);
            currentposition = currentposition - 6;
            getText('i7');
        }
}

function glideTo(x, new_caption_id)
{	

    var txt = '';
	/* Animate gliding to new x position */
	target = x;

	if (timer == 0)
	{
		window.setTimeout(step, 50);
		timer = 1;
	}

	/* Display new caption */
	caption_id = new_caption_id;
	caption = document.getElementById(caption_id)
	
	if (caption) caption_div.innerHTML = caption.innerHTML;
	
	getText(new_caption_id);

}

function getText(val) 
{
    show_data(val);
}

function finish(ret) {
    var arr = ret.split('~~~');
    
    var elem = document.getElementById('covertitle');
    elem.innerHTML = arr[0];
    
    elem = document.getElementById('coverdesc');
    elem.innerHTML = arr[1];
    
    elem = document.getElementById('captions');
    elem.innerHTML = arr[0];
}

    var xmlHttp; 
    var requestURL = 'http://www.egroup-us.com/webservices/coverflowservice.aspx'; 
    var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0; 
    var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
    var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
    //netscape, safari, mozilla behave the same??? 
    var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0; 

    function show_data(query){ 
            var subquery;
            //translate position for randomization. complete square peg, round hole solution
            //the logic isn't logical so don't try.    
            if(query == 'i1') {
                subquery = lookuporder[3];
            }
            else if(query == 'i2') {
                subquery = lookuporder[4];  
            }
            
            else if(query == 'i3') {
                subquery = lookuporder[0];
 
            }
            
            else if(query == 'i4') {
                subquery = lookuporder[1];
            }
            
            else if(query == 'i5') {
                subquery = lookuporder[2];
            }
            
            else if(query == 'i6') {
                subquery = lookuporder[5];
            }
            
            else if(query == 'i7') {
                subquery = lookuporder[6];
            }
              
			responsex = '';
            //Append the name to search for to the requestURL 
            var url = requestURL + '?id=' + subquery;        
            //Create the xmlHttp object to use in the request 
            //stateChangeHandler will fire when the state has changed, i.e. data is received back 
            // This is non-blocking (asynchronous) 
            xmlHttp = GetXmlHttpObject(stateChangeHandler); 
             
            //Send the xmlHttp get to the specified url 
            xmlHttp_Get(xmlHttp, url); 
    } 
	

    //stateChangeHandler will fire when the state has changed, i.e. data is received back 
    // This is non-blocking (asynchronous) 
    function stateChangeHandler()
    { 
        //readyState of 4 or 'complete' represents that data has been returned 
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){ 
            //Gather the results from the callback 
            var str = xmlHttp.responseText; 
		
			finish(str);
        } 
        
    } 

    // XMLHttp send GET request 
    function xmlHttp_Get(xmlhttp, url) { 
        xmlhttp.open('GET', url, true); 
        xmlhttp.send(null);
        return responsex; 
    } 

    function GetXmlHttpObject(handler) { 
        var objXmlHttp = null;    //Holds the local xmlHTTP object instance 

        //Depending on the browser, try to create the xmlHttp object 
        if (is_ie){ 
            //The object to create depends on version of IE 
            //If it isn't ie5, then default to the Msxml2.XMLHTTP object 
            var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 
             
            //Attempt to create the object 
            try{ 
                objXmlHttp = new ActiveXObject(strObjName); 
                objXmlHttp.onreadystatechange = handler; 
            } 
            catch(e){ 
            //Object creation errored 
                alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled'); 
                return; 
            } 
        } 
        else if (is_opera){ 
            //Opera has some issues with xmlHttp object functionality 
            alert('Opera detected. The page may not behave as expected.'); 
            return; 
        } 
        else{ 
            // Mozilla | Netscape | Safari 
            objXmlHttp = new XMLHttpRequest(); 
            objXmlHttp.onload = handler; 
            objXmlHttp.onerror = handler; 
        } 
         
        //Return the instantiated object 
        return objXmlHttp; 
    } 
    
    function getText(val) 
{
    show_data(val);
}

function finish2(ret) {
    var temp = ret.split('~~~');
    
    var temp2 = temp[0].split('|');
    coverimageurl[0] = temp2[0];
    lookuporder[0] = temp2[1];
    
    temp2 = temp[1].split('|');
    coverimageurl[1] = temp2[0];
    lookuporder[1] = temp2[1];
    
    temp2 = temp[2].split('|');
    coverimageurl[2] = temp2[0];
    lookuporder[2] = temp2[1];
    
    temp2 = temp[3].split('|');
    coverimageurl[3] = temp2[0];
    lookuporder[3] = temp2[1];
    
    temp2 = temp[4].split('|');
    coverimageurl[4] = temp2[0];
    lookuporder[4] = temp2[1];
    
    temp2 = temp[5].split('|');
    coverimageurl[5] = temp2[0];
    lookuporder[5] = temp2[1];
    
    temp2 = temp[6].split('|');
    coverimageurl[6] = temp2[0];
    lookuporder[6] = temp2[1];
    
    var elem = document.getElementById('top1_img1');
    elem.src = 'http://webservices.egroup-us.com/egroupwebadmin/image.aspx?id=' + coverimageurl[3];

	elem = document.getElementById('top1_img2');
    elem.src = 'http://webservices.egroup-us.com/egroupwebadmin/image.aspx?id=' + coverimageurl[4];

	elem = document.getElementById('top1_img3');
    elem.src = 'http://webservices.egroup-us.com/egroupwebadmin/image.aspx?id=' + coverimageurl[0];

	elem = document.getElementById('top1_img4');
    elem.src = 'http://webservices.egroup-us.com/egroupwebadmin/image.aspx?id=' + coverimageurl[1];
	
	elem = document.getElementById('top1_img5');
    elem.src = 'http://webservices.egroup-us.com/egroupwebadmin/image.aspx?id=' + coverimageurl[2];
        
	elem = document.getElementById('top1_img6');
    elem.src = 'http://webservices.egroup-us.com/egroupwebadmin/image.aspx?id=' + coverimageurl[5];
	
	elem = document.getElementById('top1_img7');
    elem.src = 'http://webservices.egroup-us.com/egroupwebadmin/image.aspx?id=' + coverimageurl[6];

    glideTo(-450,'i4' );
}

    var xmlHttp2; 
    var requestURL2 = 'http://www.egroup-us.com/webservices/coverflowimageservice.aspx'; 
    
    function show_data2(){ 
			responsex = '';
			var cacheBuster = (new Date).valueOf();
            //Append the name to search for to the requestURL 
            var url = requestURL2 + '?cacheBuster=' + cacheBuster;       
            //Create the xmlHttp object to use in the request 
            //stateChangeHandler will fire when the state has changed, i.e. data is received back 
            // This is non-blocking (asynchronous) 
            xmlHttp2 = GetXmlHttpObject2(stateChangeHandler2); 
             
            //Send the xmlHttp get to the specified url 
            xmlHttp_Get2(xmlHttp2, url); 
    } 
	

    //stateChangeHandler will fire when the state has changed, i.e. data is received back 
    // This is non-blocking (asynchronous) 
    function stateChangeHandler2()
    { 
        //readyState of 4 or 'complete' represents that data has been returned 
        if (xmlHttp2.readyState == 4 || xmlHttp2.readyState == 'complete'){ 
            //Gather the results from the callback 
            var str = xmlHttp2.responseText; 
		
			finish2(str);
        } 
        
    } 

    // XMLHttp send GET request 
    function xmlHttp_Get2(xmlhttp2, url) { 
        xmlhttp2.open('GET', url, true); 
        xmlhttp2.send(null);
        return responsex; 
    } 

    function GetXmlHttpObject2(handler) { 
        var objXmlHttp = null;    //Holds the local xmlHTTP object instance 

        //Depending on the browser, try to create the xmlHttp object 
        if (is_ie){ 
            //The object to create depends on version of IE 
            //If it isn't ie5, then default to the Msxml2.XMLHTTP object 
            var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 
             
            //Attempt to create the object 
            try{ 
                objXmlHttp = new ActiveXObject(strObjName); 
                objXmlHttp.onreadystatechange = handler; 
            } 
            catch(e){ 
            //Object creation errored 
                alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled'); 
                return; 
            } 
        } 
        else if (is_opera){ 
            //Opera has some issues with xmlHttp object functionality 
            alert('Opera detected. The page may not behave as expected.'); 
            return; 
        } 
        else{ 
            // Mozilla | Netscape | Safari 
            objXmlHttp = new XMLHttpRequest(); 
            objXmlHttp.onload = handler; 
            objXmlHttp.onerror = handler; 
        } 
         
        //Return the instantiated object 
        return objXmlHttp; 
    } 

function moveTo(x)
{
	current = x;
	var zIndex = max;
	/* Loop */
	for (var index = 0; index < max; index++)
	{ 
		var image = img_div.childNodes.item(array_images[index]);
		var z = Math.sqrt(10000 + x * x)+80;
        
		var xs = x / z * size + size;
		
		/* Get current image properties */
		var img_h = image.height;
		var img_w = image.width;

		/* Check source image format. Get image height minus reflection height! */

//		if(img_h > 190)
//		{
////		    alert(index + '; ' + img_w + 'w; ' + img_h + 'h');
//		    img_w =  (190*img_w)/img_h;
//		    img_h = 190;
//		}
		switch ((img_w + 1) > (img_h / (reflection_p + 1))) 
		{
			/* Landscape format */
			case true:
				var img_percent = 120;
				break;

			/* Portrait and square format */
			default:
				var img_percent = 100;
				break;
		}
		
		/* Process new image height and top spacing */
		
		var new_img_h = (img_h / img_w * img_percent) / z * size;
		if(new_img_h > 160)
		{
		    new_img_h = 160;
		}

		image.style.left = xs - (img_percent / 2) / z * size + imageflow_left + "px";


//		alert('new_img_h = (' + img_h + '/' + img_w + '*' + img_percent + ')/' + z + '*' + size + '='+new_img_h);
		var new_img_top = (images_width * 0.33 - new_img_h) + images_top + ((new_img_h / (reflection_p + 1)) * reflection_p) - 75;

        
		/* Set new image properties */
		

		image.style.height = new_img_h + "px";

		image.style.width= "";
		image.style.top = new_img_top + "px";
		

		/* Set image layer through zIndex */
		switch ( x < 0) 
		{
			case true:
				zIndex++;
				break;

			default:
				zIndex = zIndex -1;
				break;
		}
		image.style.zIndex = zIndex;

		x += 150;
	}
}

//----------------------------
function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }
function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
/* Main function */
function refresh()
{

	/* Cache document objects in global script variables */
	img_div = document.getElementById("images");
	
	caption_div = document.getElementById("captions");
	
	/* Change images div properties */

	images_width = img_div.offsetWidth;
	var images_height = images_width * 0.33;
	img_div.style.height = images_height - 85 + "px";

	//img_div.style.height = "200px";
	
    
	/* Change captions div properties */
	caption_div.style.top = img_div.offsetTop + images_height + "px";
	caption_div.style.width = images_width + "px";
	caption_div.innerHTML = document.getElementById(caption_id).innerHTML;
	
	/* Cache global variables, that only change on refresh */
	IE7 = (navigator.appVersion.indexOf('MSIE 7.')==-1) ? false : true;

	if(!IE7)
	{
	    imageflow_left = findPosX(document.getElementById("imageflow"));//.offsetLeft;
	}
	else
	{
	    imageflow_left = document.getElementById("imageflow").offsetLeft;
	}
	// if its IE 6 then we need to reposition by the container div position
	
	images_top = img_div.offsetTop;
	size = images_width * 0.5;
	max = img_div.childNodes.length;
	
	/* Cache correct node type indices in an array */
	var count=0;
	for (var index = 0; index < max; index++)
	{ 
		var image = img_div.childNodes.item(index);
		if (image.nodeType == 1)
		{
			array_images[count] = index;
			count++;
		}
	}
	max = array_images.length;

	/* Display images in current order */
	moveTo(current);

}

/* Show/hide functions */
function show(id) {
	var element = document.getElementById(id);
	element.style.visibility = "visible";
	element.style.display = "block";
}
function hide(id) {
	var element = document.getElementById(id);
	element.style.visibility = "hidden";
	element.style.display = "none";


}

/* Hide loading div and show the images div */
window.onload = function() {
    loadImages();
	hide('loading');
	// for Moz, resize the image to 0 height
	
	show('images');
	refresh();
	// move to default image
	
}

window.onresize = refresh;

/* JavaScript mouse wheel support */
function handle(delta) {

	var caption_id_int = caption_id.substr(1);
	caption_id_int = parseInt(caption_id_int);

	switch (delta > 0) 
	{
	case true:
		if(target != 0)
		{
			target = target + 150;
			new_caption_id = 'i' + (caption_id_int - 1);
		}
		break;

	default:
		if(caption_id_int < max)
		{
			target = target - 150;
			new_caption_id = 'i' + (caption_id_int + 1);
			break;
		}
	}
	glideTo(target, new_caption_id);
}

function buttonClick(direction)
{

    handle(direction);

}

/* JavaScript mouse wheel support */
//function wheel(event){
//	var delta = 0;
//	if (!event) event = window.event;
//	if (event.wheelDelta) {
//	    alert(event.wheelDelta);
//		delta = event.wheelDelta/120; 
//	} else if (event.detail) {
//		delta = -event.detail/3;
//	}
//	if (delta)
//		handle(delta);
//        if (event.preventDefault)
//                event.preventDefault();
//        event.returnValue = false;
//}

/* Initialization code */
//if (window.addEventListener)
//	window.addEventListener('DOMMouseScroll', wheel, false);
//window.onmousewheel = document.onmousewheel = wheel;