/* Utilidades javascript para incorporar funcionalidades ao DVD da PEME */

scriptTransport = Class.create();
//modeled after XmlHttpRequest http://en.wikipedia.org/wiki/XMLHttpRequest
//functions open, send (setRequestHeader) - variable readyState, status
//
//    * 0 = uninitialized - open() has not yet been called.
//    * 1 = open - send() has not yet been called.
//    * 2 = sent - send() has been called, headers and status are available.
//    * 3 = receiving - Downloading, responseText holds partial data.
//    * 4 = loaded - Finished.

//TODO:
//Removal of <script> nodes?

//
//------------------------------ initialize, open and send ------------------------------------------------------
//

scriptTransport.prototype.initialize = function() {
    this.readyState = 0;
}

scriptTransport.prototype.open = function(method, url, asynchronous) {
    if (method != 'GET')
    alert('Method should be set to GET when using cross site ajax');
    this.readyState = 1;
    this.onreadystatechange();
    this.url = url;
    this.userAgent = navigator.userAgent.toLowerCase();
    this.setBrowser();
    this.prepareGetScriptXS();
}

scriptTransport.prototype.send = function(body) {
    this.readyState = 2;
    this.onreadystatechange();
    this.getScriptXS(this.url);
}

//
//------------------------------ actually do the request: setBrowser, prepareGetScriptXS, callback, getScriptXS ----------
//

