/* called */

var textCopy = '&copy; RDS Brauweiler GmbH';  // text under

bV  = parseInt(navigator.appVersion)
bNS = navigator.appName=="Netscape"
bIE = navigator.appName=="Microsoft Internet Explorer"

var idframe = 'detailbigimg';   // main BG frame 

/* resize attributes */
var imageDistanceH = 15;  // horizontal border distance
var imageDistanceT = 15;  // top border distance
var imageDistanceB = 45;  // bottom border thickness
var sipkyWidth = 30;        // sipky dimensions
var sipkyHeight = 30;       // sipky dimensions

// just for IE
var sipkaLSrc = PATH + '../img/sipka-left.png';
var sipkaRSrc = PATH + '../img/sipka-right.png';

/* transmutation parameters */
if(bIE) {
    // special for IE
    var steps = 5;
    var timeout = 1;  // timeout for window shaping
    var startupFade = true; // startup fade enable
    var fadeTimeout = 20;   // fade in timeout
    var fadeSteps = 10;     // fade steps
} else {
    var steps = 10;
    var timeout = 10;  // timeout for window shaping
    var startupFade = true; // startup fade enable
    var fadeTimeout = 10;   // fade in timeout
    var fadeSteps = 10;     // fade steps
}
var bgFadeFactor = 0.8; // factor on how much to show allframe BG

/* ----------------------------------------------------------------- */


function enable_boxes() {
  var arr = getElementsByClassName(null, "*", "menubox");
  for(var i=0; i<arr.length; i++) {
    arr[i].style.visibility = 'visible';
  }
}


function GetDisplaying(objid){
  if (!isObject(objid))
		objid=getId(objid);
  if (objid)
    s=objid.style.display;
  else
    return false;
  //if (s=='none')
	if (s.indexOf('none')>=0)
      return false;
  return true;
}

Array.prototype.find = function(searchStr) {
  var returna = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        returna = push;
        break;
      }
    } else {
      if (this[i]===searchStr) {
        returna = i;
        break;
      }
    }
  }
  return returna;
}

var inprogress=false;
var switching=false;
var origw = 0;
var origh = 0;

// nasty globals
var index = 0;
var idfram = 'detailbigimg';

function ImgForward() {
  if(!switching) {
    index = index + 1;
    
    // if next img is 0, roll back to start or prev 0
    if(next_imgs[index] == 0 || index == next_imgs.length) {
        index = index - 1;
        while(next_imgs[index] != 0 && index >= 0) {
            index = index - 1;
        }
        index++;
    }
    
    UpdateImage();
  }
}

function ImgBackward() {
  if(!switching) {
    index = index - 1;
    
    // if next img is 0, roll forward to end or next 0
    if(next_imgs[index] == 0 || index < 0) {
        index = index + 1;
        while(next_imgs[index] != 0 && index < next_imgs.length) {
            index = index + 1;
        }
        index = index - 1;
    }
    
    UpdateImage();
  }
}

function UpdateImage() {
    if(!switching) {
        // show loading pane
        loadingPane();
        // load image into backup pane
        backupImage.src = next_imgs[index];
        switching = true;
        // set enough time to update
        setTimeout('UpdateImage()', 250);
        return;
    } 
    
    if(IsImageOk(backupImage)) {
        firstImage = false;
        // dimensions           
        origx = currx;
        origy = curry;
        origw = currw;
        origh = currh;
        
        neww = backupImage.width + 2*imageDistanceH;
        newh = backupImage.height + imageDistanceT + imageDistanceB;
            
        // screen fit X        
        if(neww > screenWidth) {
            var aspect = neww/newh;
            neww = screenWidth;
            newh = Math.round(neww/aspect);
        }
        
        // screen fit Y
        if(newh > screenHeight) {
            var aspect = neww/newh;
            newh = screenHeight;
            neww = Math.round(newh*aspect);
        }
  
        // compute new position coords
        var scrolls = getScrollXY();
        newx = scrolls.x + Math.round((screenWidth-neww)/2);
        newy = scrolls.y + Math.round((screenHeight-newh)/2);

        // call magic transmutation algorithm
        fadeCompleted = false;
                
        transmuteImage();
        
        
    } else {
        // set enough time to update
        setTimeout('UpdateImage()', 100);
    }
      
}

