/*Library js vsm */
if(typeof vsm == "undefined") var vsm = {};

vsm.attachEvent = function(obj, eventname, action) {
     if (obj.addEventListener) {
        if(eventname.substring(0,2) == 'on'){ eventname = eventname.substring(2);}
        obj.addEventListener(eventname, action, false); 
    } else if (obj.attachEvent) {
        if(eventname.substring(0,2) != 'on'){ eventname = 'on'+eventname;}
        obj.attachEvent(eventname, action);
    }
};

vsm.detachEvent = function(obj, eventname, action) {
    if (obj.removeEventListener) {
        if(eventname.substring(0,2) == 'on'){ eventname = eventname.substring(2);}
        obj.removeEventListener(eventname, action, false); 
    } else if (obj.detachEvent) {
        if(eventname.substring(0,2) != 'on'){ eventname = 'on'+eventname;}
        obj.detachEvent(eventname, action);
    }
};

vsm.loadScript = function(file, action) {
    var h = document.getElementsByTagName('SCRIPT');
    var s= h.length;
    var f=false;
    for(var i=0; i<s;i++){
        var itm= h[i];
        if (itm.getAttribute("src") && itm.getAttribute("src") == file){f= true;i=s;}
    }
    if (!f){
        s = document.createElement('SCRIPT');
        s.type = 'text/javascript';
        s.src = file;
        if (typeof s.onreadystatechange =='object' ){
            s.onreadystatechange = function() {if (s.readyState == 'loaded' || s.readyState =='complete'){vsm.eval(action);} };   
        }else{
            s.onload = function (){vsm.eval(action);};
        }
        h = document.getElementsByTagName('head');
        if (h[0]){ h[0].appendChild(s);}
    }else{vsm.eval(action);}
};


vsm.loadCss = function(file) {
    var h = document.getElementsByTagName('LINK');
    var s= h.length;
    var f=false;
    for(var i=0; i<s;i++){
        var itm= h[i];
        if (itm.getAttribute("href") && itm.getAttribute("href") == file){f= true;i=s;}
    }
    if (!f){
        s = document.createElement('LINK');
        s.rel = 'stylesheet';
        s.href = file;
        h = document.getElementsByTagName('head');
        if (h[0]){ h[0].appendChild(s);}
    }
};

vsm.ajaxCall = function(url, callback_function, error_function, method, plainform, http_object){
    if (typeof http_object !== 'object') {
        if (window.XMLHttpRequest) { 
            http_object = new XMLHttpRequest(); 
        } else if (window.ActiveXObject) { 
            try { 
                http_object = new ActiveXObject("Msxml2.XMLHTTP"); 
            } catch (e) { 
                try { 
                    http_object = new ActiveXObject("Microsoft.XMLHTTP"); 
                } catch (er) {} 
            } 
        } 
    }
    if (!http_object) {return false;}     
    var data = null;
    if (plainform){data=plainform;}
    if(!method){ method='GET';} 
    http_object.open(method, url, true);
    if(method.toUpperCase()=='POST' && plainform){ http_object.setRequestHeader('Content-Type','application/x-www-form-urlencoded');}
    http_object.onreadystatechange = function() {
        try { 
            if (http_object.readyState == 4) { 
                if (http_object.status == 200) {
                    var err = http_object.getResponseHeader("error");
                    var p; var a; var f;
                    if (err &&  err.length > 0) {
                        vsm.eval(error_function,err);
                    } else{
                        vsm.eval(callback_function,http_object.responseText);   
                    }
                }else{ 
                    if (typeof vsmdebug != 'undefined'){
                        alert('There was a problem with the request. (Code: ' + http_object.status + ')'); 
                    }
                } 
            } 
        } catch (eerr) {
            if (typeof vsmdebug != 'undefined'){
                alert('Exception: ' + eerr.description); 
            }
        }
    };
    http_object.send(data); 
    return http_object;
};

