/*
 Created By: Chris Campbell
 Website: http://particletree.com
 Date: 2/1/2006

 Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
 */

/*-------------------------------GLOBAL VARIABLES------------------------------------*/


var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
    if (checkIt('konqueror')) {
        browser = "Konqueror";
        OS = "Linux";
    }
    else if (checkIt('safari')) browser = "Safari";
    else if (checkIt('omniweb')) browser = "OmniWeb";
    else if (checkIt('opera')) browser = "Opera";
    else if (checkIt('webtv')) browser = "WebTV";
    else if (checkIt('icab')) browser = "iCab";
    else if (checkIt('msie')) browser = "Internet Explorer";
    else if (!checkIt('compatible')) {
        browser = "Netscape Navigator";
        version = detect.charAt(8);
    }
    else browser = "An unknown browser";

    if (!version) version = detect.charAt(place + thestring.length);

    if (!OS) {
        if (checkIt('linux')) OS = "Linux";
        else if (checkIt('x11')) OS = "Unix";
        else if (checkIt('mac')) OS = "Mac";
        else if (checkIt('win')) OS = "Windows";
        else OS = "an unknown operating system";
    }
}

function checkIt(string) {
    place = detect.indexOf(string) + 1;
    thestring = string;
    return place;
}

/*-----------------------------------------------------------------------------------------------*/

jQuery(window).load(initialize);
jQuery(window).load(getBrowserInfo);

//Class.create();

// Definição de classe
function lightbox() {
    return this.initialize(arguments[0]);
}

lightbox.prototype = {
    yPos : 0,
    xPos : 0,
    initialize: function(ctrl) {
        if (ctrl != null) {
            this.content = ctrl.href;
            jQuery(ctrl).click({ obj: this }, this.activate);
            ctrl.onkeypress = function() {
                return false;
            };
        }
    },

    // Turn everything on - mainly the IE fixes
    activate: function(e) {
        var obj;
        if (typeof e === 'undefined') {
            obj = this;
        } else {
            var obj = e.data.obj;
            e.preventDefault();
        }

        if (browser == 'Internet Explorer') {
            obj.getScroll();
            obj.prepareIE('100%', 'hidden');
            obj.setScroll(0, 0);
        }

        obj.hideSelects('hidden');

        jQuery('#lightbox').removeClass().addClass("loading");
        obj.displayLightbox("block");

    },

    // Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
    prepareIE: function(height, overflow) {
        bod = document.getElementsByTagName('body')[0];
        bod.style.height = height;
        bod.style.overflow = overflow;

        htm = document.getElementsByTagName('html')[0];
        htm.style.height = height;
        htm.style.overflow = overflow;
    },

    // In IE, select elements hover on top of the lightbox
    hideSelects: function(visibility) {
        selects = document.getElementsByTagName('select');
        for(i = 0; i < selects.length; i++) {
            selects[i].style.visibility = visibility;
        }
        object = document.getElementsByTagName('object');
        for(i = 0; i < object.length; i++) {
            object[i].style.visibility = visibility;
        }
        embed = document.getElementsByTagName('embed');
        for(i = 0; i < embed.length; i++) {
            embed[i].style.visibility = visibility;
        }

    },

    // Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
    getScroll: function() {
        if (self.pageYOffset) {
            this.yPos = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            this.yPos = document.documentElement.scrollTop;
        } else if (document.body) {
            this.yPos = document.body.scrollTop;
        }
    },

    setScroll: function(x, y) {
        window.scrollTo(x, y);
    },

    /*displayLightbox: function(display){
     $('overlay').style.display = display;
     $('lightbox').style.display = display;
     if(display != 'none') this.loadInfo();
     },*/


    displayLightbox: function(display) {
        document.getElementById('lightboxFixed').style.display = display;
        if (display != 'none')
            this.loadInfo();
    },


    // Begin Ajax request based off of the href of the clicked linked
    loadInfo: function() {
        var myAjax = jQuery.ajax({
            url: this.content,
            type: 'POST',
            context: this,
            success: function(data) {
                this.processInfo(data);
            }
        });
    },

    // Display Ajax response
    processInfo: function(response) {

        var newElem = jQuery('<div id="lbContent">'+response+'</div>');

        newElem.insertBefore('#lbLoadMessage');

        jQuery('#lightbox').removeClass().addClass('done');

        this.actions();

    },

    // Search through new links within the lightbox, and attach click event
    actions: function() {
        var lbActions = jQuery('.lbAction');

        lbActions.filter('form').bind('submit', function(e) {
            e.preventDefault();
            return false;
        });

        lbActions.not('form').bind('click', { obj: this }, function(e) {
            e.preventDefault();
            var obj = e.data.obj;
            var lbAxn = jQuery(e.target).closest('.lbAction');
            obj[lbAxn.attr('rel')](obj, lbAxn);
        });

        jQuery('#overlay').bind('click', { obj: this }, function(e) {
            e.preventDefault();
            var obj = e.data.obj;
            obj.deactivate(obj);
        });
    },

    // Example of creating your own functionality once lightbox is initiated
    postdata: function(obj, elem) {
        var ObjetoForm = jQuery(elem).closest('form').get(0);

        //Captura valores dos campos do form e monta a query string
        data = "ctl.php?" + create_request_string(ObjetoForm.name);
        //Valida campos do formulario
        var MsgErro = '';
        if (ObjetoForm.rev) {
            var valida = ObjetoForm.rev.split(' ');
            for (i = 0; i < valida.length; i++) {
                feedback = eval('document.' + ObjetoForm.name);
                MsgErro = MsgErro + TestaCampoText(ObjetoForm.name, valida[i], feedback[valida[i]].title);
            }
        }
        if (MsgErro == '') {
            jQuery('#lbContent').remove();
            jQuery('#lightbox').attr('class', "loading");

            var myAjax = jQuery.ajax({
                url: data,
                type: 'POST',
                context: this,
                success: function(data) {
                    this.processInfo(data);
                }
            }); /*new Ajax.Request(
                    data,
            {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
                    );*/
        } else {
            alert(MsgErro);
        }

    },


    insert: function(e, obj) {

        var link = obj.attr('href');
        jQuery('#lbContent').remove();
        jQuery('#lightbox').removeClass().addClass("loading");

        var myAjax = jQuery.ajax({
            url: link,
            type: 'POST',
            context: this,
            success: function(data) {
                this.processInfo(data);
            }
        });
    },

    // Example of creating your own functionality once lightbox is initiated
    deactivate: function(obj) {
        jQuery('#lbContent').remove();

        if (browser == "Internet Explorer") {
            obj.setScroll(0, this.yPos);
            obj.prepareIE("auto", "auto");
        }

        obj.hideSelects("visible");
        obj.displayLightbox("none");
    }
};