function ImgClose() {
  BigImageViewClose(idframe);
}

var def_left; 
var def_top;

var screenWidth;
var screenHeight;

var origx=0;
var origy=0;
var newx=0;
var newy=0;
var currx=0;
var curry=0;
var origw=0;
var origh=0;
var neww=0;
var newh=0;
var currw=0;
var currh=0;

var image=null;
var pane=null;
var bg = null;
var sipkaLeft = null;
var sipkaRight = null;
var firstImage = false;
var step=0;
var fadeStep=0;
var currstep= 0;
var fadeCompleted = false;

function transmuteImage() { 
    // currstep indicates this is just the begin of transmute
    if(currstep==0) {      
        inprogress = true;
        // fade original image, hide it, replace with new, and carry on transmutation
        if(!firstImage) {
            deleteLoadingPane();
            if(startupFade) {
                if(fadeStep == 0) {
                    setTimeout('fadeImageOut()', fadeTimeout);
                }         
            } else {
                
            }
        }
    }
    
    // wait till fade out is on its way
    // only NOT for first image and NOT if fade is completed and startupFade is set
    if(!firstImage && !fadeCompleted && startupFade) {
        setTimeout('transmuteImage()', 50);   
        return; 
    }
    
    // hide the image
    // then swap with the backup
    // also hide arrows
    // also change text
    if(!firstImage && currstep == 0) {
        image.style.visibility = 'hidden';
        bottom.style.visibility = 'hidden';
        image.src = backupImage.src;
        bottom.innerHTML = '<p>' + next_texts[index] + '</p><h4>' + textCopy + '</h4>';
        sipkaRight.style.display = 'none';
        sipkaLeft.style.display = 'none';
    }
    
    currstep++;
    
    // final?
    if(currstep==steps) {
        // finish transmutation
        currw = neww;
        currh = newh;
        currx = newx;
        curry = newy;    
        modifier=1;
        inprogress = false;
            
        // final pane update
        pane.style.width = currw+'px';
        pane.style.height = currh+'px';
        pane.style.left = currx+'px';
        pane.style.top = curry+'px';
    
        setOpacity(pane, 1);
        setOpacity(bg,bgFadeFactor);
        
    } else if(inprogress)  {
        // proceed with transmute
        // first get step modifier
        var modifier = currstep/steps;
        
        // now compute additions and add them
        currx = origx + Math.round((newx - origx)*modifier);
        curry = origy + Math.round((newy - origy)*modifier);
        currw = origw + Math.round((neww - origw)*modifier);
        currh = origh + Math.round((newh - origh)*modifier);
        
        // in-pane update
        pane.style.width = currw+'px';
        pane.style.height = currh+'px';
        pane.style.left = currx+'px';
        pane.style.top = curry+'px';
        
        // startup fade startup opacity for first image
        if(startupFade && firstImage) {
            setOpacity(pane, modifier);
        }
        
        
        // background, only if this is first Image
        if(firstImage) {
            setOpacity(bg,modifier*bgFadeFactor);
        }
        
        // call timeout once more
        setTimeout('transmuteImage()', timeout);
        return;
    }
    
    

    // terminal arrangements
    // this is the last run of the function transmuteImage
    if(!inprogress) {
        currstep=0;
        
        // this updates image coords
        image.width = Math.max(0, currw - 2*imageDistanceH);
        image.height = Math.max(0, currh - imageDistanceT - imageDistanceB);
        image.style.left = (currx + imageDistanceH) + 'px';
        image.style.top = (curry + imageDistanceT) + 'px';
        
        // this updates bottom pane
        bottom.style.top = (curry + imageDistanceT + image.height) + 'px';
        bottom.style.left = (currx + imageDistanceH) + 'px';
        bottom.style.width = (image.width) + 'px';
        
        // detect total images in the set with respect to 0's
        var idx = index;
        while(next_imgs[idx] != 0 && idx >= 0) {
            idx = idx - 1;
        }
        idx++;
        var beg = idx;
        while(next_imgs[idx] != 0 && idx < next_imgs.length) {
            idx = idx + 1;
        }
        idx--;
        var imgsCorrect = idx - beg + 1;
        
        // this updates sipka Left, sipka right
        if(imgsCorrect > 1) {
            sipkaLeft.style.left = currx + 'px';
            // sipka right is a little bit tricky :P
            sipkaRight.style.left = (currx + neww - sipkyWidth) + 'px';
            var sipkyY = (curry + imageDistanceT + Math.round(image.height/2) - Math.round(sipkyHeight/2)) + 'px';
            sipkaRight.style.top = sipkyY;
            sipkaLeft.style.top = sipkyY;
        }

        

        // fade image in, only if setup correctly
        if(startupFade) {
            setOpacity(image, 0);
            image.style.visibility='visible';
            bottom.style.visibility='visible';
            // show arrows only if len > 1
            if(imgsCorrect > 1) {
                sipkaRight.style.display = 'block';
                sipkaLeft.style.display = 'block';       
            }
            setTimeout('fadeImageIn()', fadeTimeout);        
        } else {
            image.style.visibility='visible';
            bottom.style.visibility='visible';
            if(imgsCorrect > 1) {
                sipkaRight.style.display = 'block';
                sipkaLeft.style.display = 'block';       
            }
        }

        switching = false;
    }

}