scriptTransport.prototype.setBrowser = function(body) {
    scriptTransport.prototype.browser = {
        version: (this.userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
        safari: /webkit/.test(this.userAgent),
        opera: /opera/.test(this.userAgent),
        msie: /msie/.test(this.userAgent) && !/opera/.test(this.userAgent),
        mozilla: /mozilla/.test(this.userAgent) && !/(compatible|webkit)/.test(this.userAgent),
        konqueror: this.userAgent.match(/konqueror/i)
        };
}

scriptTransport.prototype.prepareGetScriptXS = function() {
    if (this.browser.safari || this.browser.konqueror) {
        _xsajax$node = [];
        _xsajax$nodes = 0;
    }
}

scriptTransport.prototype.callback = function() {
    this.status = (_xsajax$transport_status) ? _xsajax$transport_status : 200;
    this.readyState = 4;
    this.onreadystatechange();
}

scriptTransport.prototype.getScriptXS = function() {

    /* determine arguments */
    var arg = {
        'url': null
    };
    arg.url = arguments[0];

    /* generate <script> node */
    this.node = document.createElement('SCRIPT');
    this.node.type = 'text/javascript';
    this.node.src = arg.url;

    /* optionally apply event handler to <script> node for
   garbage collecting <script> node after loading and/or
   calling a custom callback function */
    var node_helper = null;

    if (this.browser.msie) {

        function mybind(obj) {
            temp = function() {
                if (this.readyState == "complete" || this.readyState == "loaded") {
                    return obj.callback.call(obj);
                }
            };
            return temp;
        }
        /* MSIE doesn't support the "onload" event on
           <script> nodes, but it at least supports an
           "onreadystatechange" event instead. But notice:
           according to the MSDN documentation we would have
           to look for the state "complete", but in practice
           for <script> the state transitions from "loading"
           to "loaded". So, we check for both here... */
        this.node.onreadystatechange = mybind(this);

        } else if (this.browser.safari || this.browser.konqueror) {
        /* Safari/WebKit and Konqueror/KHTML do not emit
           _any_ events at all, but we can exploit the fact
           that dynamically generated <script> DOM nodes
           are executed in sequence (although the scripts
           theirself are still loaded in parallel) */
        _xsajax$nodes++;

        var helper = 'var ctx = _xsajax$node[' + _xsajax$nodes + '];' + 'ctx.callback.call(ctx.node);' + 'setTimeout(function () {' + '    ctx.node_helper.parentNode.removeChild(ctx.node_helper);' + '}, 100);';
        node_helper = document.createElement('SCRIPT');
        node_helper.type = 'text/javascript';
        node_helper.appendChild(document.createTextNode(helper));
        _xsajax$node[_xsajax$nodes] = {
            callback: this.callback.bind(this),
            node: this.node,
            node_helper: node_helper
        };
    } else {
        /* Firefox, Opera and other reasonable browsers can
           use the regular "onload" event... */
        this.node.onload = this.callback.bind(this);
    }

    /* inject <script> node into <head> of document */
    this.readyState = 3;
    this.onreadystatechange();
    var head = document.getElementsByTagName('HEAD')[0];
    head.appendChild(this.node);

    /* optionally inject helper <script> node into <head>
   (Notice: we have to use a strange indirection via
   setTimeout() to insert this second <script> node here or
   at least Konqueror (and perhaps also Safari) for unknown
   reasons will not execute the first <script> node at all) */
    if (node_helper !== null) {
        setTimeout(function() {
            var head = document.getElementsByTagName('HEAD')[0];
            head.appendChild(node_helper);
        }, 100);
    }

}

//
//------------------------------ Don't complain when these are called: setRequestHeader and onreadystatechange ----------
//

scriptTransport.prototype.setRequestHeader = function() {
}
scriptTransport.prototype.onreadystatechange = function() {
}

//
//------------------------------- Extend prototype a bit -----------------------
//
Ajax.Request.prototype = Object.extend(Ajax.Request.prototype,{
    initialize: function(url, options) {
        this.setOptions(options);
        this.transport = (!this.options.crossSite) ? Ajax.getTransport() : new scriptTransport;
        this.request(url);
        }    
});

var _xsajax$transport_status = null;
function ligazons() {
    var nav_str = '<div id="services-links"><a href="http://www.mancomun.org/obteraxuda/directoriodeempresas" class="external-white" title="Directorio de empresas" target="_blank">Directorio de empresas</a> &nbsp; &nbsp; <a href="http://www.mancomun.org/obteraxuda/forosdedubidas/" class="external-white" title="Obter Axuda" target="_blank">Obter Axuda</a> &nbsp; &nbsp; <a href="https://forxa.mancomun.org" title="A Forxa" target="_blank" class="external-white">A Forxa</a> &nbsp; &nbsp; <a href="http://wiki.mancomun.org" title="Wiki" target="_blank" class="external-white">Wiki</a> &nbsp; &nbsp; <a href="http://listas.mancomun.org" title="Lista de Correo para Empresas" target="_blank" class="external-white">Lista de Correo</a></div>';
    
    /* Poñer un recurso javascript que non teña código únicamente para comprobar conectividade */
    new Ajax.Request('http://peme.mancomun.org/js/nothing.js', {
        method: 'GET',
        crossSite: true,
        
        onLoading: function() {                        
        },
        
        onSuccess: function(transport) {
            var searchBox = $('head-user').getElementsByTagName('DIV')[0];
            searchBox.innerHTML = nav_str;
            
            transformLogo();
            //new Effect.Appear( 'services-links' );
            //new Effect.Shake( 'services-links' );            
        }
    });
}

var Fabtabs = Class.create();
Fabtabs.prototype = {
   initialize : function(element) {
        this.element = $(element);
        if(this.element) {
            var options = Object.extend({}, arguments[1] || {});
            this.menu = $A(this.element.getElementsByTagName('a'));
            this.menu.each( function(ee){ $(ee.href.match(/#(\w.+)/)[1]).removeClassName('panel-initial');
                                          $(ee.href.match(/#(\w.+)/)[1]).addClassName('panel');} );
            this.show(this.getInitialTab());
            this.menu.each(this.setupTab.bind(this));
        }
    },
    
    setupTab : function(elm) {
        Event.observe(elm,'click',this.activate.bindAsEventListener(this), true);
    },
    
    activate :  function(ev) {
        var elm = Event.findElement(ev, "a");
        Event.stop(ev);
        this.show(elm);        
        this.menu.without(elm).each(this.hide.bind(this));
        
        elm.blur();
    },
    
    hide : function(elm) {
        $(elm).removeClassName('active-tab');
        $(this.tabID(elm)).removeClassName('active-tab-body');
    },
    
    show : function(elm) {
        $(elm).addClassName('active-tab');
        $(this.tabID(elm)).addClassName('active-tab-body');
    },
    
    tabID : function(elm) {
        return elm.href.match(/#(\w.+)/)[1];
    },
    
    getOS : function() {
        var OSName="linux";
        if (navigator.appVersion.indexOf("Win")!=-1) OSName="windows";
        if (navigator.appVersion.indexOf("Mac")!=-1) OSName="mac";
        if (navigator.appVersion.indexOf("X11")!=-1) OSName="unix";
        if (navigator.appVersion.indexOf("Linux")!=-1) OSName="linux";
        if (navigator.appVersion.indexOf("Solaris")!=-1) OSName="solaris";
        
        return( OSName );
    },
        
    getInitialTab : function() {
        if(document.location.href.match(/#(\w.+)/)) {
            var loc = RegExp.$1;
            var elm = this.menu.find(function(value) { return value.href.match(/#(\w.+)/)[1] == loc; });
            return elm || this.menu.first();
        } else {
            //return this.menu.first();
            var ssoo = this.getOS();
            
            var elm = this.menu.find(function(value) { return value.href.match(/#(\w.+)/)[1] == ssoo; });
            return elm || this.menu.first();
        }
    }
}



/* *************************************************************************** */
// FIXME: quitar
function ver_descargas() {
    
    function hiddenAll() {
        var divs = document.getElementsByTagName('DIV');
        var agapito = /\-contenedor/;
        for(var i=0; i<divs.length; i++) {
            if(agapito.test(divs[i].id)) {
                divs[i].style.display = 'none';
            }
        }
    }

    hiddenAll();

    function toggleDiv() {
      hiddenAll();
      var cadea = this.href.sub('#', ' ');
      var reg = $w(  cadea.toString() );
      var nome = reg[1];
      var divs = document.getElementsByTagName('DIV');
      var agapito =new RegExp(nome + '\-contenedor', 'i');
      for(var i=0; i<divs.length; i++) {
        if(agapito.test(divs[i].id)) {        
            if(divs[i].style.display == '') {
                divs[i].style.display = 'none';
            } else {
                divs[i].style.display = '';            
            }
        }
      }
      
      return false;
    }

    var ligazons = document.getElementsByTagName('A');
    var reg = /\#([a-z]*)$/;
    for(var i=0; i<ligazons.length; i++) {
        if(reg.test(ligazons[i].href)) {
            ligazons[i].onclick = toggleDiv;
        }
    }
    
}

function transformLogo() {
    var liga = $('head-logo-mancomun').getElementsByTagName('img')[0].getAttribute('src');
    //var path = liga.href.match('')[0];
    //$('head-logo-mancomun').innerHTML = '<a href="http://www.mancomun.org/" title="Mancomun.org"><img alt="Mancomun.org Logo" src="../index/logo-mancomun.png" alt="" /></a>';
    
    var results = liga.match(/^([\.\/]+)/);    
    $('head-logo-mancomun').innerHTML = '<a href="http://www.mancomun.org/" title="Mancomun.org"><img alt="Mancomun.org Logo" src="'+results[0]+'index/logo-mancomun.png" alt="" /></a>';    
}

function init() {
    ligazons();
    ver_descargas();
    
    var urchin = '<script src="http://www.google-analytics.com/urchin.js" type="text/javascript" onload=""></script><script type="text/javascript">_uacct = "UA-855796-8";urchinTracker();</script>';
    
    // Para ter pestanas nos sistemas operativos
    try {
        new Fabtabs('tabs');
    } catch(e) {
        //console.log(e);
    }
}

Event.observe(window, 'load', function() {
    init();
});