vsm.ajaxForm = function(formObj, callback_function, error_function, http_object){
    if(formObj) {
        var method = 'GET';
        if(formObj.method) {
            method = formObj.method.toUpperCase();
        } 
        var data= '';
        for (var i = 0; i < formObj.length; i++) {
            var fieldObj = formObj[i];
            switch(fieldObj.type) {
                case 'checkbox':
                case 'radio':
                    if (fieldObj.checked) {data+= fieldObj.name + '=' + encodeURIComponent(fieldObj.value) + '&';}
                    break;
                case 'select-one':
                    data+= fieldObj.name + '=' + encodeURIComponent(fieldObj.options[fieldObj.selectedIndex].value) + '&';
                    break;
                case 'reset':
                case 'submit':
                case 'button':
                    break;
                default: 
                    data+= fieldObj.name + '=' + encodeURIComponent(fieldObj.value) + '&';
                    break;
            }
        }
        if(data.length >0) {data = data.slice(0, -1);} 
        var url = formObj.action;
        if(method.toUpperCase()=='GET' && data) {
            url = url+'?'+data;
            data = null;
        }
        return vsm.ajaxCall(url,callback_function,error_function,method,data,http_object);
    }else{
        return false;
    }
};

vsm.opacity = function (obj, opacity) {
    // Si opacity es 1 en lugar de desaparecer (display:none) mantiene el espacio en la página (visibility:hidden)
    var obj = vsm.object(obj);
    if(obj) {
        var sty = obj.style;
        switch(opacity) {
        case 0: sty.display = 'none'; break;
        case 1: sty.visibility = 'hidden'; break;
        default:
            opacity = Math.floor(opacity);
            sty.display = '';
            sty.visibility = 'visible'; 
            sty.opacity = (opacity/100); 
            sty.MozOpacity = (opacity/100); 
            sty.KhtmlOpacity = (opacity/100); 
            if(sty.filter) sty.filter = sty.filter.replace(/alpha\([^)]*\)/, '').replace(/^\s*|\s*$/g,"");
            if(opacity < 100) sty.filter+= " alpha(opacity="+opacity+")";
        }
    }
};

vsm.effects = {};

vsm.effects.fade = function(obj, opacity, functionatend, steps) {
    var fps=30;
    var data = [];
    var index = 0;
    var runningproc = false;
    var time =0;
    var steped=0;
    obj = vsm.object(obj);
    if(obj) {
        var id = obj.id;
        if(currentopacity == opacity) return;
        var currentopacity = vsm.currentStyle(obj,'filter');
        if (currentopacity =='none') {
            currentopacity =vsm.currentStyle(obj,'opacity')*100;    
        }else{
            currentopacity  = (currentopacity) ? currentopacity.replace('alpha(opacity=','').replace(')','')*1:100;
        }
        if(!functionatend) functionatend = null;
        if(!steps || isNaN(steps)) {steps = 10;}
        index++;
        if (data[index]){
          delete data[index];  
        } 
        data[index] = {"id":id,"current":currentopacity, "end": opacity, "step":((opacity - currentopacity)/steps), "trigger":functionatend, "fading":true};

        vsmSetOpacity(id, currentopacity);
        var i=0;
        for(var key in data) i++;
        if(i==1 && !runningproc) {
            process();
        }
    }
    function process () {
        if (runningproc)return; 
        var d = new Date();  
        var st = d.getTime();
        for(var key in data) {
            runningproc = true;
            var fd = data[key];
            var obj = document.getElementById(fd.id);
            var endfade = false;
            if(obj) {
                var step = fd.step;
                var opacity = fd.current + step;
                if(step < 0) {
                    if(opacity <= fd.end) endfade = true;
                } else {
                    if(opacity >= fd.end) endfade = true;
                }
                if(endfade) {
                    vsm.opacity(obj, fd.end);
                    var trigger = fd["trigger"];
                    delete  data[key];
                    if(trigger) {
                        if(trigger.indexOf('(') == -1) trigger+='()';
                        eval(trigger);
                    }
                } else {
                    vsm.opacity(obj, opacity);
                    fd["current"] = opacity;
                }
            } else {

                delete data[key];
            }
        }
        var s =data.length;    
        runningproc = false;
        if(s>0) {
            d = new Date();
            time += d.getTime()+(1000/fps)-st;
            steped++; 
            var rfps = time/steped;
            rfps = (rfps > fps) ? fps: rfps;
            if (time >1000){
                steped=0;
                time=0;   
            }
            setTimeout(process, 1000/rfps);
        }
    }
};