function fadeImageIn() {
    fadeStep++;
    if(fadeStep < fadeSteps && !fadeCompleted) {
        setOpacity(image, fadeStep/fadeSteps);   
        //setOpacity(bottom, fadeStep/fadeSteps);  
        setTimeout('fadeImageIn()', fadeTimeout);    
    } else {
        setOpacity(image, 1);    
        //setOpacity(bottom, 1); 
        fadeStep = 0;
    }
}

function fadeImageOut() {
    fadeStep+=2;
    if(fadeStep < fadeSteps && !fadeCompleted) {
        setOpacity(image, 1-fadeStep/fadeSteps);   
        //setOpacity(bottom, 1-fadeStep/fadeSteps);  
        setTimeout('fadeImageOut()', fadeTimeout);    
    } else {
        setOpacity(image, 0);
        //setOpacity(bottom, 0);     
        fadeStep = 0;
        fadeCompleted = true;
    }
            
}

var started = false;
var origImage = null;
var backupImage = null;
var bottom = null;

function BigImageView(event, srcframe){
    var objMain;
    var is;
        
    screenWidth = GetPageWidth();
    screenHeight = GetPageHeight();
    var scrolls = getScrollXY();
  
    index = next_imgs.find(srcframe);
  
    is2 = document.getElementById(idframe+'INNER');
    is3 = document.getElementById(idframe+'PANE');
      
    if(started) {
        
        if(IsImageOk(is2)) {
            
            // complete, start with transmute
            deleteLoadingPane();
            
            // compute new dimensions
            neww = is2.width + 2*imageDistanceH;
            newh = is2.height + imageDistanceT + imageDistanceB;
            
            // screen fit X        
            if(neww > screenWidth) {
                var aspect = neww/newh;
                neww = screenWidth;
                newh = Math.round(neww/aspect);
            }
            
            // screen fit Y
            if(newh > screenHeight) {
                var aspect = neww/newh;
                newh = screenHeight;
                neww = Math.round(newh*aspect);
            }
    
            // compute new position coords
            newx = scrolls.x + Math.round((screenWidth-neww)/2);
            newy = scrolls.y + Math.round((screenHeight-newh)/2);

            if(startupFade) {
                setOpacity(is2, 0);
                setOpacity(is3, 0);
                //setOpacity(bottom, 0);
            }

            is2.style.visibility = 'hidden';
            is3.style.visibility = 'visible';
            bottom.style.visibility = 'hidden';

            image = is2;
            pane = is3;
            bg = document.getElementById(idframe);
            setOpacity(bg,0);

            // now enable transitions        
            transmuteImage();
            
            // no more bigImageView
            started = false;
            return;
            
        } else {
            
            // not complete, check later
            setTimeout('BigImageView(false, \''+srcframe+'\')', 50);
        }
           
    } else {

        loadingPane();
        
        started = true;
        firstImage=true;
        
        /* fill up the page with black */
        objMain=document.createElement("div");
        objMain.id = idframe;
        objMain.style.width=GetPageWidth()+'px';
        objMain.style.height=  '1600px';
        objMain.style.position='absolute';
        objMain.style.left='0';
        objMain.style.top='0';
        objMain.style.zIndex=100;
        setOpacity(objMain, 0);            
        
        // attach event 	
        AddEvent(objMain,'click',BigImageViewEventClose);

        // pane - around the image
        var objPane = document.createElement("div");
        objPane.id = idframe+'PANE';
        objPane.style.position='absolute';
        objPane.style.visibility='hidden';
        
        // text div - bottom
        var objBottom = document.createElement("div");
        objBottom.id = idframe+'BOTTOM';
        objBottom.style.position='absolute';
        objBottom.style.visibility='hidden';
        objBottom.innerHTML = '<p>' + next_texts[index] + '</p><h4>' + textCopy + '</h4>';
        bottom = objBottom;
            
        // image itself
        var objIn = document.createElement("img");
        objIn.id = idframe+'INNER';
        objIn.style.position='absolute';
        objIn.src = srcframe;
        objIn.style.visibility='hidden';
        
        // attach to body
        document.body.appendChild(objIn);
        document.body.appendChild(objPane);
        document.body.appendChild(objBottom);
        
        // onclick on image
        AddEvent(objIn, 'click', BigImageViewEventClose);
        AddEvent(objPane, 'click', BigImageViewEventClose);
        
        // hide selects
        if(document.all && typeof document.body.style.maxHeight == "undefined"){
        	var selects=document.getElementsByTagName('SELECT');
        	for(var i=0; i<selects.length; i++){
          		SetVisibility(selects[i],false);
        	}
        }
           
        // attach main  
        document.body.appendChild(objMain);
        
        // explore the originating image
        if(event == null) 
            event = window.event;
        var origObject=(typeof event.target != 'undefined') ? event.target : event.srcElement;
        
        if(origObject) {
            // fetch starting image coords
            origx = getElementLeft(origObject);
            origy = getElementTop(origObject);
            origw = origObject.width;
            origh = origObject.height;
        } else {
            // or, if not possible, put to screen center
            origx = scrolls.x + Math.round(ScreenWidth/2);
            origy = scrolls.y + Math.round(ScreenHeight/2);
            origw = 0;
            origh = 0;
        }
        
        // place arrows in
        var objSipL = document.createElement("a");
        objSipL.id = 'sipkaLeft';
        objSipL.innerHTML = '&nbsp;';
        objSipL.href='javascript:ImgBackward()'; 
        // fix png background
        if(!(window.supersleight == undefined)) {
            objSipL.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + sipkaLSrc + "', sizingMethod='scale')";
		    objSipL.style.background = 'transparent';
        }

        var objSipR = document.createElement("a");
        objSipR.id = 'sipkaRight';
        objSipR.innerHTML = '&nbsp;';
        objSipR.href='javascript:ImgForward()';
        // fix png background
        if(!(window.supersleight == undefined)) {
            objSipR.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + sipkaRSrc + "', sizingMethod='scale')";
		    objSipR.style.background = 'transparent';
        }
        
        sipkaLeft = objSipL;
        sipkaRight = objSipR;
        
        sipkaLeft.style.display = 'none';
        sipkaRight.style.display = 'none';

        document.body.appendChild(objSipL);
        document.body.appendChild(objSipR);

        // generate backup image, for switch
        var objIn = document.createElement("img");
        objIn.id = idframe+'BACKUP';
        objIn.style.position='absolute';
        objIn.style.display='none';
        backupImage = objIn;
                                
        // let it work
        setTimeout('BigImageView(false, \''+srcframe+'\')', 100);
    }
}