/*-----------------------------------------------------------------------------------------------*/

// Onload, make all links that need to trigger a lightbox active
function initialize() {
    addLightboxMarkup();
    var lbox = jQuery('.lbOn');
    lbox.each(function() {
        valid = new lightbox(this);
    });
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
/*function addLightboxMarkup() {
 bod 				= document.getElementsByTagName('body')[0];
 overlay 			= document.createElement('div');
 overlay.id		= 'overlay';
 lb					= document.createElement('div');
 lb.id				= 'lightbox';
 lb.className 	= 'loading';
 lb.innerHTML	= '<div id="lbLoadMessage">' +
 '<p>Loading</p>' +
 '</div>';
 bod.appendChild(overlay);
 bod.appendChild(lb);
 }*/

function addLightboxMarkup() {
    // bod = document.getElementsByTagName('body')[0];
    var $body = jQuery('body');

    var lightboxFixed = jQuery('<div />').attr('id', 'lightboxFixed');
    var overlay = jQuery('<div />').attr('id', 'overlay');
    var lb = jQuery('<div />').attr('id', 'lightbox').addClass('loading');
    lb.html('<div id="lbLoadMessage"><img src="/img/lightbox-loader.gif" align="center"></div>');


    overlay.appendTo(lightboxFixed);
    lb.appendTo(lightboxFixed);
    lightboxFixed.appendTo('body');
}


function create_request_string(formName) {
    var theForm = eval('document.' + formName);

    var reqStr = "";

    for (i = 0; i < theForm.elements.length; i++) {
        var isFormObject = false;

        switch (theForm.elements[i].tagName) {
            case "INPUT":

                switch (theForm.elements[i].type) {
                    case "text":
                    case "password":
                    case "hidden":
                        reqStr += theForm.elements[i].name + "=" + encodeURIComponent(theForm.elements[i].value);
                        isFormObject = true;
                        break;

                    case "checkbox":
                        if (theForm.elements[i].checked) {
                            reqStr += theForm.elements[i].name + "=" + theForm.elements[i].value;
                        } else {
                            reqStr += theForm.elements[i].name + "=";
                        }
                        isFormObject = true;
                        break;

                    case "radio":
                        if (theForm.elements[i].checked) {
                            reqStr += theForm.elements[i].name + "=" + theForm.elements[i].value;
                            isFormObject = true;
                        }
                }
                break;

            case "TEXTAREA":

                reqStr += theForm.elements[i].name + "=" + encodeURIComponent(theForm.elements[i].value);
                isFormObject = true;
                break;

            case "SELECT":
                var sel = theForm.elements[i];
                for (var z = 0; z < sel.options.length; z++) {
                    if (sel.options[ z ].selected) {
                        reqStr += sel.name + "=" + sel.options[z].value;
                        isFormObject = true;
                        reqStr += "&";
                    }
                }
                break;
        }

        if ((isFormObject) && ((i + 1) != theForm.elements.length)) {
            reqStr += "&";
        }

    }

    return reqStr;
}