vsm.eval = function(action){
    var args = Array.prototype.slice.call(arguments,1);
    if (typeof action  == 'string'){
         var fnc= action.match(/([\w\.]*)?\(/); 
         fnc = (fnc) ? fnc[1]: action;
         if (!fnc) return;
         if (action.substring(action.length-1) == ")"){
            action = action.substring(fnc.length+1,action.length-1).split(",");
            for (var i=0;i<action.length && (action[i] = eval(action[i]));i++);
            args = args.concat(action);
         }
         var ns= fnc.split(".");     
         fnc= ns.pop(); 
         var action= window;
         for (i=0; i < ns.length && (action = action[ns[i]]); i++);
         action[fnc].apply(action, args);  
    }else if (typeof action  == 'function'){
        action.apply(action,args);
    }
};

vsm.currentStyle = function(obj, property) {
    // Devuelve el valor actual de una propiedad de estilo. Independientemente de si fue asignada en el atributo style o como clase en <style> o CSS
    var x = vsm.object(obj);
    if (x.currentStyle)
        var y = x.currentStyle[property];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null)[property];
    return y;
};

vsm.currentOpacity = function (obj, defaultOpacity) {
    return defaultOpacity;
};

vsm.object = function(obj) {
    // Devuelve un objeto del DOM determinado por obj que puede ser el objeto en si mismo o el id.
    // Devuelve undefined si obj no es un objeto o un id de objeto válido.
    // Además si el objeto no tiene id le asigna un id aleatorio.
    var obj = (typeof(obj) == 'object') ? obj : document.getElementById(obj);  
    if(obj) {
        if(!obj.id) obj.id = 'vsm-'+(parseInt(Math.random()*10000000000));
        return obj;
    } else {
        return undefined;
    }
};

vsm.checkObject = function(obj, vsmtype) {
    var obj = vsm.object(obj);
    if(obj != undefined && obj.getAttribute('data-vsmel') != vsmtype) alert('VSM Element Error in '+((vsm.checkObject.caller.name)?vsm.checkObject.caller.name:'undefined function')+': "'+obj.id+'" must type "'+vsmtype+'" (vsmel="'+vsmtype+'")'); 
    return obj;
}

vsm.key = function(e) {
    var evt=(e)?e:(window.event)?window.event:null;
    if(evt) return ((evt.charCode)?evt.charCode:((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0)));
}

vsm.trim = function(s) {
    return s.replace(/^\s*|\s*$/g,"");
}

vsm.capitalize = function(s) {
    return s.charAt(0).toUpperCase()+s.slice(1);
}

vsm.findPos = function(obj) {
    obj = vsm.object(obj);
    if( typeof( obj.offsetParent ) != 'undefined' ) {
        for( var posX = 0, posY = 0; obj; obj = obj.offsetParent ) {
            posX += obj.offsetLeft;
            posY += obj.offsetTop;
        }
    }
    return {x:posX,y:posY};
}

vsm.browser= (function(){
  var ua= navigator.userAgent, tem;
  var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
  var N = M[1]||navigator.appName,s={};s.name=N.toLowerCase();s.version =(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) ? tem[1]:M[2]; 
  s.OS =(M && (tem= ua.match(/(macintosh|linux|windows|ipad|iphone|ipod)/i))!= null) ? tem[1].toLowerCase():"unknown"; 
  s[s.name] = s.version;
  return s;
})();

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin !== 0){ return null;}
  } else{
    begin += 2;
  }
  var end = document.cookie.indexOf(";", begin);
  if (end == -1){
    end = dc.length;
  }
  return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        "; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

