// -----------------------------------------------------------------------------------
//
//	LoginBox v1.0
//	by Victor Volker - http://www.victorvolker.com
//	Last Modification: 3/11/08
//
//	Based on Lokesh Dhakar's LightBox 2 - http://lokeshdhakar.com/projects/lightbox2/
//	
//
// -----------------------------------------------------------------------------------
/*

    Table of Contents
    -----------------
    Configuration

    Loginbox Class Declaration
    - initialize()
    - updateImageList()
    - start()
    - resizeImageContainer()
    - showImage()
    - end()
    
    Function Calls
    - document.observe()
   
*/
// -----------------------------------------------------------------------------------

//
//  Configurationl
//
LoginboxOptions = Object.extend({
    fileLoadingImage:        '../images/loading.gif',     

    overlayOpacity: 0.8,   // controls transparency of shadow overlay

    animate: true,         // toggles resizing animations
    resizeSpeed: 10,        // 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
	
	cont_w: 473, 
	cont_h: 256

}, window.LoginboxOptions || {});

// -----------------------------------------------------------------------------------

var Loginbox = Class.create();

Loginbox.prototype = {
    
    // initialize()
    // Constructor runs on completion of the DOM loading. Calls updateImageList and then
    // the function inserts html at the bottom of the page which is used to display the shadow 
    // overlay and the image container.
    //
    initialize: function() {    
        
	
        this.updateImageList();
        

        if (LoginboxOptions.resizeSpeed > 10) LoginboxOptions.resizeSpeed = 10;
        if (LoginboxOptions.resizeSpeed < 1)  LoginboxOptions.resizeSpeed = 1;

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

        // When Loginbox starts it will resize itself from 250 by 250 to the current image dimension.
        // If animations are turned off, it will be hidden as to prevent a flicker of a
        // white 250 by 250 box.
        var size = (LoginboxOptions.animate ? 250 : 1) + 'px';
        

        // Code inserts html at the bottom of the page that looks similar to this:

        var objBody = $$('body')[0];

		objBody.appendChild(Builder.node('div',{id:'overlay'}));
	
        objBody.appendChild(Builder.node('div',{id:'loginbox'}, [
            Builder.node('div',{id:'outerImageContainer'}, 
                Builder.node('div',{id:'imageContainer'}, [
                    Builder.node('div',{id:'loginboxImage'},[]), 
                    Builder.node('div',{id:'loading'}, 
                        Builder.node('a',{id:'loadingLink', href: '#' }, 
                            Builder.node('img', {src: LoginboxOptions.fileLoadingImage})
                        )
                    )
                ])
            )
        ]));


		$('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
		$('loginbox').hide().observe('click', (function(event) { if (event.element().id == 'loginbox') this.end(); }).bind(this));
		$('outerImageContainer').setStyle({ width: LoginboxOptions.cont_w, height: LoginboxOptions.cont_h });

        var th = this;
        (function(){
            var ids = 
                'overlay loginbox outerImageContainer imageContainer loginboxImage loading loadingLink ' ;   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();
		
    },

    //
    // updateImageList()
    // Loops through anchor tags looking for 'loginbox' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding images w/ajax.
    //
    updateImageList: function() {   
        this.updateImageList = Prototype.emptyFunction;

        document.observe('click', (function(event){
            var target = event.findElement('a[rel^=loginbox]') || event.findElement('area[rel^=loginbox]');
            if (target) {
                event.stop();
                this.start(target);
            }
        }).bind(this));
    },
    
    //
    //  start()
    //  Display overlay and loginbox. If image is part of a set, add siblings .
    //
    start: function(imageLink) {    

        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LoginboxOptions.overlayOpacity });

        // calculate top and left offset for the loginbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var loginboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var loginboxLeft = arrayPageScroll[0];
        this.loginbox.setStyle({ top: loginboxTop + 'px', left: loginboxLeft + 'px' }).show();

        this.loginboxImage.hide();
        
		this.loadInfo(imageLink.href);

    },

	loadInfo: function(link_href) {
		var myAjax = new Ajax.Request(
		link_href,
	
		{method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);
	},

	submitLogin: function() {
		var erro="";
		if ($('qform').value == "login") {
			if ($('poplog_login').value == "") 	erro += "Digite seu e-mail.\n";
			if ($('poplog_senha').value == "") 	erro += "Digite a senha.\n";
		} else if ($('qform').value == "rec_senha") {
			if ($('popsenha_login').value == "") 	erro += "Digite seu e-mail.\n";
			if ($('popsenha_nascimento').value == "") 	erro += "Digite a data de nascimento.\n";
			else if (!e_data($('popsenha_nascimento').value)) erro += "Digite uma data válida (dd/mm/aaa).\n";
		} else erro="Formulário não identificado.";
		
		if (erro!="") { alert("Corrija o(s) erro(s) abaixo :\n\n"+erro); 
		} else {
        	this.loading.show();
			var myAjax = new Ajax.Request(
			$('pop_log_form').action,
			{method: 'post', parameters: $('pop_log_form').serialize(true), onComplete: this.processInfo.bindAsEventListener(this)}
			);
		}
	},

	processInfo: function(response){
		this.loginboxImage.update(response.responseText);
        this.loading.hide();
        this.loginboxImage.hide();
		this.showImage();
       // this.resizeImageContainer(LoginboxOptions.cont_w, LoginboxOptions.cont_h);
		
	},
	
    //
    //  showImage()
    //  Display image .
    //
    showImage: function() {
        //new Effect.Scale(this.loginboxImage, 100, {scaleX: false, duration: 0, queue: 'front'}); 
        //new Effect.Scale(this.loginboxImage, 100, {scaleY: false, duration: 0}); 
		//this.loginboxImage.update(this.loginboxImage.innerHTML);
        this.loginboxImage.show();
		$('pop_fechar').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
		$('bt_entrar').observe('click', (function(event) { event.stop(); this.submitLogin(); }).bind(this));
		
        this.updateImageList();
		 
       new Effect.Appear(this.loginboxImage, { 
            duration: this.resizeDuration, 
            queue: 'end'
        });
    },
	
    //
    //  resizeImageContainer()
    //
    resizeImageContainer: function(imgWidth, imgHeight) {

        // get current width and height
        var widthCurrent  = this.outerImageContainer.getWidth();
        var heightCurrent = this.outerImageContainer.getHeight();

        // get new width and height
        var widthNew  = (imgWidth  + LoginboxOptions.borderSize * 2);
        var heightNew = (imgHeight + LoginboxOptions.borderSize * 2);

        // scalars based on change from old to new
        var xScale = (widthNew  / widthCurrent)  * 100;
        var yScale = (heightNew / heightCurrent) * 100;

        // calculate size difference between new and old image, and resize if necessary
        var wDiff = widthCurrent - widthNew;
        var hDiff = heightCurrent - heightNew;

        if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
        if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); 

        // if new and old image are same size and no scaling transition is necessary, 
        // do a quick pause to prevent image flicker.
        var timeout = 0;
        if ((hDiff == 0) && (wDiff == 0)){
            timeout = 100;
            if (Prototype.Browser.IE) timeout = 250;   
        }

        (function(){

            this.showImage();
        }).bind(this).delay(timeout / 1000);
    },
    

    //
    //  end()
    //
    end: function() {
        this.loginbox.hide();
        new Effect.Fade(this.overlay, { duration: this.overlayDuration });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
    },

    //
    //  getPageSize()
    //
    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;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	}
}

document.observe('dom:loaded', function () { new Loginbox(); });