function setOpacity(element, howMuch) {
    if(element) {
        if (navigator.userAgent.indexOf("Firefox") != -1) {
		   if (howMuch == 1) { howMuch = 0.999999; } // This is majorly awkward
		}

    	// Multi-browser opacity setting
        if(bIE) {
            element.style.filter = "alpha(opacity=" + (Math.round(howMuch*100)) + ")"; // IE/Win
        } else {
            element.style.opacity = howMuch;
        }
    }
}

function loadingPane() {
    // loading pane    
    objLoading = document.createElement('div');
    objLoading.id = 'loadingPane';
    
    var scrolls = getScrollXY();
    objLoading.style.top = scrolls.y + 'px';
    objLoading.style.left = scrolls.x + 'px';
    
    // IE 6 fix
    if(document.all && typeof document.body.style.maxHeight == "undefined"){
         objLoading.style.height = GetPageHeight() + 'px';    
    }
    
    document.body.appendChild(objLoading);    
}

function removeElementOfId(id) {
    id = document.getElementById(id);
    if(id) {
        var par = id.parentNode;
        par.removeChild(id);
    }    
}

function deleteLoadingPane() {
    // loading pane
    removeElementOfId('loadingPane');
}  

function BigImageViewEventClose(e){
		
	// erase variables
	origImage = null;
	
    // IE6 only	
	if(document.all && typeof document.body.style.maxHeight == "undefined"){
		var selects=document.getElementsByTagName('SELECT');
		for(var i=0; i<selects.length; i++){
      		SetVisibility(selects[i],true);
    	}
	}
	
	removePhotoPanes();
	
}

