/*
	cornBox JS CS: Fullsize Scaleable Image Overlays for Cornerstone CMS

        by prosper design 2011

        ver 1.1

        Built on lightbox by Lokesh Dhakar - http://www.huddletogether.com

       
	
	Table of Contents
	-----------------
	Configuration
	
	Functions
	- getPageScroll()
	- getPageSize()
	- pause()
	- getKey()
	- listenKey()
	- showLightbox()
	- hideLightbox()
	- initLightbox()
	- addLoadEvent()
	
	Function Calls
	- addLoadEvent(initLightbox)


*/

//
// Configuration
//

// If you would like to use a custom loading image or close button reference them in the next two lines.
var loadingImage = 'images/loading.gif';		
var closeButton = 'images/close.gif';		
var currentObjLink;





//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//

function getKey(e){

       var keycode = (window.event) ? event.keyCode : e.keyCode;

	key = String.fromCharCode(keycode).toLowerCase();
	if(key == 'x'){ hideLightbox(); }
        if(keycode == 39) { 
         var thisObj = getBrowseObj(currentObjLink,1);
         hideLightbox();
         showLightbox(thisObj);
     
        }
          if(keycode == 37) { 
         var thisObj = getBrowseObj(currentObjLink,-1);
           hideLightbox();
         showLightbox(thisObj);
     
        }
}


//
// listenKey()
//
function listenKey () {	document.onkeydown = getKey; }
	

function getBrowseObj(objLink,browse) {
	// loop through all anchor tags
   
       
    var anchors = document.getElementsByTagName("a");
        var numtot=0;
     //   var numnext=0;
      //  var numprev;
        var thisnum=0;
         var aimages = new Array();
         
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];
               
                
		if (anchor.getAttribute("href")){
                        if (anchor.getAttribute("rel") == "cornbox" || anchor.getAttribute("rel") == "cornbox-scale"  ) {
                        
			  aimages[numtot]=anchor;
                          numtot++;

                        }

                     }
		}
        
	
        for (var z=0; z<aimages.length; z++){
        var aimage = aimages[z];
                
                
        if (aimage==objLink){
           thisbrowse2=99;
            thisbrowse=z+browse;
            lastbrowse=aimages.length-1;
            
            if (thisbrowse==-1) { thisbrowse=lastbrowse }
             if (thisbrowse==lastbrowse+1) { thisbrowse=0 }
                        
             return aimages[thisbrowse];  
           
        }

       }
 return objLink;
      
}


//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//

function stripHttp(strUrl) {
var retStr=""
ztmp=strUrl.split("/");


for (var i=3; i<ztmp.length; i++) {
 
 retStr=retStr + "/" + ztmp[i];

}

return retStr
}

function showLightbox(objLink)


{       
        var thishref=objLink.href;
        currentObjLink=objLink;
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

        var imgX = arrayPageSize[0] - Math.round((arrayPageSize[0]/5));
        var imgY = arrayPageSize[1] - Math.round((arrayPageSize[1]/3));

       // alert(arrayPageSize[1] + ' - ' + Math.round((arrayPageSize[1]/3)) + ' = ' + imgY);
        if (objLink.getAttribute("rel")=='cornbox-scale') {
          thishref='/cs/resize.asp?src=' + stripHttp(thishref) + '&x=' + imgwidth + '&y=' + imgheight; 
         
        }
        
  
	// prep objects
	var objOverlay = document.getElementById('CSover');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objImage = document.getElementById('lightboxImage');

	var objLightboxDetails = document.getElementById('lightboxDetails');
        var objProsperDetails = document.getElementById('mess' + objLink.getAttribute('id'));
        var  objKeyboardMsg = document.getElementById('keyboardMsg');

        if (objProsperDetails) {
        //  
	// objProsperDetails.style.visibility='visible';
        objProsperDetails.style.zIndex="100";
 

        }
         
        // view overlay
        CSOver();
	// preload image
        
	imgPreload = new Image();

	imgPreload.onload=function(){
               
		objImage.src = thishref;

		// center lightbox and make sure that the top and left values are not negative
		// and the image placed outside the viewport
		var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
		var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);

		var prosperBoxTop =imgPreload.height + arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2) - 120;
                var prosperBoxLeft = imgPreload.width + ((arrayPageSize[0] - 20 - imgPreload.width) / 2) - 200;
		objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
                

                if (objProsperDetails) {
                  
		  objProsperDetails.style.top = (lightboxTop < 0) ? "0px" : prosperBoxTop + "px";
		  objProsperDetails.style.left = (lightboxLeft < 0) ? "0px" : prosperBoxLeft + "px";
                  objKeyboardMsg.innerHTML = '<input class=light_box style="Height: 16px; font-size: 7pt; font-weight: bold" onClick=showprosperBox(); type=button value=Detaljer>';

                 
                } else {

                      objKeyboardMsg.innerHTML = '';

                }

		objLightboxDetails.style.width = imgPreload.width + 'px';
		
		if(objLink.getAttribute('title')){
			objCaption.style.display = 'block';
			//objCaption.style.width = imgPreload.width + 'px';
			objCaption.innerHTML = objLink.getAttribute('title');
		} else {
			objCaption.style.display = 'none';
		}
		
		// A small pause between the image loading and displaying is required with IE,
		// this prevents the previous image displaying for a short burst causing flicker.
		if (navigator.appVersion.indexOf("MSIE")!=-1){
			pause(250);
		} 

		// if (objLoadingImage) {	objLoadingImage.style.display = 'none'; }

		

	
		objLightbox.style.display = 'block';

		// After image is loaded, update the overlay height as the new image might have
		// increased the overall page height.
		arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');
		
		// Check for 'x' keypress
		listenKey();

		return false;
	}

	imgPreload.src = thishref;


       
	
}





