/*********************************************************************
  Copyright 2006-2009 .
  
  Auteur : Boudchicha naime -- WWW.NEW6TM.COM
           Manager@new6tm.com
***********************************************************************/

NEW6TM.UI.Window = Class.create(NEW6TM.UI.Options, {
  options: {
    fileLoadingImage:        'asset/loading32.gif',     
	logowindow             : 'asset/aahplogo.png',
	titleImage             : 'asset/act-title.jpg', 
	closeButtonImage       : 'asset/close24.png',   
    overlayOpacity: 0.8,   // controls transparency of shadow overlay
    animate: true,         // toggles resizing animations
	overlayDuration : 0,
    resizeSpeed: 7,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)
    borderSize: 10,         //if you adjust the padding in the CSS, you will need to update this variable	
	resizeDuration : 0,   
	isAnimated : false
  },
    imageArray: [],
    activeImage: undefined,
	MyBody     : null,
    enable     : true,
	bounds     : {left : 0,top : 0 , right : 0 , buttom : 0 ,width : 0 , height : 0},
    initialize: function(options) {   
	     var _NuiWindow = document._NuiWindow = this;
        this.setOptions(options);   	
        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);

        if (this.options.resizeSpeed > 10) this.options.resizeSpeed = 10;
        if (this.options.resizeSpeed < 1)  this.options.resizeSpeed = 1;

	    this.options.resizeDuration = this.options.animate ? ((11 - this.options.resizeSpeed) * 0.15) : 0;
	    this.options.overlayDuration = this.options.animate ? 0.2 : 0;  // shadow fade in/out duration

        this.buildComponent();  
	 
    },
    // build component //
	buildComponent : function() {
        this.MyBody = $$('body')[0];
        // Madding Css
		var temp = this;
		this.MyBody.appendChild(Builder.node('div',{id:'Wnd_Mask'}));
		this.MyBody.appendChild(Builder.node('div',{id:'Wnd_disabled'}));
        this.MyBody.appendChild(Builder.node('div',{id:'Wnd_container'},Builder.node('div',{id:'Wnd_More'},
						  [Builder.node('div',{'class':'title'},
						  [Builder.node('a',{id:'Wnd_Close','class' : 'close'}),
						   Builder.node('img',{src:temp.options.logowindow}),			
						   Builder.node('h4',{id:'Wnd_Title'})]),
					Builder.node('div',{'class':'Wnd_Class',id : 'Wnd_Class'},
						  [Builder.node('div',{id:'Wnd_Loadding'},
								/*Builder.node('a',{id:'Wnd_Loadding_Link', href: '#' },*/ 
                                   Builder.node('img', {src: ''})/*)*/),
						  Builder.node('div',{id:'Wnd_Centent'})
						])					
			     ])
			 ));
		 this.MyBody.appendChild(Builder.node('div',{id:'Wnd_Temp'}));
		$("Wnd_Temp").setStyle({width : '800px'}).hide(); 
		$("Wnd_Close").setStyle({position:'absolute',background:'url('+temp.options.closeButtonImage+') no-repeat',
								 width:'24px',height:'24px',top:'5px',right:'10px', cursor:'pointer'});
        $("Wnd_More").down().setStyle({background:'url('+temp.options.titleImage+') repeat-x', margin:'0 0',
									   height:'30px', width:'100%', border:'#FFF 1px solid',padding:'0 0'});
        $('Wnd_Loadding').setStyle({width : '100%',width : '100%'}).down()
		                 .setStyle({position: 'absolute', top: '50%', left: '50%', border: 'none'})
						 .src = this.options.fileLoadingImage;
		$('Wnd_Mask').hide().observe('click', (function() { this.closeWindow(); }).bind(this));
		$('Wnd_Mask').setStyle({position: 'absolute',top: '0', left: '0', 'z-index': '1990', width: '100%', height: '500px', background: '#000'});
		$('Wnd_container').observe('click', (function(event) { if (event.element().id == 'Wnd_container') this.closeWindow(); }).bind(this));
		$('Wnd_More').hide().setStyle({position: 'relative',background:'#f0f0f0',margin:'auto auto'});
		$('Wnd_Class').setStyle({ width: '100%', height: '100%' ,'background':'#f0f0f0',border: '#FFF 1px solid',
								  'z-index':'1999px',overflow:'auto'});	
		$("Wnd_Centent").setStyle({padding:'10px 10px',margin : '0'});
		$('Wnd_container').setStyle({position: 'absolute',left: '0px',top : '0px',
									width: '100%', 'z-index': '1999',display:'inline-block'});
		/*$('Wnd_disabled').hide().setStyle({position: 'absolute',left: '0px',top : '0px',
									'z-index': '102',background : '#FFF'});*/
		$('Wnd_Close').observe('click', (function(event) { event.stop(); this.closeWindow();}).bind(this));
		$("Wnd_Title").setStyle({'font-size':'20px','font-family':'"Courier New"','font-style':'oblique',
								'line-height':'16px','margin': '0 50px','position':'absolute', 'top':'5px'});
				
      
     (function(){
			   var ids = 'Wnd_Mask Wnd_More Wnd_Title Wnd_Class Wnd_Loadding Wnd_container Wnd_Centent Wnd_Close Wnd_Temp Wnd_disabled'; 
			   $w(ids).each(function(id){ temp[id] = $(id);});		   
			   }).defer();				
	},
	Insert : function(wrapper,wrap) {
		var first = wrap.firstDescendant();	
		if (first) {
			var theAll = first.siblings(); 
		    wrapper.insert(first);		    
		    theAll.each(function(element) {wrapper.insert(element)});
		} else {wrapper.update(wrap.innerHTML)}
	},
	showWindowEx : function(target,absolitize) {
		var content = $(target.content);
		if (content.innerHTML != "") {
		if (absolitize != false) {
		    this.Wnd_Title.update(target.title);
		    var h =content.getHeight();
		    var w = content.getWidth();
		    if (h > 500) h=500; if (h<100) h=100;
			if (w < 300) w = 300;
		    this.Insert(this.Wnd_Temp,content);
		     //this.Wnd_Temp.insert(content.firstDescendant());
		    this.showWindow(null,w,h);
		} else 
		{
			 
			this.Wnd_Title.update(target.title);
		    this.Wnd_Temp.update(content.innerHTML);
		    var h =this.Wnd_Temp.getHeight();
		    if (h > 500) h=500;
		    this.showWindow(null,800,h);	
		}}
	},
    showWindow: function(event,width,height) {
	    var arrayPageSize = this.getPageSize();
		var arrayWindowPosition = this.getWindowStartPosition();
	    var arrayPageScroll = document.viewport.getScrollOffsets();
	    this.MyBody.setStyle({overflow : 'hidden'});
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
        $("Wnd_Mask").setStyle({ width: arrayPageSize[0] + 50 +'px', height: arrayPageSize[1] + 'px' });
        new Effect.Appear($("Wnd_Mask"), { duration: this.options.overlayDuration, from: 0.0, to: this.options.overlayOpacity });
		 this.Wnd_Centent.hide();	
		 this.Wnd_Loadding.show();	
		 if (event) { 
		  var target = Event.findElement(event, 'a');	  
          if (target) { 
			event.stop();		
			this.Wnd_Title.update(target.title);
		}}
		var ScrollXY = document.viewport.getScrollOffsets();
        $("Wnd_More").setStyle({top: ScrollXY.top + 50+ 'px',width : '400px',height:'100px'}).show();
		var Width = (width) ? width : 300;
		var Height = (height) ? height : 100;
		this.bounds.width = Width;
		this.bounds.height = Height
		this.resizeImageContainer(Width,Height);
    },
    resizeImageContainer: function(imgWidth, imgHeight) {

        var widthCurrent  = this.Wnd_More.getWidth();
        var heightCurrent = this.Wnd_More.getHeight();
        var widthNew  = (imgWidth  + this.options.borderSize * 2);
        var heightNew = (imgHeight + this.options.borderSize * 2);
        var xScale = (widthNew  / widthCurrent)  * 100;
        var yScale = (heightNew / heightCurrent) * 100;
		
		(function (){				  
		      new Effect.Parallel(
            [ 
			 new Effect.Scale(this.Wnd_More, yScale, {scaleX: false, duration: this.options.resizeDuration, queue: 'front',scaleContent: false}),
             new Effect.Scale(this.Wnd_More, xScale, {scaleY: false,scaleContent:false, duration: this.options.resizeDuration,
							  delay: this.options.resizeDuration})
            ], 
            { 
                duration: this.options.resizeDuration, 
                afterFinish: (function() {
					   this.updateContent();
	                  }).bind(this)
            } 
        );
        }).bind(this).delay(0.2);
     
    },  
	
	updateContent : function() {
		Object.extend(this.bounds,this.Wnd_Class.cumulativeOffset());
		Object.extend(this.bounds,this.Wnd_Class.getDimensions());
		this.Wnd_Centent.update();
		this.showImage();
	},
 
    showImage: function(){		
        this.Wnd_Loadding.hide();
		this.Insert(this.Wnd_Centent,this.Wnd_Temp);
		//alert(this.Wnd_Centent);
		//this.Wnd_Centent.insert(this.Wnd_Temp.firstDescendant());
		//this.Wnd_Temp.update();
        new Effect.Appear(this.Wnd_Centent, { 
            duration: this.options.resizeDuration, 
            queue: 'end'
        });
    },

    enableKeyboardNav: function() {
        document.observe('keydown', this.keyboardAction); 
    },
    disableKeyboardNav: function() {
        document.stopObserving('keydown', this.keyboardAction); 
    },
    keyboardAction: function(event) {
        var keycode = event.keyCode;
		event.stop();
       alert(keycode);
	   return 0;
        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }

        var key = String.fromCharCode(keycode).toLowerCase();
        
        if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
            this.closeWindow();
        } else if ((key == 'p') || (keycode == 37)){ // display previous image
            if (this.activeImage != 0){
                this.disableKeyboardNav();
                this.changeImage(this.activeImage - 1);
            }
        } else if ((key == 'n') || (keycode == 39)){ // display next image
            if (this.activeImage != (this.imageArray.length - 1)){
                this.disableKeyboardNav();
                this.changeImage(this.activeImage + 1);
            }
        }
    },
	disabledWindowContent : function() {
		/*this.Wnd_disabled.show().setStyle({left : this.bounds.left + 'px',top : this.bounds.top + 'px',
								   width : this.bounds.width + 'px',height : this.bounds.height + 'px'});*/
	},
    closeWindow: function() {
		
		if (this.enable == true) {
        this.Wnd_More.hide();
        new Effect.Fade(this.Wnd_Mask, { duration: this.options.overlayDuration ,
						afterFinish: (function() {this.MyBody.setStyle({overflow : 'auto'});}).bind(this)});
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
		}
    },
    getPageSize: function() {        
	     var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}

		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	},
	
	getWindowStartPosition : function() {
		var width = document.viewport.getWidth();
		var height = document.viewport.getHeight();
		var ScrollXY = document.viewport.getScrollOffsets();
		var wndLeft   = ((width - 600) / 2) + ScrollXY.left;
		var wndTop  =   ((height - 100) / 3) + ScrollXY.top;
		return {left : wndLeft,top : wndTop};
	}
});