function writeFlash(src,w,h) {
    var args = arguments;
    var callArgs = "'codebase','http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','"+ w + "','height','" + h + "','src','" + src + "','movie','" + src +"',";
    for (var i=3; i < args.length; i++){
        callArgs += "'" + args[i] + "',";
    }
    if (callArgs.indexOf('quality')<0){callArgs += "'quality','high',";}

    if (callArgs.indexOf('bgcolor')<0){callArgs += "'bgcolor','#ffffff',";}

    if (callArgs.indexOf('wmode')<0){callArgs += "'wmode','transparent',";}
    callArgs=callArgs.substr(0,callArgs.length-1);
    eval("AC_FL_RunContent("+callArgs+")");
}

var vsmStrmImage = [];
function vsmFindPos( oElement ) {
  if( typeof( oElement.offsetParent ) != 'undefined' ) {
    for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
      posX += oElement.offsetLeft;
      posY += oElement.offsetTop;
    }
    return [ posX, posY ];
  } else {
    return [ oElement.x, oElement.y ];
  }
}
function vsmImageStreaming(e,d){
    if (!d) d =document;
    var y = d.getElementsByTagName('img');
    var ch = document.documentElement.clientHeight;
    var st = (document.documentElement.scrollTop) ? document.documentElement.scrollTop: document.body.scrollTop;
    for (var i=0;i<y.length;i++){
        var vsmsrc = y[i].getAttribute('vsmsrc');
        var l = y[i].src.length;
        if (vsmsrc && y[i].src.substring(l-12) == '/lib/1x1.gif'){
            var pos = vsmFindPos(y[i]);
            var pos2 = y[i].offsetHeight+pos[1]; 
            if ((pos[1] > st-200 && pos[1] < ch+st+200) || (pos2 > st-200 && pos2 < ch+st+200)){
                if(vsmStrmImage[vsmsrc]  === undefined){
                    vsmStrmImage[vsmsrc] = new Image();
                    vsmStrmImage[vsmsrc].src = vsmsrc;
                }
                if (vsmStrmImage[vsmsrc].complete){
                    y[i].src = vsmsrc;
                }else{
                    vsmStrmImage[vsmsrc].obj = y[i];
                    vsmStrmImage[vsmsrc].onload =function(){this.obj.src = this.src;};
                }
            }
        }
    }
}

var vsmActivePanel;
function vsmHidePanel() {
    if(vsmActivePanel) {
        vsmActivePanel.style.display = 'none';
        vsmActivePanel = null;
    }
}

function vsmShowPanel(obj) {
    if(typeof(obj) != 'object'){ obj = document.getElementById(obj);}
    if(obj) {
        if(vsmActivePanel){ vsmHidePanel(vsmActivePanel);}
        vsmActivePanel = obj;
        vsmActivePanel.style.display = '';
    }
}

function vsmpLoginKeys(e) {
    e = (window.event) ? window.event:e;
    if(e.keyCode == 86 && e.ctrlKey && e.shiftKey) {  // Analiza si se presiona CTRL-SHIFT-V para mostrar el diálogo de login o ESC para cerrarlo
        if(typeof vsmversion3!='undefined') {
            if(typeof vsmLoginLoaded == 'function')    {
                vsmCreateModalWindow(500, 300, '/panel/session/login/loginForm.php', 'Cargando...', 'vsmLoginLoaded');
            } else {
                vsm.loadScript('/panel/lib/js/common.js', "vsmCreateModalWindow(500, 300, '/panel/session/login/loginForm.php', 'Cargando...', 'vsmLoginLoaded')");
            }
        } else {
            window.open("/admin/session/login/login.php?popup=1", "popuplogin", "width=560,height=320,resize=no,status=no,toolbars=no,left="+(screen.availWidth/2-560/2)+",top="+(screen.availHeight/2-330/2));
        }
        return false;
    } else if (e.keyCode == 27) {
        if(typeof vsmCloseModalWindow == 'function'){ vsmCloseModalWindow(); }
        return false;
    }
}
if(typeof vsmloggedin=='undefined' && typeof vsmloginkeys!='undefined'){ vsm.attachEvent(document, 'keydown', vsmpLoginKeys);}// Si no está logueado agrega el evento del CTRL-SHIFT-V y ESC para la ventana de login