//
// hideLightbox()
//
function hideLightbox()
{
	// get objects
	
	objLightbox = document.getElementById('lightbox');
       
        objOverlay = document.getElementById('CSover');


     

	// hide overlay and lightbox
        hideCSOver();
        objOverlay.onclick = "";
	objLightbox.style.display = 'none';

	

        // hide prosper details boxes "mess"

    for (i = 0; i != 100; i++) {
        objTmpbox = document.getElementById('mess'+i);
        if (objTmpbox){
		objTmpbox.style.visibility = "hidden";
                objTmpbox.style.zIndex = "1";
        }        
    }



	// disable keypress listener
	document.onkeypress = '';
}



function showprosperBox()
{
	

    for (i = 0; i != 100; i++) {
        objTmpbox = document.getElementById('mess'+i);
        if (objTmpbox){
           if (objTmpbox.style.zIndex == "100") 
             objTmpbox.style.visibility = "visible";
                   
        }        
    }



	// disable keypress listener
	document.onkeypress = '';
}




//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
function initLightbox()
{
	
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		
                       if (anchor.getAttribute("href")){
                        if (anchor.getAttribute("rel") == "cornbox" || anchor.getAttribute("rel") == "cornbox-scale"  ) {
           
			anchor.onclick = function () {showLightbox(this); return false;}
                     }
		}
	}

	
	var objBody = document.getElementsByTagName("body").item(0);
	

	var objOverlay = document.getElementById('CSover');

	objOverlay.onclick = function () {hideLightbox();}
	

	// create lightbox div, same note about styles as above
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	
	// create link
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	objLink.setAttribute('title','Click to close');
	objLink.onclick = function () {hideLightbox(); return false;}
	objLightbox.appendChild(objLink);

	// preload and create close button image
	var imgPreloadCloseButton = new Image();

	// if close button image found, 
	imgPreloadCloseButton.onload=function(){

		var objCloseButton = document.createElement("img");
		objCloseButton.src = closeButton;
		objCloseButton.setAttribute('id','closeButton');
		objCloseButton.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objLink.appendChild(objCloseButton);

		return false;
	}

	imgPreloadCloseButton.src = closeButton;

	// create image
	var objImage = document.createElement("img");
	objImage.setAttribute('id','lightboxImage');
	objLink.appendChild(objImage);
	
	// create details div, a container for the caption and keyboard message
	var objLightboxDetails = document.createElement("div");
	objLightboxDetails.setAttribute('id','lightboxDetails');
	objLightbox.appendChild(objLightboxDetails);

	// create caption
	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objCaption.style.display = 'none';
	objLightboxDetails.appendChild(objCaption);

	// create keyboard message
	var objKeyboardMsg = document.createElement("div");
	objKeyboardMsg.setAttribute('id','keyboardMsg');
       	objLightboxDetails.appendChild(objKeyboardMsg);
        


}





addLoadEvent(initLightbox);	// run initLightbox onLoad