function removePhotoPanes() {
    // destroy panes
	removeElementOfId('loadingPane');
    removeElementOfId(idframe + 'INNER');
    removeElementOfId(idframe + 'PANE');
    removeElementOfId(idframe + 'BACKUP');
    removeElementOfId(idframe + 'BOTTOM');
    removeElementOfId('sipkaLeft');
    removeElementOfId('sipkaRight');
    removeElementOfId(idframe);
}

function BigImageViewClose(idcko){
		
	// erase variables
	origImage = null;
	
  // IE6 only	
	if(document.all && typeof document.body.style.maxHeight == "undefined"){
		var selects=document.getElementsByTagName('SELECT');
		for(var i=0; i<selects.length; i++){
      		SetVisibility(selects[i],true);
    	}
	}
	
	removePhotoPanes();
    
	return false;
	
}

function GetPageWidth(){
    return (!document.body.scrollWidth)?document.width:document.body.scrollWidth;
}

function GetPageHeight(){
   if (typeof window.innerHeight != 'undefined') {
      return window.innerHeight;
    } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
       return document.documentElement.clientHeight;
    } else {
         return document.getElementsByTagName('body')[0].clientHeight;
    }
}

function getElementLeft(elem) {	
		xPos = elem.offsetLeft;
		tempEl = elem.offsetParent;
  		while (tempEl != null) {
  			xPos += tempEl.offsetLeft;
	  		tempEl = tempEl.offsetParent;
  		}
		return xPos;
}

function getElementTop(elem) {
		yPos = elem.offsetTop;
		tempEl = elem.offsetParent;
		while (tempEl != null) {
  			yPos += tempEl.offsetTop;
	  		tempEl = tempEl.offsetParent;
  		}
		return yPos;
}