function vsmWalk(objid, x1, y1, w1, h1, x2, y2, w2, h2, steps, speed, functionatend, functionstep, step) {
    // Animación de objid desde las coordenadas 1 a las coordenadas2 teniendo en cuenta steps y speed
    // El final llama a functionatend(que debería ocultar este objeto y mostrar uno del tamaño w2, h2)
    // El último parámetro no se pasa. Es interno de la función
    if(!step){ step =0;}
    if(!functionstep) {functionstep = 'void(0)';}
    if(!functionatend) {functionatend = 'void(0)';}
    var obj = document.getElementById(objid);
    if(x1==null) x1 = obj.offsetLeft;
    if(y1==null) y1 = obj.offsetTop;
    if(w1==null) w1 = obj.offsetWidth;
    if(h1==null) h1 = obj.offsetHeight;
    
    if(w2==null) {
        w2 = obj.getAttribute('vsmwalkoriginalwidth');
        if(w2 == null) obj.offsetWidth;
    } else {
        if(obj.getAttribute('vsmwalkoriginalwidth')== null) obj.setAttribute('vsmwalkoriginalwidth', w1);  
    }

    if(h2==null) {
        h2 = obj.getAttribute('vsmwalkoriginalheight');
        if(h2 == null) obj.offsetHeight;
    } else {
        if(obj.getAttribute('vsmwalkoriginalheight')== null) obj.setAttribute('vsmwalkoriginalheight', h1);  
    }

    if (x1 && x2){
        var valuex = Math.round(x1+((x2-x1)/steps)*step);
        obj.style.left = valuex+'px';
    }
    if (y1 && y2){
        var valuey = Math.round(y1+((y2-y1)/steps)*step);
        obj.style.top =  valuey+'px';
    }
    if (w1 && w2){
        var valuew = Math.round(w1+((w2-w1)/steps)*step);
        obj.style.width = valuew+'px';
    }
    if (h1 && h2){
        var valueh = Math.round(h1+((h2-h1)/steps)*step);
        obj.style.height = valueh+'px';
    }
    obj.style.display = '';
    if(step < steps) {
        eval(functionstep);
        setTimeout('vsmWalk(\''+objid+'\','+x1+','+y1+','+w1+','+h1+','+x2+','+y2+','+w2+','+h2+','+steps+','+speed+',\''+functionatend.replace(/\'/g, '\\\'')+'\',\''+functionstep.replace(/\'/g, '\\\'')+'\','+(step+1)+')', speed);
    } else {
        if (x2){obj.style.left = x2+'px';}
        if (y2){ obj.style.top =  y2+'px';}
        if (w2){obj.style.width = w2+'px';}
        if (h2){obj.style.height = h2+'px';}
        eval(functionatend);
    }
}

/* OLD Compatibility */
function vsmAttachEvent(obj, eventname, action) {
    vsm.attachEvent(obj,eventname,action);
}

function vsmLoadScript(file, action) {
    return vsm.loadScript(file,action);
}

function vsmHttpRequest(url, callback_function, error_function, response_xml, formid, method, plainform) { 
    if (formid) {
        vsm.ajaxForm(document.getElementById(formid), callback_function, error_function);
    } else {
        vsm.ajaxCall(url, callback_function, error_function, method, plainform);
    }
}

function vsmAjaxForm(formObj, callback_function, error_function, response_xml) { 
     vsm.ajaxForm(formObj, callback_function, error_function);  
}

function vsmSetOpacity(obj, opacity) {
    vsm.opacity(obj, opacity);
}

function vsmFadeIn(obj, finalopacity, functionatend, steps) {
    if(!finalopacity || isNaN(finalopacity)) finalopacity = 100;
    vsm.effects.fade(obj, finalopacity, functionatend, steps);
}

function vsmFadeOut(obj, finalopacity, functionatend, steps) {
    if(!finalopacity || isNaN(finalopacity)) finalopacity = 0;
    vsm.effects.fade(obj, finalopacity, functionatend, steps);
}