function SetVisibility(objid, boolstate){
  if (boolstate){
    s='visible';
  }else{
    s='hidden';
  }
  if (obj=getId(objid)) obj.style.visibility=s;
}

function parseClassesContain(oClassNames,testedclass){
	var a = parseClasses(oClassNames);
	for(var i=0; i<a.length; i++){
		if (a[i]==testedclass)
			return true;
	}
	return false;
}

function parseClasses(oClassNames){
    return oClassNames.split(' ');
}

function getElementByClassName(oElm, strTagName, oClassNames){
  arr=getElementsByClassName(oElm, strTagName, oClassNames);
  
  return arr.length==0 ? null : arr[0];
}


/*vraci kolikaty children sveho rodice jsem*/
function MyOrderNum(obj){
  par=obj.parentNode;
  for(var i=0; i<par.childNodes.length; i++)
    if (par.childNodes[i]==obj)
      return i;
  return -1;
}

 


function SetDisplaying(objid, boolstate){
  if (boolstate){
    s='';
  }else{
    s='none';
  }
  if (isObject(objid))
	objid.style.display=s;
  else
    if (obj=getId(objid)) obj.style.display=s;
}

function isNull(a) {
    return typeof a == 'object' && !a;
}
function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

function isUndefined(a) {
    return typeof a == 'undefined';
}

function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}

function isFunction(a) {
    return typeof a == 'function';
}

function isString(a) {
    return typeof a == 'string';
}

function getId(id){
    if (isObject(id)) return id;
    return document.getElementById(id);
}

function SetClass(objid,cl){
	if (isString(objid))
		objid=getId(objid);
  if (objid)
    objid.className=cl;
}


function AddEvent(obj,etype,fn){
	if (!obj) obj=document;
	if(window.opera && (obj == window)) obj = document;
	
	if(document.addEventListener)   
         obj.addEventListener(etype, fn, false);
	else
         obj.attachEvent('on' + etype, fn);
}

function RemoveEvent(obj,etype,fn){
	if (!obj) obj=document;
	if(window.opera && (obj == window)) obj = document;
	
	if(document.removeEventListener)
        obj.removeEventListener(etype, fn, false);
    else
		obj.detachEvent('on' + etype, fn);
}



function SrcFromEvent(e){
	if(!e) return null;
	if (navigator.appName == "Microsoft Internet Explorer" && e.srcElement) {
      return e.srcElement;
  } else if(e.target) {  // is mozilla/netscape
      // need to crawl up the tree to get the first "real" element
      // i.e. a tag, not raw text
      var o = e.target;
      while (!o.tagName) {
          o = o.parentNode;
      }
      return o;
  }
  return e;
}

function getElementsByClassName(oElm, strTagName, oClassNames){
    if (oElm==null) oElm=document.body;

    var arrElements = (strTagName == "*" )? getAllChildren(oElm) : 
					  oElm.getElementsByTagName(strTagName);

    var arrReturnElements = new Array();
    var arrRegExpClassNames = new Array();
    if(typeof oClassNames == "object"){
        for(var i=0; i<oClassNames.length; i++){
            arrRegExpClassNames.push(new RegExp("(^|\\s)" + 
            oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
        }
    }
    else{
        arrRegExpClassNames.push(new RegExp("(^|\\s)" + 
        oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
    }
    var oElement;
    var bMatchesAll;
    for(var j=0; j<arrElements.length; j++){
        oElement = arrElements[j];
        bMatchesAll = true;
        for(var k=0; k<arrRegExpClassNames.length; k++){
            if(!arrRegExpClassNames[k].test(oElement.className)){
                bMatchesAll = false;
                break;                      
            }
        }
        if(bMatchesAll)
            arrReturnElements.push(oElement);
		
    }
    return (arrReturnElements)
}

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
} 

function IsImageOk(img) {
  if (!img.complete) {
    return false;
  }

  if (typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0) {
    return false;
  }

  return true;
}

// get scroll offsets

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return { x:scrOfX, y:scrOfY };
}

