try {if (top.location.hostname != self.location.hostname) throw 1;} catch (e) {top.location.href = self.location.href;}

function deleteChildNodes(element) {
	var children = element.childNodes, i, num;
	for (i = 0, num = children.length; i < num; ++i) {
		element.removeChild(children[i]);
	}
}

// cook the cookies [+]
var Cookies = {
    init: function () {
        var allCookies = document.cookie.split('; ');
        for (var i=0;i<allCookies.length;i++) {
            var cookiePair = allCookies[i].split('=');
            this[cookiePair[0]] = cookiePair[1];
        }
    },

    read:  function (name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    },

    create: function (name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*86400000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=" + (window._cookiesPath ? window._cookiesPath : '/') + "; domain=" + (window._cookiesDomain ? window._cookiesDomain : '220.ro');
        this[name] = value;
    },

    erase: function (name) {
        this.create(name,'',-1);
        this[name] = undefined;
    }
};
Cookies.init();
// cook the cookies [-]


/* current view [+]*/
var current_view="";

switchView=function(event){
    className=Event.element(event).readAttribute('title').toLowerCase();
    if(className=='tabel'){
        $$('.container_filme').each(function(dv) {
            dv.removeClassName('view_lista');
            dv.addClassName('view_tabel');
        });
    }
    else {
        $$('.container_filme').each(function(dv) {
            dv.removeClassName('view_tabel');
            dv.addClassName('view_lista');
        });
    }
    current_view=className;
    $('current_view').update(current_view)
}


document.observe("dom:loaded", function() {
    current_view=$('current_view') ? $('current_view').innerHTML : "";

    $$('a.view-switcher').each(function(avs){

        Event.observe(avs,'mouseover', function(event){
            c_elem=Event.element(event);
            $('current_view').update(c_elem.readAttribute('title').toLowerCase())
        })

        Event.observe(avs,'mouseout', function(event){
            c_elem=Event.element(event);
            $('current_view').update(current_view)
        })
        Event.observe(avs,'click', switchView);

    })

});
/* current view [-]*/

document.observe("dom:loaded", function() {
if($('expand-switcher')){
        Event.observe('expand-switcher','click', switchExpand);
    }
});

switchExpand=function(event){
    var elm = $('expand-switcher');
    var elm1 = $('new_box');
    className = elm1.hasClassName('expand');
    if(className){
        if(elm.childNodes[0]){
            elm.removeChild(elm.childNodes[0]);
        }
        var image = Builder.node('img',{src: WEB_BASE+"img/plus.jpg", alt:"+"});
        elm.appendChild(image);
        elm.title = 'unexpand';
        elm1.removeClassName('expand');
        elm1.addClassName('unexpand');
        Cookies.create('fze','unexpand',0);
    }
    else {
        elm1.removeClassName('unexpand');
        elm1.addClassName('expand');
        if(elm.childNodes[0]){
            elm.removeChild(elm.childNodes[0]);
        }
        var image = Builder.node('img',{src: WEB_BASE+"img/minus.jpg", alt:"-"});
        elm.appendChild(image);
        elm.title = 'expand';
        Cookies.create('fze','expand',0);
    }

}

/*[+] filmele zilei exapand*/

/*[-] filmele zilei exapand*/

/* Functie care initializeaza ajax autocompleter pt useri*/
getUserId = function(text, li) {
    $(text.id+'_id').value=li.id;
}

acSuccess=function(req){
    if(req.responseText.strip()=='not found'){
        $(req.request.options.indicator).hide();
    }
}

document.observe("dom:loaded", function() {
    if($$('.autocomplete-user') != undefined)
    {
        ac_users=$$('.autocomplete-user').each(function(ac){
            new Ajax.Autocompleter(ac, ac.id+"_options", SITE_BASE + "ajax.php?module=mesagerie&action=getUsers", {
                paramName: "value",
                minChars: 2,
                indicator: ac.id+'_indicator',
                //afterUpdateElement:getUserId,
                onSuccess:acSuccess
            });
        })
    }
});

/*START  - verifica containerul boom daca are content [vezi lista]*/
/*
document.observe('dom:loaded', function() {
    $$('.boom_container').each(function(item) {
        var hasChildren = item.select('div','table','object','img','a').length > 0;
        if(!hasChildren) {
            try {
                $$('.'+item.id).each(function(related_items) {related_items.hide();});
            }
            catch(e) {;}
        };
    });
});
*/
/*END  - verifica containerul boom daca are content*/

/* Check - Uncheck trigger*/

var CheckUncheckTrigger=Class.create({
    initialize:function(cu_trigger){
        this.cu_trigger=cu_trigger
        this.observeTrigger();
    },

    observeTrigger:function(){
        Event.observe(this.cu_trigger, 'click', this.checkUncheck.bindAsEventListener(this))
    },

    checkUncheck:function(event){
        i=0;
        while($(this.cu_trigger.id+'-'+i)!=undefined){
            ckb=$(this.cu_trigger.id+'-'+i);
            ckb.checked=this.cu_trigger.checked;
            // verific daca e intr-un tabel cu select row
            srt=ckb.up('table.select-row-table');
            if(srt!=undefined){
                ckb_row=ckb.up('tr');
                if(ckb_row!=undefined && ckb.checked)
                ckb_row.addClassName('row-selected');
                else
                ckb_row.removeClassName('row-selected');
            }

            i++;
        }
    }
})

document.observe("dom:loaded", function() {
    $$('.check-uncheck-trigger').each(function(cu_trigger){
        new CheckUncheckTrigger(cu_trigger)
    })
})

/* Checkbox-uri care ingalbenesc linia curenta*/
selectRow=function(event){
    elem=Event.element(event);
    if(elem.tagName != "A" && event.findElement('a')==undefined){
        cb_row=elem.up('tr');
        cb=cb_row.down('input');
        if(!cb.hasClassName('check-uncheck-trigger')){
            if(cb != elem)
            cb.checked=!cb.checked;
            if(cb_row != undefined && cb.checked==true)
            cb_row.addClassName('row-selected');
            else
            cb_row.removeClassName('row-selected');
        }
    }
}

rowOverAndOut=function(event){
    Event.stop(event);
    t_row=event.findElement('tr');
    tabel=event.findElement('table');
    $A(tabel.getElementsByTagName('tr')).invoke('removeClassName','row-over');
    t_row.addClassName('row-over');
}

document.observe("dom:loaded", function() {
    $$('.select-row-table').each(function(s_table){
        Event.observe(s_table, 'click', selectRow);
        Event.observe(s_table, 'mousemove', rowOverAndOut);
        Event.observe(s_table, 'mouseout', function(event){
            Event.stop(event);
            tabel=event.findElement('table');
            $A(tabel.getElementsByTagName('tr')).invoke('removeClassName','row-over');
        });
    })
})

/* Linkuri pentru form submit*/

document.observe("dom:loaded", function() {
    $$('.submit-button').each(function(f_submit){
        Event.observe(f_submit,'click', function(event){
            submit_button=Event.element(event);
            Event.stop(event);
            if($(submit_button.id.gsub('submit_',''))!=undefined)
            $(submit_button.id.gsub('submit_','')).submit();
        })

    })
})


/* Auto-resizing Textarea*/

document.observe("dom:loaded", function() {
    $$('textarea.auto-resize').each(function(ta){
        Event.observe(ta,'keyup', function(event){
            txt_area=Event.element(event);
            ta_st=txt_area.scrollTop
            if(ta_st >0){
                new_height=txt_area.getHeight()+ta_st
                new Effect.Morph(txt_area,{style:{height:new_height+'px'}, duration:0.5});
            }
        })
    })

})

/* AJAX Links*/
doAjax=function(event){
    elem=event.findElement('.ajax-updater');
    ax_url=elem.href;
    ax_container = $(elem.id+'_container');

    if(ax_container != undefined){
        new Ajax.Updater(ax_container, ax_url);
        ax_container.show();
    }
    Event.stop(event);
}

document.observe("dom:loaded", function() {
    $$('.ajax-updater').each(function(axlink){
        Event.observe(axlink, 'click', doAjax);
    })

})

/* Friend list*/
var FriendList={
    currTrigger:"cucu",

    selectFriend:function(event){
        fl=event.findElement('a.friends-list-link');
        up_field=FriendList.currTrigger.id.gsub('update_','');
        if($(up_field)!=undefined && fl != undefined){
            $(up_field).value=fl.innerHTML;
            $('friends-list-container').hide();
        }
    },

    openList:function(event){
        fl_trigger=event.findElement('.friends-list-trigger');
        if($('friends-list-container')!=undefined){
            if($('friends-list-container').getHeight()>250)
            $('friends-list-container').setStyle({height:'250px'});

            fl_trigger_pos=fl_trigger.positionedOffset();
            fl_x=fl_trigger_pos.left-$('friends-list-container').getWidth();
            fl_y=fl_trigger_pos.top-($('friends-list-container').getHeight()/2);

            $('friends-list-container').setStyle({position:'absolute', top:fl_y+'px', left:fl_x+'px'})
            new Effect.toggle('friends-list-container','appear',{duration:0.5})
            FriendList.currTrigger=fl_trigger;
        }
    },

    closeList:function(){
        new Effect.toggle('friends-list-container','appear',{duration:0.5})
    },
    selectAllFriends:function(event){
        up_field=FriendList.currTrigger.id.gsub('update_','');
        if($(up_field)!=undefined && all_friends != undefined){
            $(up_field).value = all_friends;
            $('friends-list-container').hide();
        }
    }

}

document.observe("dom:loaded", function() {
    $$('.friends-list-trigger').each(function(flt){
        Event.observe(flt,'click', FriendList.openList);
    })

    $$('a.friends-list-link').each(function(fl){
        Event.observe(fl, 'click', FriendList.selectFriend.bindAsEventListener(FriendList))
    })

    $$('a.friends-list-all').each(function(fl){
        Event.observe(fl, 'click', FriendList.selectAllFriends);
    })

    if($('friends-list-container')!=undefined){
        new Draggable($('friends-list-container'),{handle:$('friends-list-container').down('h2')})
    }

    $$('.close-button').each(function(close_btn){
        Event.observe(close_btn, 'click', function(event){
            cbtn=event.findElement('.close-button');
            elem_close=$(cbtn.id.gsub('close-',''));
            if(elem_close!=undefined)
            new Effect.toggle(elem_close,'appear',{duration:0.5});
        })
    })
})

toggleColorPicker=function(event, id, act){
    var button = Event.element(event)
    var XY = Element.cumulativeOffset(button);
    var posX = XY[0] + 'px', posY =  XY[1] + 'px', margX = XY[0]-230 + 'px', margY =  XY[1]-20 + 'px';
    Event.stop(event);
    CPicker.loadPicker(posX,posY,act,id);
}

//color_picker_container

document.observe("dom:loaded", function(){
    $$('.color_picker_close').each(function(dv) {
        Event.observe(dv,'click',function(event) {
            var id = (/[^0-9]*([0-9]+)/.exec(dv.id))[1];
            toggleColorPicker(event, id, 'hide');
        });
    });
    $$('.color_picker_show').each(function(dv) {
        Event.observe(dv,'click', function(event) {
            var id = (/[^0-9]*([0-9]+)/.exec(dv.id))[1];
            toggleColorPicker(event, id, 'show');
        });
    });

})


function use_embed_settings(cid) {
    if($A($$('#embeded .titlu_upl')).size() > 0) {
        Effect.Appear('embeded',{duration: 0.4});
    } else if(cid) {
        params = {content_id: cid};
        sn_updateByAjax('get_embed_settings', params,'embeded', {onComplete: embed_code_options});
    }
}

function embed_code_options() {
    if ($('form_embed')) {
        $('form_embed').getElements().each(function(el){
            if (el.type == 'radio') Event.observe(el, 'click', make_embed_code);
            else Event.observe(el, 'change', make_embed_code);
        });
    }
    $$('.color_picker_close').each(function(dv) {
        Event.observe(dv,'click',function(event) {
            var id = (/[^0-9]*([0-9]+)/.exec(dv.id))[1];
            toggleColorPicker(event, id, 'hide');
        });
    });
    $$('.color_picker_show').each(function(dv) {
        Event.observe(dv,'click', function(event) {
            var id = (/[^0-9]*([0-9]+)/.exec(dv.id))[1];
            toggleColorPicker(event, id, 'show');
        });
    });
    Effect.Appear('embeded',{duration: 0.4});
}

function remove_embed(){
    Effect.Fade('embeded',{duration: 0.4});
}

function addIFrame(node) {//deasupra selecturilor in IE6
    $$('iframe:not([id~="my_frame"])').each(function(el){Element.remove(el);});
    var iframe = document.createElement('iframe');
    with (iframe.style) {
        position = 'absolute';
        height = 300;
        width = node.style.width;
        top = -node.style.height;
        border = '0';
        zIndex='-1';
        opacity='0';
    }
   node.appendChild(iframe);
}

function bookmarksite(title,url) {
    if (window.sidebar) { // firefox
        window.sidebar.addPanel(title, url,"");
    } else if (window.opera && window.print){ // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    }
    else if(document.all) { // ie
        window.external.AddFavorite(url, title);
    } else {
        alert("Ne pare rau, browserul dvs nu e suportat \nPentru Safari apsati Ctrl/Cmd + D \nPentru Konqueror apsati Ctrl + B");
    }
}



var mplaylist = {
    add: function(id) {
        params = {mplaylist_id: id, action: 1}
        sn_updateByAjax('mplaylist', params, '');
    },

    del: function(id) {
        params = {mplaylist_id: id, action: 0};
        sn_updateByAjax('mplaylist', params, '');
    }
};




function openLoginBox(option_id) {
    if (typeof(age_minor_deny) != 'undefined' && age_minor_deny == 1 && option_id != 0) return;
    var orig = $('form_login_suplimentar');
    var holder = $('adaugalogin_' + option_id);
    if(!orig || !holder) return;
    orig.remove();
    holder.appendChild(orig);
    form = $('formslogin');
    form.show();
    orig.show();
}

function toggleStar(elementID) {
    var mumu = document.getElementById(elementID)

    if ( typeof c_activ_opt != 'undefined' ) {
        document.getElementById(c_activ_opt).style.display = 'none';
    }

    if (mumu.style.display == 'none') {
        mumu.style.display = 'block'
        openLoginBox(elementID);
    } else {
        mumu.style.display = 'none'
    }
}


function my_toggle(elementID) {
    try {
        if($(elementID).visible())  blind($(elementID));
        else blindDown($(elementID));
    }
    catch(e) {;}
}
// functie pentru development.. printare obiecte, array-uri javascript
function print_array(arr, include_objects)
{
    var sfx = '';
    var include_obj = (typeof(include_objects) == 'undefined' || include_objects == true) ? true : false;
    var lev = (typeof(arguments[2]) != 'undefined') ? arguments[2] : 0;
    for (var i=0; i <= lev; i++) sfx += "\t";
    var ret = typeof(arr) + " :\n" + sfx + "(\n";

    if(typeof(arr) == 'array' || (include_obj ? typeof(arr) == 'object' : false)) {
        for(var i in arr) {
            //alert(i);
            if(typeof(arr[i]) == 'array' || (include_obj ? (typeof(arr[i]) == 'object' && arr[i] != null) : false)) {
                ret += sfx + ' [ ' +  i + '] => ' + print_array(arr[i], include_obj, lev + 1);
            }
            else {
                ret += sfx + '[' + i + '] => ' + arr[i] + "\n";
            }
        }
        ret += sfx + ")\n";
    }
    else {
        ret += arr + "\n)\n";
    }
    if (lev > 0)    return ret;
    else alert(ret);
}

// [+] Zona ajax posts ----------------------------------------------------
function stripLink(text){
    var replacer = '[a #{1}href=#{2}]#{3}[/a]';
    replacer = "";
    //text = text.gsub(/\"/ , '\"');
    //text = text.gsub(/\'/ , "\'");
    var aux = true;
    //--------varianta cu prototype
    while(aux){
        var t2 = text;
        var t = text.gsub(/(.*?)<a class=\"?owner\"? (.*?)href=(.*?)>([^<>]*?)<\/a>/i , replacer);
        if(t == t2) aux= false;
        text = t;
    }
    return t;
}
function unstripLink(text){
    var replacer = '<a #{1}href=#{2}>#{3}</a>';
    //text = text.gsub(/\\"/ , '"');
    var aux = true;
    //--------varianta cu prototype
    while(aux){
        var t2 = text;
        var t = text.gsub(/\[a (.*?)href=(.*?)\]([^\[\]]*?)\[\/a\]/i , replacer);
        if(t == t2) aux= false;
        text = t;
    }
    return t;

}
function stripDiv(text,parent_id,username){
    var replacer = "[citat]#{1}[/citat]";
    if(parent_id != 0) replacer = "";
    var aux = true;

    //text = stripLink(text);
    //--------varianta cu prototype
    //while(aux){
       // var t2 = text;
     //alert(text);
      var index = text.indexOf("</DIV>");

      if(index == -1){
          index = text.indexOf("</div>");
      }
      if(index != -1){
          t = text.substr(index+6);
      }else{
          t = text;
      }
     //text = ' Quote: <a class ="owner" title="bursuculu"  \n href=http://developer.activesoft.ro/~dragos/220v2/bursuculu/>bursuculu</a> a spus: <div class="citat"> asdasd </div> comment';
      //text = text.escapeHTML();
      //var t = text.gsub(/<div class=\"?citat\"?>(.*?)<\/div>/gim , replacer);
       //alert(t);
       //var re = new RegExp( "(.*?)<div class=\"?citat\"?>(.*?)<\/div>","gim" );
       //t = text.replace(re ,replacer);


//      /var re = new RegExp( "(.*?)\n","gim" );
      //if(re.test(t))t = t.replace(re ,replacer);

        //if(t == t2) aux= false;
       // text = t;
    //}

    /*varianta fara ....IE SUCKS
    while(aux)
    {
        var re = new RegExp( "<div class=\"?citat\"?>([^<>]*?)<\/div>","gi" );
        text = text.replace(re ,replacer);
        re = new RegExp( "<div class=\"?citat\"?>([^<>]*?)<\/div>","gi" );
        aux = re.test(text);

    }
    */

    if(parent_id != 0) {

        if(trim(t) != "") {

            t = '[citat|'+username+']'+trim(t)+'[/citat]';
        }else{
            t = trim(t);
        }
    }

    //t = unstripLink(t);
    //alert(t);

    return t;
}

function trim(text){
    return text.replace(/^\s+/, "").replace(/\s+$/, "") ;

}

function setCursor(el,st,end) {
    if(el.setSelectionRange) {
        el.focus();
        el.setSelectionRange(st,end);
    }
    else {
        if(el.createTextRange) {
            range = el.createTextRange();
            range.collapse(true);
            range.moveEnd('character',end);
            range.moveStart('character',st);
            range.select();
        }
    }
}

function insertText(tArea, str){
    var isIE = (document.all)? true : false;
    var poss = tArea.value.length;

    if(isIE){
        tArea.focus();
        var pr_txt = tArea.value;
        var curSelect = document.selection.createRange();
        curSelect.text = str + curSelect.text;
        var cur_txt = tArea.value;
        for(i=0; i<cur_txt.length; i++) {
            if(cur_txt.charAt(i) != pr_txt.charAt(i)) {
                poss = i + str.length;
                break;
            }
        }
    }
    else if(!isIE && typeof tArea.selectionStart != "undefined"){
        var selStart = tArea.value.substr(0, tArea.selectionStart);
        var selEnd = tArea.value.substr(tArea.selectionEnd, tArea.value.length);
        var curSelection = tArea.value.replace(selStart, '').replace(selEnd, '');

        poss = tArea.selectionStart + str.length;
        tArea.value = selStart + str + curSelection + selEnd;
    }
    else {
        tArea.value += str;
    }
    pose = poss;
    tArea.focus();
    setCursor(tArea, poss, pose);
}

function citatToDiv(text,parent_id){
    var replacer = "<div class=\"citat\">#{1}<\/div>";
    if(parent_id == 0 ){
        replacer = "#{1}";
    }
    var auxil = true;
    //--------varianta cu prototype
    //while(auxil){
        var t2 = text;
        var t = text.gsub( /\[citat\]([^\[\]]*?)\[\/citat\]/i , replacer);
        if(t == t2) auxil = false;
        text = t;
    //}

    /*varianta fara ....IE SUCKS
    while(auxil)
    {
        var reg = new RegExp( /\[citat\]([^\[\]]*?)\[\/citat\]/gi );
        text = text.replace(reg,replacer);
        reg = new RegExp( /\[citat\]([^\[\]]*?)\[\/citat\]/gi );
        auxil = reg.test(text);
    }
    */
    return text;
}

function comenteaza(id,parent_id,username){
    blind('add_response');
    blind('add_form');
    blind('post_'+id)
    update(id,parent_id,username);

    //$('post_'+id).style.display = "none";
    //var post_id = "text_post_"+id;
    //blind(post_id);
    //setTimeout("update('"+id+"')",510);
    //setTimeout("blindDown('"+post_id+"')",520);
}

function delete_post(id,replys){
    id_u = $('user_id').value;
    id_d = $('disc_id').value;
    id_g = $('group_id').value;
    params = {user_id:id_u ,disc_id :id_d,post_id:id,group_id:id_g};
    if(replys != 0){
        if(confirm("Acest post are "+replys+" raspunsuri")){
            sn_getAjax("delete_post",params);
        }
    }else{
        sn_getAjax("delete_post",params);
    }
}
function sn_deletePostHandler(result, resultElementName, userData){
    if(result.code == 1002)
    {
    $('completare').update(result.text.showPosts);
    window.ajaxPagination.returnCall(result.text.numPosts);
    }
    else document.location = SITE_BASE + "index.php?module=login&err=no_auth_up";
}
function update(id,parent_id,username){
    var comment_id = "post_comment_"+id;
    var post_id = "post_"+id;
    var link_id = "linker_"+id;
    var post_text = $(post_id).innerHTML;
    post_text = stripDiv(post_text,parent_id,username);
   // post_text.unes_cape_AVIRA_SUCKS_HTML();
    //var text_update = "<div id=\"citat_"+post_id+"\">"+post_text+"</div>"+"<textarea rows=10 cols=60 name=\"text_"+post_id +" \" ";
    if(parent_id == '0'){
        if(post_text != ""){
            post_text = " [citat|"+username+"]"+trim(post_text)+"[/citat]";
        }
    }

    if(post_text)
    {
        var text_update = "<textarea rows=10 cols=57 name=\"text_"+post_id +" \" ";
        text_update += " id=\"text_"+post_id+"\" >"+trim(post_text)+"</textarea><br/>";
        text_update += "<div style='padding:0 0 30px 0' id=\"links_"+id+"\"><a class='replay content btn_albastru btn_albastru_20 b-r-3 right m-h-10' style='margin-right: 35px;' href=\"javascript:void(0)\" onclick=\"raspunde_post('"+id+"','"+parent_id+"')\">trimite</a>";
        text_update += "<a href=\"javascript:void(0)\"  class='replay content btn_albastru btn_albastru_20 b-r-3 right m-h-10' onclick=\"inchide_post('"+id+"','"+parent_id+"')\">inchide</a></div>";
        $(comment_id).update(text_update);
        setCursor($("text_"+post_id),post_text.length,post_text.length);
        $(link_id).style.display = "none";

    }else{
        var text_update = "<textarea rows=10 cols=60 name=\"text_"+post_id +" \" ";
        text_update += " id=\"text_"+post_id+"\" >Acest post nu contine text ce poate fi comentat!</textarea><br/>";
        text_update += "<div id=\"links_"+id+"\"><a href=\"javascript:void(0)\"  class='replay' onclick=\"inchide_post('"+id+"','"+parent_id+"')\">Inchide</a></div>";
        $(comment_id).update(text_update);
        $(link_id).style.display = "none";
    }
}
function inchide_post(id,parent_id){
    var links_id = "links_"+id;
    var post_id =  "post_"+id;
    var text_id = "text_post_"+id;
    var link_id = "linker_"+id;

    $(text_id).remove();
    blindDown(post_id);
    $(links_id).remove();
    $(link_id).style.display = "block";
}
function removeCitat(text){
    var aux =  text.substr(7);
    var stop = aux.length - 8;
    aux = aux.substr(0,stop);
    return aux;
}

function raspunde_post(id,parent_id){//raspunde la un post existent
    id_d = $('disc_id').value;
    var post_id = "text_post_"+id;
    var citat_id = "citat_post_"+id;
    var user_link =  document.getElementById("link_user").innerHTML;
    var post_text = $(post_id).value;
    //var citat_text = stripDiv($(post_id).innerHTML);
    //post_text = "Quote: [citat] "+citat_text+"[/citat]"+user_link+"a scris: "+"<div>"+post_text+"</div>";
    if( post_text != ""){

        post_text = '<strong>Quote:</strong>' + post_text;
        params = {post_description:post_text ,disc_id :id_d, post_id:id};
        sn_getAjax("adauga_post_form",params);

    }
    setTimeout('location.reload(true);', 2000);
}

function add_post(event){//raspunde la o discutie fara a cita
    Event.stop(event);
    id_u = $('user_id').value;
    id_g = $('group_id').value;
    id_d = $('disc_id').value;
    my_form = Event.element(event);
    customParams = my_form.serialize().parseQuery();
    if(customParams.post_description != "") {

        var user_link =  document.getElementById("link_user").innerHTML;
       // customParams.post_description = user_link +" a scris:  "+"<div >"+customParams.post_description+"</div>";
       customParams.post_description = customParams.post_description;
       sn_getAjax('adauga_post_form', customParams);

    }else{

        if($('adauga_response_msg')){
             Effect.Appear($('adauga_response_msg'), { duration: 0.0 });
             $('adauga_response_msg').innerHTML  = "Trebuie sa contina text!";
             Effect.Fade( $('adauga_response_msg'), {transition: Effect.Transitions.linear, duration: 2.0});
        }

    }
}

function sn_adaugaPostFormHandler(result, resultElementName, userData){
    if(result.code == 1005) {
        alert(result.text);
        return;
    }
    else if(result.code == 999) {
        $('completare').update(result.text.showPosts);
        $('events').update(result.text.events);
        $('add_response').style.display = "none";
        $('add_form').style.display = "none";

        var page = Math.round(result.text.numPosts/result.text.posts_per_page) ;

        if(page == 0 ){
            page = 1;
        }

        window.ajaxPagination.gotoPage(page);

        window.ajaxPagination.returnCall(result.text.numPosts);
        window.ajaxPagination2.returnCall(result.text.num_events);
    }
    else document.location = SITE_BASE + "index.php?module=login&err=no_auth_up";
}

document.observe("dom:loaded",function(){
    if($('add_post_form')!=undefined){
        Event.observe('add_post_form','submit',add_post)
    }
})

function fetchPosts(limit, offset,userData) {

    if (discId) {
        div = $('completare');
        while (div.childNodes.length > 0) {
            div.removeChild(div.childNodes[0]);
        }

        params = {limit: limit, offset: offset, disc_id: discId};

        sn_getAjax('fetch_disc_posts', params, 'completare',userData);
    }
}

function sn_fetchDiscPostsHandler(result, resultElementName, userData) {

    if (result.code == 667) {
        result = result.text.evalJSON();
        $(resultElementName).update( result.posts);
        window.ajaxPagination.returnCall(result.num_posts);
    }
    if(userData){
        var locatio = "" + document.location;
        locatio = locatio.replace(/#.+/i, '');
        document.location = locatio + '#' + "an_" + userData;
    }
}
// [-] Zona ajax posts ----------------------------------------------------

// [+] Zona ajax events ----------------------------------------------------
function fetchEvents(limit, offset) {
    if (groupId) {
        div = $('events');
        params = {limit: limit, offset: offset, group_id: groupId};
        sn_getAjax('fetch_events', params, 'events');
    }
}

function sn_fetchEventsHandler(result, resultElementName, userData) {
    if (result.code == 66) {
        result = result.text.evalJSON();
        $(resultElementName).update(result.events);
        window.ajaxPagination2.returnCall(result.num_events);
    }

}
// [-] Zona ajax events ----------------------------------------------------

// [+] Zona ajax members ----------------------------------------------------
function fetchMembers(limit, offset) {
    if (groupId) {
        div = $('events');
        params = {limit: limit, offset: offset, group_id: groupId};
        sn_getAjax('fetch_members', params, 'members');
    }
}

function sn_fetchMembersHandler(result, resultElementName, userData) {
    if (result.code == 66) {
        result = result.text.evalJSON()
        $(resultElementName).update(result.users);
        window.ajaxPagination3.returnCall(result.num_members);
    }
}
function deleteMembers(limit, offset) {
    if (groupId) {
        params = {limit: limit, offset: offset, group_id: groupId};
        sn_getAjax('delete_members', params, 'members');
    }
}

function sn_deleteMembersHandler(result, resultElementName, userData) {
    if (result.code == 66) {
        result = result.text.evalJSON()
        $(resultElementName).update(result.users);
        window.ajaxPagination3.returnCall(result.num_members);
    }
}
// [-] Zona ajax members ----------------------------------------------------

// [+] Zona ajax discussions ----------------------------------------------------
function fetchDisscusions(limit, offset) {
    if (groupId) {
        div = $('completare');
        params = {limit: limit, offset: offset, group_id: groupId};
        sn_getAjax('fetch_disc', params, 'completare');
    }
}

function sn_fetchDiscHandler(result, resultElementName, userData) {

    if (result.code == 668) {
        result = result.text.evalJSON();
        $(resultElementName).update( result.disscusions);
        window.ajaxPagination.returnCall(result.num_disscusions);
    }
}




function del_discussion(event){
  Event.stop(event);
  var  params = {disc_id:discId};
  if(confirm("Sunteti siguri ca vreti sa stergeti aceasta discutie ?")) sn_getAjax('delete_discussion',params);
}


function sn_deleteDiscussionHandler(result, resultElementName, userData){

    if(result.code == 670){
        result = result.text.evalJSON();
        var group_id = result.groupId;
        document.location = result.my_link;
    }else document.location = SITE_BASE + "err/no_rights_to_delete_discussions";
}

document.observe("dom:loaded",function(){
    if($('del_disc')!=undefined){
        Event.observe('del_disc','click',del_discussion)
    }
})
// [-] Zona ajax discussions ----------------------------------------------------

function blind(element)
{
 element = $(element);
 new Effect.BlindUp(element,  {duration : 0.5});


}
function blindDown(element)
{
 element = $(element);
 new Effect.BlindDown(element, {duration : 0.5});

}


//----------------------------------functii pentru grup-----------------------------------
function disable_notification()
{

    id_u = $('user_id').value;
    id_g = $('group_id').value;
    params = {uid: id_u, gid: id_g};
    sn_getAjax('disable_notification',params);

}
function sn_disableNotificationHandler(result, resultElementName, userData)
{
    if(result.code = 666)
    {
        if($('notif').value == "0")
        {
            $('disable_notifications').update("dezactiveaza notificarile");
            $('notif').value = "1";
        }
        else if($('notif').value == "1")
        {
            $('disable_notifications').update("activeaza notificarile");
            $('notif').value = "0";
        }
    }
    if(result.code == 667) document.location = SITE_BASE + "index.php?module=login&err=no_auth_up";
}

document.observe("dom:loaded", function(){
        if($('disable_notifications')!=undefined){
            Event.observe('disable_notifications','click', disable_notification);
        }
    })

function join_group()
{
    id_u = $('user_id').value;
    id_g = $('group_id').value;
    params = {uid: id_u, gid: id_g};
    sn_getAjax('join_group',params);
}

function sn_joinGroupHandler(result, resultElementName, userData)
{
    $('join_group').update(result.text);
    if ($('join_group') != null)
    {
     setTimeout("$('join_group').update('')", 1500);
     id_g = $('group_id').value;
     if(result.code == 0) document.location = SITE_BASE + "index.php?module=sectiune&s=comunitate&id="+id_g;
    }
}
function adauga_discutie(event)
 {

     Event.stop(event);
     my_form = Event.element(event);
     customParams = my_form.serialize().parseQuery();
     if(customParams.title != "") sn_getAjax('adauga_discutie', customParams);
     else{
          if($('adauga_discutie_msg')){
             Effect.Appear($('adauga_discutie_msg'), { duration: 0.0 });
             $('adauga_discutie_msg').innerHTML  = "Discutia trebuie sa contina un titlu!";
             Effect.Fade( $('adauga_discutie_msg'), {transition: Effect.Transitions.linear, duration: 2.0});
        }
     }
 }

 function sn_adaugaDiscutieHandler(result, resultElementName, userData){

    if(result.code == 555) document.location = SITE_BASE + "index.php?module=login&err=no_auth_up";

    if(result.code == 0)
    {
        $('completare').update(result.text.showDisscusions);
        $('events').update(result.text.events);
        $('num1').update(result.text.numDisscusions);
        if($('add_response')){
            $('add_response').style.display = "none";
        }
        if($('add_form')){
            $('add_form').style.display = "none";
        }
        if($('meniu_disc')){
            $('meniu_disc').style.display = "none";
        }
        if($('adauga_discutie_form')){
            $('adauga_discutie_form').reset();
        }
        if($('adauga_discutie_msg')){
             Effect.Appear($('adauga_discutie_msg'), { duration: 0.0 });
             $('adauga_discutie_msg').innerHTML  = "Ati adaugat cu succes discutia!";
             Effect.Fade( $('adauga_discutie_msg'), {transition: Effect.Transitions.linear, duration: 2.0});
        }

        window.ajaxPagination.returnCall(result.text.numDisscusions);
        window.ajaxPagination2.returnCall(result.text.num_events);
    }
 }

document.observe("dom:loaded",function(){
    if($('adauga_discutie_form')!=undefined){
        Event.observe('adauga_discutie_form','submit',adauga_discutie)
    }
})

document.observe("dom:loaded",function(){
    if($('sterge_membri_form')!=undefined){
        Event.observe('sterge_membri_form','submit',sterge_membri)
    }
})
function sterge_membri(event){
    Event.stop(event);
    my_form = Event.element(event);
    customParams = my_form.serialize().parseQuery();
    id_u = $('user_id').value;
    id_g = $('group_id').value;
    customParams['uid'] = id_u;
    customParams['gid'] = id_g;
    if(confirm("Sunteti siguri sa stergeti membri?")) sn_getAjax('sterge_membri',customParams);
}

function sn_stergeMembriHandler(result, resultElementName, userData){
      if(result.code == 1) document.location.reload();
}

document.observe("dom:loaded",function(){
    if($('group_file_add')!=undefined){
        Event.observe('group_file_add','submit',group_file_add)
    }
})

function group_file_add(event){
    Event.stop(event);
    my_form = Event.element(event);
    customParams = my_form.serialize().parseQuery();
    sn_getAjax('add_to_group',customParams)
}

function paraseste_grup(event)
{
    Event.stop(event);
    id_u = $('user_id').value;
    id_g = $('group_id').value;
    params={ uid:id_u , gid:id_g };
    if(confirm("Sunteti siguri ca vreti sa parasiti grupul?")) sn_getAjax('paraseste_grup',params);

}
function sn_parasesteGrupHandler(result, resultElementName, userData){
    if(result.code == 0) {
        id_g = $('group_id').value;
        if( $('num_members')) $('num_members').update(result.text.numMembers);
        document.location.reload();
    } else if (result.code == 1) {
        document.location = SITE_BASE + "index.php?module=login&err=no_auth_up"
    } else {
        var pop =  new MessageBox('response', 'Eroare', result.text, {ok:['Inchide', function(){void(0);}]});
    }
}

document.observe("dom:loaded",function(){
        if($('paraseste_grup_link')!=undefined){
            Event.observe('paraseste_grup_link','click',paraseste_grup)
        }
    })

function sterge_grup(event)
{
    Event.stop(event);
    id_u = $('user_id').value;
    id_g = $('group_id').value;
    params={ uid:id_u , gid:id_g };
    if(confirm("Sunteti siguri ca vreti sa stergeti acest grup?")){
        sn_getAjax('sterge_grup',params);
    }
}

function sn_stergeGrupHandler(result, resultElementName, userData){
 if(result.code == 889){
     document.location = SITE_BASE + "index.php?module=login&err=no_auth_up";
 }
 if(result.code == 888){
     document.location = SITE_BASE + "comunitate/";
 }
}


function sterge_gcontent(caid)
{
    id_u = $('user_id').value;
    id_g = $('group_id').value;
    params={ uid:id_u , gid:id_g , cid:caid };
    if(confirm("Sunteti siguri ca vreti sa stergeti acest fisier?")) sn_getAjax('sterge_gcontent',params);
}

function sn_stergeGcontentHandler(result, resultElementName, userData){
 id_g = $('group_id').value;
 if(result.code == 1) document.location = SITE_BASE + "index.php?module=sectiune&s=comunitate&id="+id_g;
 else{
     alert(result.text);
 }
}

function grup_favorit(aid){
    id_u = $('user_id').value;
    id_g = $('group_id').value;
    id_c = aid;
    params={ uid:id_u , gid:id_g , cid:id_c};
    if(confirm("Sunteti siguri ca vreti sa promovati acest fisier?")) sn_getAjax('favorit_grup',params);

}

function sn_favoritGrupHandler(result, resultElementName, userData){
 id_g = $('group_id').value;
 if(result.code == 1) document.location = SITE_BASE + "index.php?module=sectiune&s=comunitate&id="+id_g;
 else{
     alert(result.text);
 }
}
document.observe("dom:loaded",function(){
    if($('sterge_grup_link')!=undefined){
        Event.observe('sterge_grup_link','click',sterge_grup)
    }
})

function scoate_din_playlist(content_id, pid)
{
    if(content_id != '')
    {
        params = {content_id: content_id, pid: pid};
    }
    sn_getAjax('scoate_din_playlist',params);
}

function sn_scoateDinPlaylistHandler(result, resultElementName, userData)
{
    if(result.code == 0)
    {
        $('playlist_content').update(result.text.playlistContent);
        Sortable.destroy('playlist_content');
        init_sortable_playlist();
    }
}

function seteaza_icon(content_id, pid)
{
    params = {content_id: content_id, pid: pid};
    sn_getAjax('seteaza_icon', params, null, {'content_id': content_id});
}

function sn_seteazaIconHandler(result, resultElementName, userData)
{
    if(result.code == 0)
    {
        $('playlists').update(result.text.playlists);
        var id_msg = 'pmsg_' + userData['content_id'];
        Effect.Appear(id_msg, { duration: 2.0 });
        $(id_msg).update("Continutul a fost setat ca icon principal");
        Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
    }
}


document.observe("dom:loaded",function(){
    if($('bkg_form')!=undefined){
        Event.observe('bkg_form','submit',preview_imagine)
    }
})


function preview_imagine(){
sn_getAjax('preview_imagine');
}

function sn_previewImagineHandler(result, resultElementName, userData)
{
    var image = document.getElementById( 'img_preview' );
    image.src = "";
    image.src = result.text;

}
var UserChannel = {
    image_temp_url:"",
    image_url :"",
    setOriginalImage :function(img){
        UserChannel.image_url = img;
    },
    textSize : function(size){
        if($('u_boxText'))  $('u_boxText').style.fontSize = " " + size;
    },
    textFont : function(font){
        if($('u_boxText')){
                    $('u_boxText').style.fontFamily = font;
        }
    },
    textStil : function(stil,check){
        if($('u_boxText')){
                    switch(stil)
                    {
                     case 'bold':
                        $('u_boxText').style.fontWeight =(check)?stil:"normal";
                        break;
                     case 'italic':
                        $('u_boxText').style.fontStyle =(check)?stil:"normal";
                        break;
                     case 'underline':
                        $('u_boxText').style.textDecoration =(check)?stil:"none";
                        break;
                     default:
                        break;
                    }

        }
    },
    textColor : function(){
        $$('.id_cp2').each(function(inp){
                    if(inp.value && $('u_boxText')) $('u_boxText').style.color ="#"+inp.value ;
               });
    },
   linkSize : function(size){
        if($('text_link'))  $('text_link').style.fontSize = " "+size;
   },
   linkFont : function(font){
        if($('text_link')){
                    $('text_link').style.fontFamily = font;
        }
    },
    linkStil : function(stil,check){
        if($('text_link')){
                    switch(stil)
                    {
                     case 'bold':
                        $('text_link').style.fontWeight =(check)?stil:"normal";
                        break;
                     case 'italic':
                        $('text_link').style.fontStyle =(check)?stil:"normal";
                        break;
                     case 'underline':
                        $('text_link').style.textDecoration =(check)?stil:"none";
                        break;
                     default:
                        break;
                    }
        }
    },
   linkColor : function(){
               $$('.id_cp3').each(function(inp){
                    if(inp.value && $('text_link')) $('text_link').style.color ="#"+inp.value ;
               });
   },
   headerSize : function(size){
        if($$('.user_box h5'))  $$('.user_box h5').each(function(inp){
            inp.style.fontSize = size;
        })
    },
   headerFont : function(font){
        if($('text_link')){
                     if($$('.user_box h5'))  $$('.user_box h5').each(function(inp){
                            inp.style.fontFamily = font;
                        })
        }
    },
    headerStil : function(stil,check){
        if($('text_link')){
                       if($$('.user_box h5'))  $$('.user_box h5').each(function(inp){
                            switch(stil)
                            {
                             case 'bold':
                                inp.style.fontWeight =(check)?stil:"normal";
                                break;
                             case 'italic':
                                inp.style.fontStyle =(check)?stil:"normal";
                                break;
                             case 'underline':
                                inp.style.textDecoration =(check)?stil:"none";
                                break;
                             default:
                                break;
                            }

                        })
        }
    },
    headerColor : function(){
                $$('.id_cp4').each(function(inp)
               {
                    if(inp.value && $$('.user_box h5'))  $$('.user_box h5').each(function(inp2){
                                        inp2.style.color ="#" + inp.value;
                                    })
               });
   },
    borderSize : function(size){
        if($$('.user_box'))  $$('.user_box').each(function(inp){
                            switch($('border_position').value){
                                case 'border':
                                inp.style.borderWidth = size;
                                break;
                                case 'border-left':
                                inp.style.borderLeftWidth =  size;
                                break;
                                case 'border-right':
                                inp.style.borderRightWidth =  size;
                                break;
                                case 'border-bottom':
                                inp.style.borderBottomWidth =  size;
                                break;
                                case 'border-top':
                                inp.style.borderTopWidth =  size;
                                default:
                                break;
                            }
                        })

    },
    borderStil :function(stil){
        if($$('.user_box'))  $$('.user_box').each(function(inp){
                                UserChannel.borderSize($('border_size').value);
                                inp.style.borderStyle = stil;
                        })
    },
    borderPosition :function(position){
        if($$('.user_box'))  $$('.user_box').each(function(inp){
                            UserChannel.borderColor();
                            UserChannel.borderStil($('border_stil').value);
                            inp.style.borderWidth = 0 + "px";
                            switch(position){
                                case 'border':
                                inp.style.borderWidth = $('border_size').value;
                                break;
                                case 'border-left':
                                inp.style.borderLeftWidth =  $('border_size').value;
                                break;
                                case 'border-right':
                                inp.style.borderRightWidth =  $('border_size').value;
                                break;
                                case 'border-bottom':
                                inp.style.borderBottomWidth =  $('border_size').value;
                                break;
                                case 'border-top':
                                inp.style.borderTopWidth =  $('border_size').value;
                                default:
                                break;
                            }
                        })

    },
    borderColor :function(){
        $$('.id_cp5').each(function(inp)
               {
                    if(inp.value && $$('.user_box'))  $$('.user_box').each(function(inp2){
                                        inp2.style.borderColor ="#" + inp.value;
                                    })
               });
    },
    headerBkgColor : function(){
          $$('.id_cp6').each(function(inp)
               {
                    if(inp.value && $$('.user_box h5'))  $$('.user_box h5').each(function(inp2){
                                        inp2.style.backgroundColor ="#" + inp.value;
                                    })
               });
    },
    boxBkgColor : function(){
           $$('.id_cp7').each(function(inp)
               {
                    if(inp.value && $$('.user_box'))  $$('.user_box').each(function(inp2){
                                        inp2.style.backgroundColor ="#" + inp.value;
                                    })
               });
    },
    changeImage : function(){
        if($('picture_status')){
            if(!$('picture_status').checked){
                $('immagine').style.display = "none";
                $('immagine_default').style.display = "block";
            }
            else {
                $('immagine').style.display = "block";
                $('immagine_default').style.display = "none";
            }
        }
    },
    imageBackground : function(elem,my_url){
        $(elem).style.backgroundImage = "url('"+my_url+"')";
        $(elem).style.backgroundPosition = "center center";
        $(elem).style.backgroundRepeat = "no-repeat";
        UserChannel.image_temp_url = my_url;
    },
    imagePosition :function(elem,position){
        $(elem).style.backgroundPosition = position;
    },
    imageRepeat :function(elem,repeat){
        $(elem).style.backgroundRepeat = repeat;
    },
    imageAtasament :function(elem,repeat){
        $(elem).style.backgroundAttachment = repeat;
    },
    resetImage : function(elem,checked){
        var url = (checked)?UserChannel.image_temp_url:UserChannel.image_url;
        if($('background_status').checked) url = "";
        if(url != "") $(elem).style.backgroundImage ="url('"+url+"')";
    },
    clearToBackground : function(elem,checked){
        var url = UserChannel.image_url;
        if($('preview_cfg_image').style.backgroundImage != "none" &&  UserChannel.image_url =="" && !$('picture_status').checked){
            UserChannel.image_url = $('preview_cfg_image').style.backgroundImage;
            url =  UserChannel.image_url;
        }else if(UserChannel.image_temp_url != "" && $('picture_status').checked){
            url = UserChannel.image_temp_url;
        }
        if(url) url = "url('"+url+"')";
        $(elem).style.backgroundImage =(checked)?"none":url;

    },
    backgroundColor: function(){
             $$('.id_cp1').each(function(inp){
                    if(inp.value && $('preview_cfg_image')) $('preview_cfg_image').style.backgroundColor ="#"+inp.value ;
               });
    },
    box_resolution : function(element){
        try
        {

       var ratio = 35;

        if(Math.round(screen.width/screen.height) > 1){
            ratio -= (Math.round(screen.width/screen.height)-1)*5;
        };

        $(element).style.width = Math.round((screen.width*ratio)/100)+"px";
        $(element).style.height = Math.round((screen.height*ratio)/100)+"px";
        }catch(err){alert(err);}
    },
    saveAll : function(){
        try{
        if($('bkg_form')) $('bkg_form').submit();
        if( $('general_text')) $('general_text').submit();
        if($('link_text_design')) $('link_text_design').submit();
        if($('header_text_design')) $('header_text_design').submit();
        if($('box_design')) $('box_design').submit();
        }catch(err){
            alert(err);
        }
    },
    resetAll : function(){
        try{
        if($('bkg_form')) $('bkg_form').reset();
        UserChannel.resetBackground();
        if( $('general_text')) $('general_text').reset();
        UserChannel.resetText();
        if($('link_text_design')) $('link_text_design').reset();
        UserChannel.resetLink();
        if($('header_text_design')) $('header_text_design').reset();
        UserChannel.resetHeader();
        if($('box_design')) $('box_design').reset();
        UserChannel.resetBox();
        }catch(err){
            alert(err);
        }
    },
    resetLink : function(){
        UserChannel.linkSize($('link_size').value);
        UserChannel.linkFont($('link_font').value);
        UserChannel.linkStil($('linkStilBold').value,$('linkStilBold').checked);
        UserChannel.linkStil($('linkStilItalic').value,$('linkStilItalic').checked);
        UserChannel.linkStil($('linkStilUnderline').value,$('linkStilUnderline').checked);
        UserChannel.linkColor();

    },
    resetText : function(){
        UserChannel.textSize($('text_size').value);
        UserChannel.textFont($('text_font').value);
        UserChannel.textStil($('textStilBold').value,$('textStilBold').checked);
        UserChannel.textStil($('textStilItalic').value,$('textStilItalic').checked);
        UserChannel.textStil($('textStilUnderline').value,$('textStilUnderline').checked);
        UserChannel.textColor();

    },
    resetHeader : function(){
        UserChannel.headerSize($('header_size').value);
        UserChannel.headerFont($('header_font').value);
        UserChannel.headerStil($('headerStilBold').value,$('headerStilBold').checked);
        UserChannel.headerStil($('headerStilItalic').value,$('headerStilItalic').checked);
        UserChannel.headerStil($('headerStilUnderline').value,$('headerStilUnderline').checked);
        UserChannel.headerColor();

    },
    resetBox : function(){
        UserChannel.borderSize($('border_size').value);
        UserChannel.borderStil($('border_stil').value);
        UserChannel.borderPosition($('border_position').value);
        UserChannel.borderColor();
        UserChannel.headerBkgColor();
        UserChannel.boxBkgColor();

    },
    resetBackground : function(){
     UserChannel.resetImage('preview_cfg_image',$('picture_status').checked);
     UserChannel.imageRepeat('preview_cfg_image',$('repeta_imagine').value);
     UserChannel.backgroundColor();
    },
    rgb:function(a){

        var o=a.toLowerCase();
        return [parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4),16)];
    },
    shade:function(a,b){
        var v=[],i;
        for(i=0;i<3;i++){
            v[i]=Math.round(a[i]*b);
            if(v[i]>255)v[i] = 255;
            if(v[i]<0)v[i] = 0;
        }
        return v;
    },
    hex:function(a){
        var f=UserChannel._hex;
        return f(a[0])+f(a[1])+f(a[2]);
    },
    _hex:function(a){
        return ('0'+a.toString(16)).slice(-2);
    },
    getShades : function(my_color)
    {
        var cc,v=[],n,dark,lite ;
        cc = my_color;
        if(cc.length<6){
            alert('Value must be a 6 character hex value.');
            return;
        }
        n = m.rgb(cc);
        dark = m.hex(m.shade(n,0.8));
        v.push(dark);
        v.push(cc);
        lite = m.hex(m.shade(n,1.2));
        v.push(lite);
    return v;
    }
}



function copy_playlist(event)
{
    Event.stop(event);
    my_form = Event.element(event);
    customParams = my_form.serialize().parseQuery();
    sn_getAjax('copy_playlist', customParams);
}

function sn_copyPlaylistHandler(result, resultElementName, userData)
{

    if (result.code == 0)
    {
        $(result.text.form).style.display = 'none';
        id_msg = 'pl_err_msg';
        Effect.Appear(id_msg, { duration: 2.0 });
        $(id_msg).innerHTML = "Ai salvat cu succes playlist-ul "+userData['playlist_name']+".Il poti asculta in pagina ta, in zona `Playlist-uri`.";
        $(id_msg).className =  "errorMsgDefault";
        Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 5.0});
    }else{
        id_msg = 'pl_err_msg';
        Effect.Appear(id_msg, { duration: 2.0 });
        $(id_msg).innerHTML = "NU s-a putut efectua salvarea!";
        $(id_msg).className =  "errorMsgDefault";
        Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 5.0});
    }
}

function openNameBox(aid)
{
    $('nume_playlist_form_' + aid).style.display='block';
}

submitForm=function(event){
    my_form=Event.element(event);
    Event.stop(event);
    customParams = my_form.serialize().parseQuery();
    userData = my_form.serialize(true);
    sn_getAjax('copy_playlist', customParams, null, userData);
}


function sn_salveazaContentHandler(result, resultElementName, userData)
{
    if(result.code == 0)
    {
        $(result.text.form).style.display = 'none';
    }
}

submitContentForm=function(event){
    my_form=Event.element(event);
    Event.stop(event);
    customParams = my_form.serialize().parseQuery();
    sn_getAjax('salveaza_content', customParams);
}

function sterge_content(aid)
{
    if(confirm("Sigur  vreti sa stergeti materialul?"))
    {
        customParams = {aid: aid};
        sn_getAjax('sterge_content', customParams);
    }
}

function sn_stergeContentHandler(result, resultElementName, userData)
{
    if(result.code == 0)
    {
       result = result.text.evalJSON();
       document.location = result.my_link;
    }
}

function seteaza_content_principal(aid)
{
    params = {aid: aid}
    if(confirm("Sigur  vrei sa promovezi fisierul pe pagina principala?")){
        sn_getAjax('seteaza_content_principal', params,'',params);
    }
}
function sn_seteazaContentPrincipalHandler(result, resultElementName, userData){
 document.location.reload();
}
function input_radio_uncheck(el) {
    if (el.length == 0) el.checked = false;
    for (i = 0; i < el.length; i++) {
        el[i].checked = false;
    }
}

function input_radio_value(el)
{
    if (el.length == 0 && el.checked) return el.value;
    for (i = 0; i < el.length; i++) {
        if (el[i].checked) return el[i].value
    }
    return null;
}

function make_embed_code(e) {
    var el = null, sz = null, sizes, s, tmp, cid, aplay, w, h;
    var asp_ratio = 3/4, b = 28;

    if(typeof(e) != 'undefined') {
        el = Event.element(e);
    }
    var f = $('form_embed');
    if(el && el.name == 'player_embed') return true;
    cid = f.content_id.value;
    //sizes = [[], [320,240], [450,370], [250,130]];
    //sizes = [450, 400, 300];

    var aplay = f.aplay && f.aplay.checked ? '&aplay=true'  : '';
    var color_player = f.color_player && f.color_player.value ? '&rgb=' + f.color_player.value : ''
    var from = (f.from.value != '') ? '&from=' + f.from.value : '';
    if((!el || el && el.name == 'width_custom') && (f.width_custom && /[\d]+/.test(f.width_custom.value))) {
        w = parseInt(f.width_custom.value)
        input_radio_uncheck(f.width_player);
    } else if(f.width_player && input_radio_value(f.width_player) != null) {
        w = parseInt(input_radio_value(f.width_player));
        if (el && el.name != 'width_custom') {
            f.width_custom.value = '';
        }
    } else {
        w = 450;
    }
    if (!(w >= 300 && w <= 450)) {
        f.width_player[0].checked = true;
        f.width_custom.value = '';
        w = 450;
    }

    if (f.ctype.value != '2') {
        h =  Math.round((w * asp_ratio) + b);
    } else {
        h = 106;
    }
    sz = [w, h];

    s = '<embed width="' + sz[0] + '" height="' + sz[1] + '" src="' + SITE_BASE + 'emb/' + cid + color_player + aplay + from + '" ';
    s += 'allowfullscreen="true" allowscriptaccess="always" ';
    s += 'type="application/x-shockwave-flash" ';
    s += '></embed><br><small>Vezi mai multe din <a href="' + f.categ_link.value + '" target="_blank">' + f.categ_name.value + '</a> pe <a href="http://www.220.ro" target="_blank">220.ro</a></small>';

    script = '<script type="text/javascript" src="' + SITE_BASE + 'embjs?id=' + cid + '&width=' + sz[0] + '&height=' + sz[1] + color_player + aplay + from + '"></script>' +
    '<noscript>Vezi <a href="' + f.content_link.value + '" target="_blank">' + f.content_title.value + '</a> pe <a href="http://www.220.ro" target="_blank">220.ro</a></noscript>';

    f.player_embed.value = s;
    f.player_embed2.value = script;
    return true;
}

document.observe("dom:loaded", function() {
        if ($('form_embed')) {
            $('form_embed').getElements().each(function(el){
                if (el.type == 'radio') Event.observe(el, 'click', make_embed_code);
                else Event.observe(el, 'change', make_embed_code);
            });
        }
});


function add_to_group(instance){

    my_form = $('add_to_group_form_' + instance);
    userData = my_form.serialize(true);
    userData['form_id'] = my_form.id;
    userData['instance'] = instance;
    if(userData['group'] == '0') {
        var l = SITE_BASE + 'index.php?module=create_grup&content_id=' + userData['content_id'];

        if(typeof(window.opener) == 'undefined' || window.opener == null) {
            document.location = l;
        } else {
            window.opener.document.location = l;
            window.opener.focus();
        }

        return;
    }
    customParams=my_form.serialize().parseQuery();
    sn_getAjax('add_to_group', customParams, null, userData);
    return;
}

function sn_addToGroupHandler(result, resultElementName, userData)
{
    if(!$('grup_form_msg'))
    {
        var id_msg = 'add_group_msg_' + userData['instance'];
        Effect.Appear(id_msg, { duration: 0.0 });
        $(id_msg).innerHTML = result.text;
        Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
    }else{
        Effect.Appear('grup_form_msg', { duration: 0.0 });
        $('grup_form_msg').innerHTML = result.text;
        Effect.Fade('grup_form_msg', {transition: Effect.Transitions.linear, duration: 4.0});
        if(result.code == 2) setTimeout("reload()",900);
    }
}

function dezaboneaza_subscribe(username){
    params = {uname: username};
    if(confirm("Sunteti siguri ca vreti sa va dezabonati ?"))
        sn_getAjax('dezaboneaza_subscribe',params);
}

function sn_dezaboneazaSubscribeHandler(result, resultElementName, userData)
{

    if(result.code == 1)
    {
        if (window.pageVersion == 3) {
            $('aboneaza_te').toggle();
            $('dezaboneaza_te').toggle();
            var p = $('user').positionedOffset()
            new smallNotif(result.text, {x: p.left + 380, y: p.top - 15}, 'msg_box');
            return;
        }
        var id_msg = 'user_msg' ;
        if($(id_msg)){
            Effect.Appear(id_msg, { duration: 4.0 });
            $(id_msg).innerHTML = result.text;
            $(id_msg).className =  "errorMsgDefault";
            Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
        }

        if(!$('is_not_subscribed') ){
            setTimeout("reload()",1500);
        }else{
            $('is_not_subscribed').style.display ="inline";
        }

        if($('is_subscribed')){
            $('is_subscribed').style.display ="none";
        }

    }
}

function reload(){
    document.location.reload();
}

function remove_subscriber(username){
    params = {uname:username};
    if(confirm("Sunteti siguri ca vreti sa stergeti din lista abonatul ?"))
        sn_getAjax('remove_subscriber',params);
}

function sn_removeSubscriberHandler(result, resultElementName, userData)
{
    if(result.code == 1)
    {
        var id_msg = 'user_msg' ;
        Effect.Appear(id_msg, { duration: 4.0 });
        $(id_msg).innerHTML = result.text;
        $(id_msg).className = "errorMsgDefault";
        Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
        setTimeout("reload()",900);
    }
}

function remove_favorite(aid){
    params = {aid:aid};
    if(confirm("Sunteti siguri ca vreti sa stergeti filmul din lista de favorite ?"))
        sn_getAjax('remove_favorite',params);
}

function sn_removeFavoriteHandler(result, resultElementName, userData)
{ // nu se face redirect !!!!
    if(result.code == 0)
    {
        var id_msg = 'remove_favorite_msg' ;
        Effect.Appear(id_msg, { duration: 4.0 });
        $(id_msg).innerHTML = result.text;
        $(id_msg).className = "errorMsgDefault";
        Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
        setTimeout("reload()",900);
    }
}


function remove_friend(username){
    params = {uname:username};
    if(confirm("Sunteti siguri ca vreti sa il stergeti din lista de prieteni ?"))
        sn_getAjax('remove_friend',params);
}


function remove_request(username){
    params = {uname:username};
    if(confirm("Sunteti siguri ca vreti sa stergeti requestul ?"))
        sn_getAjax('remove_request',params);
}

function sn_removeFriendHandler(result, resultElementName, userData) {
	removeRequestAction(result, resultElementName, userData);
}

function sn_removeRequestHandler(result, resultElementName, userData) {
  removeRequestAction(result, resultElementName, userData);
}

function removeRequestAction(result, resultElementName, userData) {
	var id_msg = 'dezaboneaza_msg' ;
	try {
	    if(result.code == 1) {
	        if (window.pageVersion == 3) {
	            $('stege_prieten').toggle();
	            $('adauga_prieten').toggle();
	            var p = $('user').positionedOffset()
	            new smallNotif(result.text, {x: p.left + 380, y: p.top - 15}, 'msg_box');
	            return;
	        }
	        Effect.Appear(id_msg, { duration: 4.0 });
	        $(id_msg).innerHTML = result.text;
	        $(id_msg).className = "errorMsgDefault";
	        Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
	        if(!$('is_not_friend')) setTimeout("reload()",900);
	    }
	}
	catch(e) {
		if(result) alert(result.text);
			setTimeout("reload()",900);
	}
}

function submitFormWithMyAction(form_id,action) {
	try {
		$(form_id).action = (String.interpret(action));
		$(form_id).submit();
	}
	catch(e) {alert("ERROR HANDLING FORM "+e);}

}


function friendshipRequest(username){
    params = {uname:username};
    sn_getAjax('friendship_request',params);
}

function sn_friendshipRequestHandler(result, resultElementName, userData)
{

    if(result.code == 1 || result.code == 0)
    {
        if (window.pageVersion == 3) {
            if (result.code == 0) {
            } else {
                $('stege_prieten').toggle();
                $('adauga_prieten').toggle();
            }
            var p = $('user').positionedOffset()
            new smallNotif(result.text, {x: p.left + 380, y: p.top - 15}, 'msg_box');
            return;
        }


        var id_msg = 'user_msg' ;
        Effect.Appear(id_msg, { duration: 4.0 });
        $(id_msg).innerHTML = result.text;
        $(id_msg).className ="errorMsgDefault";
        Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
    }
}

function subscribeToUser(username){
    params = {uname:username};
    sn_getAjax('subscribe_request',params);
}

function sn_subscribeRequestHandler(result, resultElementName, userData)
{
    if(result.code == 1 || result.code == 0)
    {
        if (window.pageVersion == 3) {
            var p = $('user').positionedOffset()
            new smallNotif(result.text, {x: p.left + 380, y: p.top - 15}, 'msg_box');
            if (result.code == 0) {
            } else {
                $('aboneaza_te').toggle();
                $('dezaboneaza_te').toggle();
            }
            return;
        }

        var id_msg = 'user_msg' ;
        Effect.Appear(id_msg, { duration: 4.0 });
        $(id_msg).innerHTML = result.text;
        $(id_msg).className ="errorMsgDefault";
        Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
        if($('is_not_subscribed')) $('is_not_subscribed').style.display ="none";
        if($('is_subscribed')) $('is_subscribed').style.display ="inline";
    }
}

// [+] Stars votes
var starsHint = {
    marks: {
        one:    'naspa',
        two:    'slabut',
        tree:   'hai ca merge',
        four:   'misto',
        five:   'genial'
    },
    hint: function(event, act){
        if(act == 1) {
            if(window.isLogged) {
                var el = Event.element(event);
                var ind = (el.classNames() + '').substr(6)
                $('starsMsg').update(window.starsHint.marks[ind]);
                $('starsMsg').show();
            } else {
                $('starsMsg').hide();
                $('starsLog').show();
            }
            $('nr_voturi').hide();
        } else {
            $('starsLog').hide();
            $('starsMsg').update(' voturi').show();
            $('nr_voturi').show();
        }
    }
};
document.observe("dom:loaded", function() {
    if(window.contentId) {
        if(window.isLogged) {
            $$('.stars-holder1 LI A').each(function(a){
                Event.observe(a, 'mouseover', starsHint.hint.bindAsEventListener(a, 1));
                Event.observe(a, 'mouseout', starsHint.hint.bindAsEventListener(a, 0));
            });
        } else {
            $$('.n_rating1').each(function(dv){
                Event.observe(dv, 'mouseover', starsHint.hint.bindAsEventListener(dv, 1));
                Event.observe(dv, 'mouseout', starsHint.hint.bindAsEventListener(dv, 0));
            });
        }
    }
});
// [-] Stars votes

//[+] Zona ajax comentarii pagina profil--------------------
function fetchComments(limit, offset) {
    if (userId) {
        div = $('ajax_comments');
        params = {limit: limit, offset: offset, user_id: userId};
        sn_getAjax('fetch_comments', params, 'ajax_comments');
    }
}

function sn_fetchCommentsHandler(result, resultElementName, userData) {

    if (result.code == 1) {
        result = result.text.evalJSON();
        $(resultElementName).update(result.comments);
        window.ajaxPagination.returnCall(result.nr_messages);
    }
}
//[-] Zona ajax comentarii pagina profil--------------------

function makeSearch(section, q) {
    if (typeof q != 'string' || q.length < 2) {
        alert('Fraza e prea scurta!');
        return;
    }
    var p =  null;
    if (
    section == 'video' ||
    section == 'audio' ||
    section == 'image' ||
    section == 'playlist' ||
    section == 'user'
    ) {
        p = '/' + section;
    }
    if(p != null) {
        window.location.href = SITE_BASE + 'cauta' + '/' + encodeURIComponent(q) + p;
    } else {
        alert('Eroare la cautare');
    }
};

function deblocheaza_user(username){
    params = {uname:username};
    sn_getAjax('deblocheaza_user',params);
}

function sn_deblocheazaUserHandler(result, resultElementName, userData)
{
    if(result.code == 0)
    {
        var id_msg = 'deblocheaza_msg' ;
        if ($(id_msg)) {
            Effect.Appear(id_msg, { duration: 4.0 });
            $(id_msg).innerHTML = result.text;
            $(id_msg).className = "errorMsgDefault";
            Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
            setTimeout("reload()",900);
        }
   		var btn1 = $('btnBlockUnbolck');
        if (btn1) {
   		    var a = $$('#btnBlockUnbolck a')[0];
   		    var user = /.*\([\'\"](.+)[\'\"]\).*/.exec(a.readAttribute('onclick'))[1];
            $('btnBlockUnbolck').update('<a class="bNone user_link10" href="javascript:void(0)" onclick="block_user(\'' + user + '\')" rel="nofollow" title="Blocheaza utilizator">Blocheaza utilizator</a>')
   		    new MessageBox('msgBlockUnbolck', 'Deblocheaza utilizator', result.text);
        }
    }
}

function titleForUrl(title) {
    title = title.replace(/^\s+|\s+$/gm, '');
	title = title.replace(/[^\w]+/gm, ' ');
	title = title.replace(/^(.)|\s(.)/gm, function ($1) {return $1.toUpperCase();});
	return title.replace(/\s/gm, '-');
}

function gea_mobile(username){
    params={username:username}
    sn_getAjax('gea_mobile',params);
}

function sn_geaMobileHandler(result, resultElementName, userData){
    if(result.code == 1){
        $('email_addres').update(result.text);
    }
}

function sterge_comment(comment_id)
{

    params={ cid:comment_id };
    if(confirm("Sunteti siguri ca vreti sa stergeti acest comment?")){
        sn_getAjax('sterge_comment',params, 'ajax_comments');
    }
}

function sn_stergeCommentHandler(result, resultElementName, userData){

    if(result.code == 1)
    {

        result = result.text.evalJSON();
        $(resultElementName).update(result.comments);
        window.ajaxPagination.returnCall(result.nr_messages);
    }
}

var ptimeUpd = {
    states: [],
    send : function(id, s) {
        if (typeof window['sn_pltimeUpdHandler'] == 'undefined') {
            window['sn_pltimeUpdHandler'] = function (){}
        }
        if (this.states[id] != 1 && /^[a-zA-Z0-9]{10,10}$/.test(id) && s > 0) {
            ptimeUpd.states[id] = 1;
            sn_getAjax('pltime_upd', {'aid': id, 'dur': s}, null, {'id': id});
        }
    }
}

var Smilies = {
    enabled: 1,
    selfDo: 0,
    imgPath: SITE_BASE + '_templates/_default/img/sml/',
    classApply: 'emoticable',
    smilies: {":-":"7", ":)":"1", ":-)":"1", "(-:":"1", "(:)":"1", ":(":"2", ":-(":"2", ":(":"2", ";)":"3", ";-)":"3", ":D":"4", ";-D":"4", ";;)":"5", ";;-)":"5", "<:D>":"6", ":-/":"7", ":S":"7", ":X":"8", ":-X":"8", "(L)":"8", ":\">":"9", ":$":"9", ":-P":"10", ":P":"10", ":-*":"11", ":*":"11", "(K)":"11", "=((":"12", "(U)":"12", ":-O":"13", ":O":"13", "X-(":"14", "X(":"14", ":@":"14", ":->":"15", ":>":"15", "B-)":"16", "(H)":"16", ":-S":"17", "#:-S":"18", ">:)":"19", "(6)":"19", ":((":"20", ":-((":"20", ":'(":"20", ":))":"21", ":-))":"21", ":|":"22", ":-|":"22", "/:)":"23", "/:-)":"23", "^O)":"23", "=))":"24", "O:-)":"25", "0:-)":"25", "O:)":"25", "0:)":"25", "(A)":"25", ":-B":"26", ":B":"26", "=;":"27", "I-)":"28", "|-)":"28", "8-|":"29", "8-)":"29", "L-)":"30", ":-&":"31", "+O(":"31", ":-$":"32", ":-#":"32", "[-(":"33", ":O)":"34", ":0":"34", "<@:)":"34", "8-}":"35", "<:-P":"36", "<:O)":"36", "(:|":"37", "(:}":"37", "=P~":"38", ":-?":"39", "*-)":"39", "#-O":"40", "=D>":"41", ":-SS":"42", "@-)":"43", ":^O":"44", ":-W":"45", ";-<":"46", ">:P":"47", "<):)":"48", ":@)":"49", "3:-O":"50", ":(|)":"51", "~:>":"52", "@};-":"53", "%%-":"54", "**==":"55", "(~~)":"56", "~O)":"57", "*-:)":"58", "8-X":"59", "=:)":"60", "=:-)":"60", ">-)":"61", ":-L":"62", "[-O<":"63", "$-)":"64", ":-\"":"65", "B-(":"66", ":)>-":"67", "[-X":"68", ":D/":"69", ">:/":"70", ";))":"71", "O->":"72", "O=>":"73", "O-+":"74", "(%)":"75", ":-@":"76", "^:)^":"77", ":-J":"78", "(*)":"79", ":)]":"100", ":-C":"101", "~X(":"102", ":-H":"103", ":-T":"104", "8->":"105", ":-??":"106", "%-(":"107", ":O3":"108", "X_X":"109", ":!!":"110", "\M/":"111", ":-Q":"112", ":-BD":"113", "^#(^":"114", ":BZ":"115"},
    sml4Pad: {':))':'21', '=))':'24', ';)':'3', ':D':'4', ';;)':'5', '=D>':'41', ';))':'71', '8->':'105', ':$':'9', ':P':'10', ':*':'11', ':X':'8', ':-O':'13', '<:D>':'6', ':>':'15', 'B-)':'16', '(*)':'79', ':-BD':'113', '^:)^':'77', ':-H':'103', ':)':'1', '/:)':'23', '<):)':'48', 'O:)':'25', ':B':'26', '=;':'27', 'I-)':'28', '8-)':'29', ':)>-':'67', ':-SS':'42', ':-$':'32', 'M/':'111', '$-)':'64', '8-}':'35', '<:-P':'36', ':D/':'69', '=P~':'38', '*-)':'39', '#-O':'40', ':-/':'7', ':-J':'78', '@-)':'43', ':^O':'44', '[-(':'33', ':O)':'34', ':-S':'17', '#:-S':'18', ':@)':'49', '3:-O':'50', ':(|)':'51', '~:>':'52', '@};-':'53', '%%-':'54', '**==':'55', '(~~)':'56', '~O)':'57', '*-:)':'58', '8-X':'59', '=:)':'60', '>-)':'61', ':-L':'62', '[-O<':'63', ';-<':'46', 'B-(':'66', ':-W':'45', '[-X':'68', ':((':'20', '>:/':'70', '>:P':'47', 'O->':'72', 'O=>':'73', 'O-+':'74', '(%)':'75', ':-@':'76', ':-&':'31', '=((':'12', ':(':'2', ':)]':'100', ':-C':'101', '~X(':'102', 'L-)':'30', ':-T':'104', ':-??':'106', ':O3':'108', 'X_X':'109', ':!!':'110', 'X(':'14', ':-Q':'112', '(:|':'37', '^#(^':'114', ':BZ':'115', '%-(':'107', ':|':'22',  ':-"': '65'},
    smlPrep: {},
    smlRev: {},
    sChars: {"<":"&LT;", ">":"&GT;", "&": "&AMP;"},
    ptr: null,
    init: function(){
        if (!this.enabled) return;
        if (this.ptr == null) {
            this.ptr = '';
            for (var i in this.smilies) {
                this.ptr = (i.replace(/([\W])/g, "\\$1")) + "|" + this.ptr;
                this.smlPrep[i.replace(/<|>|&/g, function($m) {return Smilies.sChars[$m]})] = this.smilies[i];
            }
            for (var i in this.sml4Pad) {
                this.smlRev[this.sml4Pad[i]] = i;
            }
            this.ptr = this.ptr.substr(0, this.ptr.length-1);
            this.ptr = this.ptr.replace(/<|>|&/g, function($m) {return Smilies.sChars[$m]});
        }
        if (this.selfDo) {
            document.observe("dom:loaded", function() {
                Smilies.replace();
            });
        }
    },
    _replace: function(text) {
        if (!this.enabled) return;
        var re = new RegExp (this.ptr, "gmi");
        text = (' ' + text + ' ').replace(re, function ($m) {return '<img class="sml_img" src="' + Smilies.imgPath + Smilies.smlPrep[$m.toUpperCase()] + '.gif">'});
        return text.substr(1, text.length - 2);
    },
    replace: function(addSel){
        if (!this.enabled) return;
        var selector = (typeof(addSel) != 'undefined') ? addSel :  Smilies.classApply;
        $$(selector).each(function(dv) {
            if (typeof (dv.innerHTML) != 'undefined') dv.update(Smilies._replace(dv.innerHTML));
        });
    },
    _reverseReplace: function(text) {
        if (!this.enabled) return;
        text = (' ' + text + ' ').replace(/<img\s+class="?sml_img"?\s+src\=".*?\/([0-9]+)\.gif">/gmi, function ($f, $m) {return Smilies.smlRev[$m] != undefined ? Smilies.smlRev[$m] : '';});
        return text.substr(1, text.length - 2);
    },
    reverseReplace: function(addSel){
        if (!this.enabled) return;
        $$(addSel).each(function(dv) {
            if (typeof (dv.innerHTML) != 'undefined') dv.update(Smilies._reverseReplace(dv.innerHTML));
        });
    },
    sPad: null,
    pTarget: null,
    pTargetList: [],
    showPad: function(trEv, target){
        if (!this.enabled) return;
        if(this.sPad && this.sPad.visible()) {this.hidePad();return;}
        if(!this.sPad) {

            var text = '<div id="smilePadCont" class="sCont">';
            var j = 0;
            for (var i in this.sml4Pad) {
                if (i.indexOf('"') != -1) continue;
                if(j++ == 50) {
                    text += '</div><div class="sCont" id="smilePadExt" style="display: none;">';
                }
                text += '<div><img src="' + Smilies.imgPath + Smilies.smilies[i] + '.gif" onclick="Smilies.insertEmo(\'' + i +'\'); return false;"></div>'
            }
            text += '</div><div id="btns"><a href="#" onclick="Smilies.hidePad(); return false;" title="Close">X</a><br>'
            + '<a href="#" onclick="Smilies.padExtend(); return false;" id="smilePadTglBtn" title="Extend">&gt;</a></div>';
            this.sPad = new Element('div', {'id': 'smiliesPad'});
            document.body.appendChild(this.sPad.update(text));
        }
        else {
            this.sPad.show();
        }
        this.pTarget = target;
        if(this.pTargetList[this.pTarget] !== 1) {
            Event.observe($(this.pTarget), 'click', Smilies.hidePad.bindAsEventListener());
            this.pTargetList[this.pTarget] = 1;
        }
        var XY = Element.cumulativeOffset(Event.element(trEv));
        var posX = XY[0] + 'px', posY =  XY[1]-245 + 'px';
        this.sPad.setStyle({'left': posX, 'top': posY});
    },
    hidePad: function() {
        if(Smilies.sPad) {
            Smilies.sPad.hide();
            if($(this.pTarget)) $(this.pTarget).focus();
        }
    },
    padExtend: function(){
        if(Smilies.sPad) {
            $('smilePadExt').toggle();
            if($('smilePadExt').visible()) {
                $('smilePadTglBtn').update('&lt;');
                $('smiliesPad').setStyle({'width': '390px'});
            }
            else {
                $('smilePadTglBtn').update('&gt;');
                $('smiliesPad').setStyle({'width': '205px'});
            }
        }
    },
    insertEmo: function(e) {
        if (!this.enabled) return;
        insertText($(this.pTarget), e);
        this.hidePad();
    }
}
Smilies.init();

document.observe("dom:loaded", function() {
    window.domLoaded = true;
});


function resizePreview(size){
  if($('previewer')){
      var my_size = parseInt($('previewer').height) + size;
      $('previewer').height = my_size;
  }
   if($('div_previewer')){
      var my_size = parseInt($('div_previewer').style.height) + size;
      $('div_previewer').style.height = my_size+'px';
  }
}

function colorPickerScripts() {

    cpc = new Element('div', {'id': 'color_picker_container_1' , 'class':'colorPick_box','style' : 'display:none'});
    document.body.appendChild(cpc);
    var jss = ["js/colorpicker/colormethods.js", "js/colorpicker/colorvaluepicker.js", "js/colorpicker/slider.js", "js/colorpicker/colorpicker.js"];
    var x, hd = document.getElementsByTagName('head')[0];
    /*
    new Ajax.Request(WEB_BASE + jss[0], {method: 'get', onSuccess: function(t){CPicker.loadPickerPhase2();
    new Ajax.Request(WEB_BASE + jss[1], {method: 'get', onSuccess: function(t){CPicker.loadPickerPhase2();
    new Ajax.Request(WEB_BASE + jss[2], {method: 'get', onSuccess: function(t){CPicker.loadPickerPhase2();
    new Ajax.Request(WEB_BASE + jss[3], {method: 'get', onSuccess: function(t){CPicker.loadPickerPhase2();
    }}); }}); }}); }});
    */
    $A(jss).each(function(i){
        x = document.createElement('script');
        x.src = WEB_BASE + i;
        hd.appendChild(x);
    });
    sn_getAjax('load_picker',{},'color_picker_container_1', CPicker.userData);
}

var CPicker = {
    fetch_js : 1,
    picker_loaded : false,
    picker_loadedPhase2 : 0,
    loadPicker : function(posX,posY,act,id){
        if (!this.picker_loaded) {
            this.picker_loaded = true;
            params={}
            CPicker.userData ={posX:posX,posY:posY,act:act,id:id};
            if(this.fetch_js){//----------------add the javascript for the color picker-----------------
                this.fetch_js = 0;
                colorPickerScripts();
            }
        }else{
             this.togglePicker(posX,posY,act,id);
        }

    },
    loadPickerPhase2: function(){
      if (++this.picker_loadedPhase2 != 4) return;

      sn_getAjax('load_picker',{},'color_picker_container_1', CPicker.userData);
    },
    togglePicker:function(posX,posY,act,id){
        var cont = 'color_picker_container_1';

        if (act == 'show') {
            if ($('cp1_Hex')) $('cp1_Hex').setAttribute('id', 'id_temp');
            $$('.id_cp' + id).each(function(inp) {
                inp.setAttribute('id', 'cp1_Hex');
            });
        }

        Element.absolutize(cont);
        if(act != 'hide'){
        $(cont).setStyle({'left': posX, 'top': posY});
        }
        color_picker = null;
        $('cp1_ColorMap').update('');
        $('cp1_ColorBar').update('');
        $$('.color_picker_arrow').each(function(el){Element.remove(el);});

        if($(cont)){
            if($(cont).visible()){
                $(cont).hide();
                $$('img.color_picker_arrow').invoke('hide');
            }
            else{
                $(cont).show();
                $$('img.color_picker_arrow').invoke('show');

                color_picker = new Refresh.Web.ColorPicker('cp1', {startHex: 'b9121b', startMode:'s'});
            }
        }
       if(act == 'hide'){
           if($('form_embed')) make_embed_code();
           if($('form_vchannel')) make_embed_wm();
           try
           {
                   UserChannel.backgroundColor();
                   UserChannel.linkColor();
                   UserChannel.headerColor();
                   UserChannel.textColor();
                   UserChannel.borderColor();
                   UserChannel.headerBkgColor();
                   UserChannel.boxBkgColor();

           }catch(err){}
        }
    }
}

function sn_loadPickerHandler(result, resultElementName, userData){
    $(resultElementName).update(result);
    CPicker.togglePicker(userData['posX'],userData['posY'],userData['act'],userData['id']).defer();
}

function sterge_raspuns_video(content_response_to, id){
    if(confirm('Sunteti sigur ca vreti sa stergeti acest raspuns video ?')) {
        params = {content_response_to: content_response_to,content_id: id};
        sn_getAjax('sterge_raspuns_video', params);
    }
    return;
}

function sn_stergeRaspunsVideoHandler(result, resultElementName, userData){
    var id_msg = 'mesaj_ok' ;
    Effect.Appear(id_msg, { duration: 4.0 });
    $(id_msg).update(result.text);
    Effect.Fade(id_msg, {transition: Effect.Transitions.linear, duration: 2.0});
    setTimeout("reload()",900);
}

var minFPVer =  "9.0.115";
var recomFPVer =  "10.0.0";
var SNotices = {
	close: function(id,place) {
		if ($(place)) Effect.SlideUp(place, {duration: 0.3});
		Cookies.create(id, '1', 2)
	}
}


function abonare_show(aid, status) {
    params = {aid: aid, status: status}
    sn_getAjax('abonare_show', params);
}

function sn_abonareShowHandler(result, resultElementName, userData){
    if(result.code == 0){
        var inner = (result.text.status)?"Dezaboneaza-te":"Aboneaza-te";
        var text = (result.text.status )?"Te-ai abonat cu succes!":"Te-ai dezabonat cu succes!";
        var status = (result.text.status )?0:1;
        var a = Builder.node('a', {className:'abshow', onclick:'abonare_show(\''+result.text.show_id+'\',\''+status+'\');', href:'javascript:void(0);'}, [inner]);
        $('abonare_show').innerHTML ="";
        $('abonare_show').appendChild(a);
        $('abonare_mesaj').style.display = "block";
        $('abonare_mesaj').update(text);
        setTimeout(function(){$('abonare_mesaj').update('');$('abonare_mesaj').style.display = "none";},4000);
    }
}

/*widget provari*/
function fetchPromovariShows(limit, offset,userData ) {
    if(limit != 0 && window.ajaxPagination.interval){
           window.ajaxPagination.interval.stop();
           window.ajaxPagination.offset = offset;
           window.ajaxPagination.interval = null;
           if(window.ajaxPagination.timeout){
               clearTimeout(window.ajaxPagination.timeout);
           }
           if(num_promo > 1){
            window.ajaxPagination.timeout = setTimeout(function(){new PeriodicalExecuter(promo_widget_interval,4);},10000);
           }
    }else{
         var cur_pag = offset + 1;
         window.ajaxPagination.startPage = cur_pag;
    }

     $$('.promo_show').each(function(el){
         if(el.style.display == 'block'){
             el.style.display = 'none';
         }
     });
    try{
        $('promo_show_'+offset).style.display = 'block';
        window.ajaxPagination.returnCall(num_promo);
    }catch(e){}
}

function promo_widget_interval(pe){
    if(!window.ajaxPagination.interval){
        window.ajaxPagination.interval = pe;
    }
    window.ajaxPagination.offset += 1;
    if(window.ajaxPagination.offset >= num_promo){
        window.ajaxPagination.offset = 0;
    }
    fetchPromovariShows(0,window.ajaxPagination.offset,null);//limit 0 because is an automatic call
    return;
}

function toggleShowDescription(){
	try{
		if($('desriere_show').style.display != "none"){
		 	$('desriere_show').style.display = 'none';
		 	$('desriere_show_big').style.display = 'block';
		 	$('desc_show').style.width = "940px";
		}else{
			$('desriere_show').style.display = 'block';
		 	$('desriere_show_big').style.display = 'none';
		 	$('desc_show').style.width = "310px";
		}
	}catch(e){}
}


var getPageDimensions = function() {
	var xScroll, yScroll, windowWidth, windowHeight, pageDimensions = {};
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else {
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	if (self.innerHeight) {
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	if(yScroll < windowHeight){
		pageDimensions.height = windowHeight;
	} else {
		pageDimensions.height = yScroll;
	}
	if(xScroll < windowWidth){
		pageDimensions.width = windowWidth;
	} else {
		pageDimensions.width = xScroll;
	}
	return pageDimensions;
}

var MessageBox =  Class.create({
	// callbacks {'ok': 'name of function callback', 'cancel': 'name of function callback'}
	open: function(){
		var nd;
		if (typeof message == "object") message = message.join('<br>');
		if (!$(this.id)) nd = new Element('DIV', {'id': this.id});
		nd.update('\
		<div class="msg_box_cont" style="height:' + getPageDimensions().height + 'px;" onclick="window[\'' + this.id +'\'].blink();"></div>\
		<table cellspacing="0" cellpadding="0" border="0" class="box_msg">\
        <tr>\
            <td class="top-left"></td>\
            <td class="top"></td>\
            <td class="top-right"></td>\
        </tr>\
        <tr>\
            <td class="left"></td>\
            <td class="boxy-inner">\
                <div class="title-bar" style="-moz-user-select: none;">\
                    <h5 class="h5_msg_box">' + this.title + '' + (this.callback['x'] ? '<a class="content inchide" style="float:right;margin-top: 4px;" href="javascript:void(0);" onclick="window[\'' + this.id +'\'].callback.x();" id="bXMB' + this.id +'">' + this.callbackLabels['x'] + '</a>' : '') +'</h2>\
                </div>\
                <div style="display: block;" class="boxy-content">\
                	<div class="msg_box_desc">' + this.message +'</div>\
                    ' + (this.callback['ok'] ? '<a class="close_nsg_box" href="javascript:void(0);" onclick="window[\'' + this.id +'\'].callback.ok();" id="bOkMB' + this.id +'">' + this.callbackLabels['ok'] + '</a>' : '') +'\
                    ' + (this.callback['cancel'] ? '<a class="close_nsg_box" href="javascript:void(0);" onclick="window[\'' + this.id +'\'].callback.cancel();" id="bClsMB' + this.id +'">' + this.callbackLabels['cancel'] + '</a>' : '') +'\
                </div>\
            </td>\
            <td class="right"></td>\
        </tr>\
        <tr>\
            <td class="bottom-left"></td>\
            <td class="bottom"></td>\
            <td class="bottom-right"></td>\
        </tr>\
</table>\
		');
		document.body.appendChild(nd);
		this.positionCenter();
		if ($('bOkMB' + this.id)) $('bOkMB' + this.id).focus();
        if ($('bClsMB' + this.id)) $('bClsMB' + this.id).focus()
	},
	close: function(callbacks){
	    Event.stopObserving(document, 'keyup', this.keyUpBinder);
	    if (callbacks) {//dirty way
	        if (this.callback['cancel']) this.callback['cancel']();
	        else if ((this.callback['x'])) this.callback['x']();
	    }
	    if($(this.id)) $(this.id).remove();
		window[this.id] = null;
	},
	blink: function() {
	    var b = $$('#' + this.id + ' .boxy-content')[0];
	    if (!b) return;
	    b.setStyle({'backgroundColor': '#F1EF36'});
	    setTimeout(function(){b.setStyle({'backgroundColor': '#FFFFFF'});}, 200);
	},
	positionCenter: function(){
		if (!$(this.id)) return;
		var boxDim = {x: 420, y: 120}
		var new_pos_x =  Math.round(document.viewport.getScrollOffsets()[0] + (document.viewport.getDimensions()['width'] * 0.5) - (boxDim.x/2));
		var new_pos_y =  Math.round(document.viewport.getScrollOffsets()[1] + (document.viewport.getDimensions()['height'] * 0.4) - (boxDim.y/2));
		$$('#' + this.id + ' table')[0].setStyle({'top': 200 + 'px', left: new_pos_x  + 'px'});
	},
	onKeyUp: function(e) {
	    e = e || window.event;
	    var code = e.keyCode || e.charCode || e.which;
	    if (code == 27) this.close(1);
	},
	//init
	initialize: function(id, title, message, callbacks) {

	    if (arguments.length == 1) {
   	        message = arguments[0];
	        id = 'mb_' + Math.floor(Math.random() * 10000000000);
 	        title = 'Notificare';
	    }

	    this.id = id;
		this.title = title;
		this.message = message
		var self = this;
		this.callback = {};
		this.callbackLabels = {ok: 'ok', cancel: 'close'};
		if (callbacks)  {
		    if (callbacks['ok']) {
		        this.callback['ok'] = function() {
		            callbacks['ok'][1]();
		            if(!callbacks['ok']['dontClose']) self.close();
		        };
		        this.callbackLabels['ok'] = callbacks['ok'][0];
		    }
		    if (callbacks['cancel'])  {
		        this.callback['cancel'] = function() {
		            callbacks['cancel'][1]();
		            if(!callbacks['cancel']['dontClose']) self.close();
		        };
		        this.callbackLabels['cancel'] = callbacks['cancel'][0];
		    }
		    if (callbacks['x']) {
		        this.callback['x'] = function() {
		            callbacks['x'][1]();
		            if(!callbacks['x']['dontClose']) self.close();
		        };
		        this.callbackLabels['x'] = callbacks['x'][0];
		    }
		}
		if (!this.callback['ok'] && !this.callback['cancel'] && !this.callback['x']) {
		    this.callback['ok'] = function() {self.close()};
		}
		//Event.observe(window, 'scroll', function(){self.positionCenter();});

		window[this.id] = this;
		this.open();
		this.keyUpBinder = this.onKeyUp.bindAsEventListener(this);
		Event.observe(document, 'keyup', this.keyUpBinder);
	}
});


function block_user(username){
	var params = {username: username};
	var userData = {'fromComment': arguments[1]};
	sn_getAjax('block_user', params, null, userData);
}

function sn_blockUserHandler(result, resultElementName, userData){
	if(result.code == 0){
	    if ($('content')) {
	        $('content').update(result.text);
	        setTimeout("$('report').remove()",1500);
	    }

		var btn1 = $('btnBlockUnbolck');
		if (btn1) {
		    var a = $$('#btnBlockUnbolck a')[0];
		    var user = /.*\([\'\"](.+)[\'\"]\).*/.exec(a.readAttribute('onclick'))[1];
		    $('btnBlockUnbolck').update('<a class="bNone user_link9" href="javascript:void(0)" onclick="deblocheaza_user(\'' + user + '\')" rel="nofollow" title="Deblocheaza utilizator">Deblocheaza utilizator</a>')
		    new MessageBox('msgBlockUnbolck', 'Blocheaza utilizator', result.text);
		}

		if(userData.fromComment && $(userData.fromComment)) {
		    $(userData.fromComment).remove();
		    new MessageBox('msgBlockComment', 'Blocheaza utilizator', result.text);
		}
	} else {
		    new MessageBox('msgBlockComment', 'Blocheaza utilizator', result.text);
	}

}

function addFriends() {
   try {
       var ids = [];
       $$('INPUT[type="checkbox"]:checked ').each(function(el){
            ids.push(el.value);
        });
        if (!(ids.length > 0)) {
        	new MessageBox('adauga_prieteni', 'Eroare', 'Nu ati selectat niciun user');
        	return;
        }
       	addFriendsIds(ids);
   } catch(e) {
       //alert(e);
   }
}

function addFriendsIds(ids){
    if (typeof ids == 'object') {
		ids =  ids.join(',');
	}
	var params = {users_names:ids};
	sn_getAjax('add_friends_msg',params);
}

function sn_addFriendsMsgHandler(result, resultElementName, userData){
	if(result.code == 1){
		new MessageBox('raportare_spam', 'Eroare', result.text);
		return;
	}else if(result.code == 0){
        window.location = SITE_BASE + "index.php?module=mesagerie&folder=inbox";
	}

}

function add_avatar(){
    var url=SITE_BASE+"index.php?module=profile&action=edit&what=2";
    var loader=SITE_BASE+"_templates/_default/img/upload_loader.gif";
    var str='<body><p id="f1_upload_process" style="display:none">Loading...<br/><img src="'+loader+'" /></p><p id="result" class="errUpl red"></p><div id="form"><form action="'+url+'" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >File: <input name="myfile" id="myfile" type="file" /><input type="submit" name="submitBtn" value="Upload" /></form></div><iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe></body>';
    new MessageBox('uploadAvatar', 'Adaugare avatar', str, {ok: ['OK', reloadComments]});
}

function startUpload(){
    if ($('myfile').value.length < 3) {
        $('result').update('Trebuie sa selectati o imagine !')
        return false;
    } else {
        $('f1_upload_process').show();
        $('form').hide();
    }
    return true;
}

function reloadComments() {
    window.ajaxPagination.gotoPage(window.ajaxPagination.startPage);
}

function stopUpload(success){
    var result = '';
    if (success == 1) {
        $('result').innerHTML =
        '<span class="msg">Avatarul a fost adaugat !<\/span><br/><br/>';
        //setTimeout("$('schimbaAvatarC').remove()",1500);
    } else {
        $('result').innerHTML = '<span class="emsg">A aparut o problema la upload !<\/span><br/><br/>';
    }
    $('f1_upload_process').style.visibility = 'hidden';
    return true;

}

var trackSource = {
    cName: 'trSrc',
    checkerAdd: function(tr) {// tr must be of form: {check:function(){}}
        if (typeof tr == 'object' && typeof tr.check == 'function') {
            var v = tr.check();
            if (v !== false) {
                trackSource.set(v);
            }
        }
    },
    set: function(v) {
        Cookies.create(this.cName, v);
    },
    get: function() {
        return Cookies.read(this.cName);
    }
}

var addLolzTrCheck = {
    nls: ['2946', '2974', '2980', '3112', '3174', '3175', '3176', '3212'],
    check: function() {
        prm = document.location.href.toQueryParams();
        if(prm) {
            if (prm.utm_campaign && prm.utm_campaign.substr(11) == '1756' && this.nls.indexOf(prm.nl_id) != -1) {
                return 'nl' + prm.nl_id;
            }
            else if (prm.utm_campaign && this.nls.indexOf(prm.utm_campaign.substr(11)) != -1) {
                return 'nl' + prm.utm_campaign.substr(11);
            }
        }
        return false;
    }
}
//trackSource.checkerAdd(addLolzTrCheck);

document.observe("dom:loaded", function() {
(function(){//lolz banner
    if(!window.ctPlDet || window.ctPlDet.ctype != 1) return;
    var el = $$('DIV.content_det')[0];
    if (!el) return;
    var a = $$('#user_stats a')[0];
    if (a && /\/CronicaCarcotasilor\//.test(a.href)) {
        //el.insert({bottom: new Element('div', {'id': 'promovare_carca'}).update('<a href="http://cronica.primatv.ro/tv/din-15-septembrie-un-nou-sezon-de-cronica-la-prima-tv.html?play=1" id="promovare_carca_bann" target="_blank"></a>')});
        return;
    } else if (a && /\/DaKINO\//.test(a.href)) {
        el.insert({bottom: new Element('div', {'id': 'promovare_dakino'}).update('<a href="http://iff.dakino.ro/" id="promovare_dakino_bann" target="_blank">&nbsp;</a>')});
        return;
    }
    var cook = Cookies.read('dp_lolz');
    if (cook) return;
    el.insert({bottom: new Element('div', {'id': 'promovare_lolz'}).update('<a href="' + SITE_BASE + 'index.php?module=alert_special&action=configure" id="lolz">&nbsp;</a><a href="javascript:void(0)" onclick="Cookies.create(\'dp_lolz\', \'1\', 7);$(\'promovare_lolz\').remove()" id="inchide_lolz">&nbsp;</a>')});
})();
});

var RoundBox = function(text) {
    var tpl = '\
    <div class="rounded-box">\
    <div class="rb-top-left-corner"><div class="rb-top-left-inside">&bull;</div></div>\
    <div class="rb-bottom-left-corner"><div class="rb-bottom-left-inside">&bull;</div></div>\
    <div class="rb-top-right-corner"><div class="rb-top-right-inside">&bull;</div></div>\
    <div class="rb-bottom-right-corner"><div class="rb-bottom-right-inside">&bull;</div></div>\
    <div class="rb-box-contents">[boxcontent]</div>\
    </div>'
    return tpl.replace(/\[boxcontent\]/, text);
};

var ATTip = {
    show: function(el, text) {
        if (arguments.length == 3) {
            el = arguments[1];
            text = arguments[2];
        }
        if (! $(el)) return;
        if (! $(el.attId) && text == '') return;
        if (! el.attId) {
            el.attId = 'ttid_' + (new Date()).getTime() + Math.floor(Math.random() * 3);
            if (el.title) el.title = '';
            if (el.alt) el.alt = '';
            var dv = new Element('div', {'id': el.attId, style: 'border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius:5px; box-shadow: 1px 1px 2px #666666, 0 0 5px #000000 inset; -webkit-box-shadow: 1px 1px 2px #666666, 0 0 5px #000000 inset; -moz-box-shadow: 1px 1px 2px #666666, 0 0 5px #000000 inset; background:#B9121A; border:2px solid #fff; color:#fff; display:block; font-size:11px; filter:alpha(opacity=85); -moz-opacity:0.85; -webkit-opacity: 0.85; opacity: 0.85; padding: 3px 7px 3px 7px; overflow-x: hidden; text-align:center; width: 100px; position: absolute; z-index: 1002; top:' + (parseInt(el.positionedOffset().top) - 30) + 'px; left:' + el.positionedOffset().left + 'px;'});

            document.body.appendChild(dv.update(text));
            dv.setStyle({top: (parseInt(el.positionedOffset().top) + el.getHeight()) + 'px'});
            Event.observe(el.attId, 'mouseover', this.show.bindAsEventListener(null, el, null));
            Event.observe(el.attId, 'mouseout', this.hide.bindAsEventListener(null, el, null));
            Event.observe(el, 'mouseout', this.hide.bindAsEventListener(null, el, null));
        }
        $(el.attId).show();
    },
    hide: function(e, el) {
        if (! el.attId) return;
        $(el.attId).hide();
    }
};


Ajax.CachedAutocompleter = Class.create();
Object.extend(Object.extend(Ajax.CachedAutocompleter.prototype, Autocompleter.Base.prototype), (function (){
    var auto_complete_cache = {};

    return {
        initialize: function(element, update, url, options) {
            if (!Prototype.Browser.IE) Event.observe(element, 'keydown', this.onKeyPress2.bindAsEventListener(this));
            this.baseInitialize(element, update, options);
            this.options.asynchronous  = true;
            this.options.onComplete  = this.onComplete.bind(this);
            this.options.defaultParams = this.options.parameters || null;
            this.url  = url;
            this.options.workSpace = this.options.workSpace || (this.element.id || this.element.name);
            if (auto_complete_cache[this.options.workSpace] === undefined) {
                auto_complete_cache[this.options.workSpace] = {};
            } else if (Object.values(auto_complete_cache[this.options.workSpace]).length >= 5000) {
                auto_complete_cache[this.options.workSpace] = {};
            }
            if (Prototype.Browser.IE) Event.observe(element, 'keydown', this.onKeyPress2.bindAsEventListener(this));
        },

        onKeyPress2: function(event) {
            switch(event.keyCode) {
                case Event.KEY_RETURN:
                this.active = false;
                return;
            }
        },

        getUpdatedChoices: function() {
            this.startIndicator();
            var t = this.getToken();
            if(auto_complete_cache[this.options.workSpace][t]) {
                this.updateChoices(auto_complete_cache[this.options.workSpace][t]);
            } else {
                entry = encodeURIComponent(this.options.paramName) + '=' +
                encodeURIComponent(t);

                this.options.parameters = this.options.callback ?
                this.options.callback(this.element, entry) : entry;

                if(this.options.defaultParams)
                this.options.parameters += '&' + (typeof this.options.defaultParams == 'string' ? this.options.defaultParams : Object.toQueryString(this.options.defaultParams));
                new Ajax.Request(this.url, this.options);
            }
        },
        onComplete: function(request) {
            var rsp = request.responseJSON, txt = '';
            txt = '<ul><li>' + rsp[1].join('</li><li>') + '</li></ul>';
            this.updateChoices(auto_complete_cache[this.options.workSpace][this.getToken()] = txt);
        }
    }
}()));

if ($('input_cautare_top')) {
	var input_cautare_top_sugg = new Ajax.CachedAutocompleter('input_cautare_top', 'input_cautare_top_sugg', SITE_BASE + '?module=opensuggest&format=json&add_info=link', {autoSelect: false, paramName: 'q', minChars: 3, method: 'GET', frequency: 0.6, afterUpdateElement: function(t, el) {makeSearch('video', t.value);}});
}

document.observe("dom:loaded", function() {
    $$('.disabled_js_div').each(function(d) {
        var ins = new Element('div');
        d.insert({after: ins});
        ins.setStyle('background-color: #000000; position: absolute; filter: alpha(opacity=05); opacity: .05; color: #FFFFFF; z-index:' + (d.style.zIndex + 1) + ';top: ' + d.cumulativeOffset().top + 'px; left:' +  d.cumulativeOffset().left + 'px; height:' + d.getHeight() + 'px; width:' + d.getWidth() + 'px;');
    });
});

//deprecated
var menuTopSections = {
    timeoutDelay: 1000,
    timeoutFn: [],
    menuStats: [],
    init: function() {
        var els = new Hash({'video': 'toate filmele', 'muzica': 'toata muzica', 'comunitate': 'toate grupurile'});
        var ptr = new RegExp (SITE_BASE.replace(/([\W])/g, "\\$1") + '([a-z]+)\/?.*', 'i');
        var section, el, tmp, size, i;
        $$('div#meniu>a').each(function(a){
            section = ptr.exec(a.href);
            if (section == null) return;
            section = section[1];
            if(els.keys().indexOf(section) == -1) return;
            if ($('footer_categ_' + section) == null) return;
            el = new Element('div', {'id': 'topMenu_' + section, 'style' : 'position: absolute; z-index: 77000; width: 390px;display: none; left: ' + (parseInt(a.positionedOffset().left)) + 'px;'});
            $(document.body).insert({top: el});
            size = $$('#footer_categ_' + section + ' A').length;
            if (! (size > 0)) return;
            i = 0;
            tmp = '<div class="droptitle">\
                <div class="droptitle-inside">\
                        <a href="' + a.href +'" title="' + els.get(section) +'">' + els.get(section) +'</a>\
                </div>\
        </div>\
        <div class="divider">\
                <div class="divider-inside"></div>\
        </div>\
        <div class="content">\
                <div class="content-inside">\
                        <div class="col-l">';
            $$('#footer_categ_' + section + ' A').each(function(a) {
                tmp += '<a href="' + a.href + '" title="' + a.innerHTML + '">' + a.innerHTML + '</a>';
                if (Math.ceil(size/2) == ++i) tmp +='</div><div class="col-r">';
            });
            tmp += '</div>\
                </div>\
                </div>\
                <div class="cbl"></div>\
                <div class="bb"></div>\
                <div class="cbr"></div>';
            el.update(tmp);
            Event.observe(a, 'mouseover', menuTopSections.show.bindAsEventListener(null, section));
            Event.observe(a, 'mouseout', menuTopSections.hide.bindAsEventListener(null, section));
            Event.observe('topMenu_' + section, 'mouseover', menuTopSections.show.bindAsEventListener(null, section));
            Event.observe('topMenu_' + section, 'mouseout', menuTopSections.hide.bindAsEventListener(null, section));
        });
    },
    show: function(e, section, from_timeout) {
        $('topMenu_' + section).setStyle({top: (parseInt(menuTopSections.firstTab.positionedOffset().top) + menuTopSections.firstTab.getHeight()-1) + 'px'});
        $('topMenu_' + section).show();
    },
    hide: function(e, section, from_timeout) {
        $('topMenu_' + section).hide();
    },
    firstTab: $$('#meniu A')[0]
}
//menuTopSections.init();

LoginPop = {
    message: '',
    tpl: '<div id="msg_login_box_pp">{MSG}</div><form id="frm_login" class="pop_login fl_left" onsubmit="LoginPop.login();return false;"><label>Utilizator:</label><input class="log_inp" type="text" maxlength="500" name="username"><label>Parola:</label><input class="log_inp" type="password" name="password"><div class="clearAll"></div><span id="pop_tine_minte"><label for="autologin">Tine-ma minte</label><input id="autologin" type="checkbox" value="" checked="checked" name="autologin"/></span><input type="hidden" value="usr_auth" name="f"><input type="submit" value="Login" id="pop_login"><div id="pop_optiuni_cont"><a title="Cont nou" href="'+ SITE_BASE +'inregistrare">cont nou</a><a title="Am uitat parola" href="' + SITE_BASE + 'recuperare-parola" style="border: none!important;">am uitat parola</a></div></form><div class="pop_login fl_right"><label>Autentificare prin Facebook</label><p>Acum te poti conecta la 220.ro si prin contul tau de Facebook! Fa click pe butonul de mai jos si introdu datele tale:</p><a href="javascript:void(0)" onclick="FbConnect.loginFB()" id="facebook">&nbsp;</a></div><div class="clearAll"></div>',
    show: function(message) {
        if (message == undefined) message = 'Autentificare';
        FbConnect.init()
        new MessageBox('dvLoginBox', '<span>Autentificare</span>', this.tpl.replace(/\{MSG\}/, message), {x: ['x', function(){}]});
        $('frm_login').username.focus();
    },
    login: function() {
        var f = $('frm_login');
        if (typeof window.sn_usrAuthHandler != 'function') {
            window.sn_usrAuthHandler = function(result, resultElementName, userData) {
                if (result.code == 0) {
                    window.location.href = window.location.href;
                } else {
                    $('msg_login_box_pp').update(result.text);
                }
            }
        }
        sn_getAjax('usr_auth', f.serialize(true), '');
        $('msg_login_box_pp').update('');
    }
}

function urlDecode(str){
    if (!str) return str;
    return unescape(str.replace(new RegExp('\\+','g'), ' '));
}

QLSearch = {
    search: function(query) {
        if (trim(query) == '' || query.substr(0, 4) == 'Ex: ') {
            new MessageBox('QLSearchB', 'Playlist audio', 'Nu ati introdus un termen de cautare');
            return;
        }
        var params = {query: query};
        sn_getAjax('ql_search_audio', params);
        if (typeof window.sn_qlSearchAudioHandler != 'function') {
            window.sn_qlSearchAudioHandler = function(result, resultElementName, userData) {
                if(result.code == 0) {
                    var resJS = result.text.evalJSON();
                    window.location.href = SITE_BASE + 'muzica-online/' + resJS.tk.substr(0, (resJS.tk.length - 32)) + '/';
                } else if(result.code == 1) {
                    new MessageBox('QLSearchB', 'Playlist audio', 'Ne pare rau, nu am gasit muzica conform termenilor introdusi');
                } else {
                    new MessageBox('QLSearchB', 'Playlist audio', 'A aparut o eroare la cautare');
                }
            }
        }
    },
    store: function(val) {
        Cookies.create('QLSearch', val);
    },
    del: function(id) {
        var ql = QLSearch.getData();
        var i = ql.ct.indexOf(id);
        if (i == -1) return false;
        delete ql.ct[i];
        ql.ct = ql.ct.without(null, undefined).compact();
        QLSearch.store(Object.toJSON(ql));
        return true;
    },
    getData: function() {
        var cook = Cookies.read('QLSearch');
        if (!cook) return {};
        return urlDecode(Cookies.read('QLSearch')).evalJSON();
    },
    shuffle: function() {
        var ql_tmp = QLSearch.getData().ct, sh_tmp = [];
        if (! ql_tmp) return;
        while (ql_tmp.length > 0) {
            i = Math.floor(Math.random() * 1000000) % ql_tmp.length;
            sh_tmp.push(ql_tmp[i]);
            ql_tmp.splice(i, 1);
        }
        QLSearch.storeItems(sh_tmp);
    },
    storeItems: function(ct) {
        var cook = QLSearch.getData();
        cook.ct = ct;
        QLSearch.store(Object.toJSON(cook));
    }
}

function clone_playlist(pid) {
    sn_getAjax('clone_playlist', {'pid': pid});
}

function sn_clonePlaylistHandler(result, resultElementName, userData) {
    new MessageBox('dv_clone_playlist', 'Salveaza playlist', result.text);
}

function delete_playlist(aid){
    sn_getAjax('delete_playlist', {'aid': aid});
}

function sn_deletePlaylistHandler(result, resultElementName, userData){
    if(result.code == 0)
    {
        document.location = SITE_BASE + "index.php?module=profile&action=playlists";
    }
}

function conf_delete_playlist(aid) {
    new MessageBox ('del_playlist', 'Stergere Playlist', 'Esti sigur ca vrei sa stergi acest Playlist?', {ok: ['Ok', function(){delete_playlist(aid)}], cancel: ['Cancel', function(){}]});
}

function setSelect(el, value) {
    if (typeof el == 'string') el = document.getElementById(el);
    if (!el || !el.type || el.type != 'select-one') return false;
    for (var i = 0; i < el.options.length; i++) {
        if (el.options[i].value == value) {
            el.options.selectedIndex = i;
            return true;
        }
    }
}

function setSelectSearchHead(){
    if (!$('searchBoxHead')) return;
    var section = document.location.href.replace(/^https?\:\/\/.*?\//, '/'), search_section;
    var prm = $.string(document.location.href).toQueryParams();
    if (typeof ctPlDet != 'undefined' && ctPlDet.ctype) {
        section = [null, 'video', 'audio', 'image', 'video'][ctPlDet.ctype];
    } else if (/\/cauta\//.test(section)) {
        search_section = /.*?\/(video|audio|image|playlist|user)(?:\/[0-9]+)?$/.exec(section)[1];
    } else if(/\/(muzica|dj)\//.test(section) || prm['module'] == 'quicklist') {
        search_section = 'audio';
    } else if(/\/user\//.test(section)) {
        search_section = 'user';
    }
    if (search_section) setSelect('searchBoxHead', search_section);
}
setSelectSearchHead();

(function(){
    if ($('input_cautare_top') && $('input_cautare_top').visible()) $('input_cautare_top').focus();
})();

HeadNotif = function(id, message, style) {
    this.id = id;
    if (Cookies.read('HeadNotif' + this.id)) return;
    this.message = message;
    var h = $$('div#header')[0];
    if (! h) return;
    h.insert({before: new Element('div', {'id': 'HeadNotif' + this.id, 'class': 'not_220_top', 'style': style}).update('<a class="not_220_inchide" href="javascript:void(0)" title="Inchide" onclick="HeadNotif' + this.id + '.close(); return false;"><img src="' + WEB_BASE + 'img/close_info.png" alt="Inchide" width="15" height="15"></a><center><p>' + this.message + '</p></center>')});
    this.close = function() {
        var el = $('HeadNotif' + this.id);
        if (! el) return;
        Effect.SlideUp(el, {duration: 0.3});
		Cookies.create('HeadNotif' + this.id, '1', 7);
		window['HeadNotif' + this.id] = null;
    }
    window['HeadNotif' + this.id] = this;
};

var player220Control = {
    getPlayer: function() {
	return $$('#player220' + ((Prototype.Browser.Gecko) ? ' OBJECT' : ''))[0];
    },
    aplay: 0,
    trackPrerollView: function(id) {
        if (typeof _gaq != 'undefined') _gaq.push(['_trackEvent', 'Internal prerolls', id]);
        sn_getAjax('track_preroll_view', {id: id});
    },
    nextLink: null,
    PlayNext: function() {
        this.finishedPlay = true;
        if (!this.aplay){
            var o =  player220Control.getPlayer();
            if (o && typeof o.toggleRelatedMovies == 'function') o.toggleRelatedMovies();
            return;
        }
        if (this.nextLink != null) document.location = this.nextLink;
        return;
    },
    finishedPlay: false,
    setTextAdProvider: function(type) {
	player220Control.getPlayer().setAdType(type); // tradeads | google
    },
    incrementSessCookie: function(name) {
        var count = Cookies.read(name);
        if (!count) {
            count = 0;
        }
        count++;
        Cookies.create(name, count, 0);
    },
    getCountSessCookie: function(name) {
        return Cookies.read(name);
    }
}
document.observe("dom:loaded", function() {
    var pl = player220Control.getPlayer();
    if (!window.contentId || !pl) return;
    if (window.userData && userData.adfree) return;

    if (typeof getTradeAdsParams == 'undefined' || getTradeAdsParams() == '') {
    	//pl.setAdType('google');
    } else {
    }
});
var smallNotif = function(message, ev, classes) {

    if (!ev) return false;
    if (ev.clientX) {
        var pos = {x: ev.clientX +  document.viewport.getScrollOffsets().left, y: ev.clientY + document.viewport.getScrollOffsets().top};
        try {Event.stop(ev)} catch(e){};
    } else if (ev.nodeType && ev.nodeType == 1) {
        var pos = {x: parseInt(ev.cumulativeOffset()[0] + ev.getWidth()/2), y: parseInt(ev.cumulativeOffset()[1] + ev.getHeight()/2)};
    } else if (ev.x && ev.y) {
        var pos = ev;
    } else {
        return false;
    }
    var id_not = 'smn_' + Math.floor(Math.random() * 10000000000);

    var propr = {id: id_not, className: classes ? classes : 'msg_box', style: 'position: absolute; z-index: 1002; top:' + pos.y + 'px; left:' + pos.x + 'px;'};
    if (classes === undefined) {
        propr.style = propr.style + 'border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius:5px; box-shadow: 1px 1px 2px #666666, 0 0 5px #000000 inset; -webkit-box-shadow: 1px 1px 2px #666666, 0 0 5px #000000 inset; -moz-box-shadow: 1px 1px 2px #666666, 0 0 5px #000000 inset; background:#333; border:2px solid #fff; color:#fff; display:block; font-size:11px; filter:alpha(opacity=70); -moz-opacity:0.7; -webkit-opacity: 0.7; opacity: 0.7; padding:3px 7px 3px 7px; text-align:center; max-width:200px;';
    }
    var dv = new Element('div', propr);
    message = '<a style="close_smn" style="color: #fff; font-weight: bold;" onclick="$(\'' + id_not +  '\').remove()" href="javascript:void(0)"></a><span>' + message + '</span>';
    dv.innerHTML = message;
    document.body.appendChild(dv);
    setTimeout(function() {if ($(id_not)) $(id_not).remove()}, 2000);
};

var sn_getPlaylistContentHandler = function(result, resultElementName, userData) {
    if(result.code == 0) {
        var cont =  result.text.evalJSON();
        if (userData.PlayIt) {
            window.location.href = cont.link + '?play_from=playlist&playlist_id=' + userData.id;
        }
    } else {
        new MessageBox(result.text);
    }
}

var play_playlist = function(id) {sn_getAjax('get_playlist_content', {id: id, position: 1}, null, {PlayIt: true, id: id})};

function contest_vote(content, contest, votePlace, ev) {
    sn_getAjax('contest_vote', {content: content, contest: contest}, null, {ev: {clientX: ev.clientX, clientY: ev.clientY}, votePlace: votePlace});
    try{Event.stop(ev)} catch(e) {};
}

function sn_contestVoteHandler(result, resultElementName, userData) {
    if (result.code == 0) {
        new smallNotif('Vot inregistrat!', userData.ev);
        userData.votePlace.update(parseInt(userData.votePlace.innerHTML) + 1);
    } else {
        new smallNotif(result.text, userData.ev);
    }
}

function soft_delete_comment(id, status, ev) {
    sn_getAjax('soft_delete_comment', {id: id, status: status}, null, {id: id, ev: ev});
}
function sn_softDeleteCommentHandler(result, resultElementName, userData) {
    if (result.code == 0) {
        $$('.contentBody#ccomm_' + userData.id)[0].remove();
    }
    new smallNotif(result.text, userData.ev);
}

function prop_delete_user(u, ev) {
    sn_getAjax('prop_delete_user', {u: u}, null, {ev: ev});
}
function sn_propDeleteUserHandler(result, resultElementName, userData) {
    new smallNotif(result.text, userData.ev);
}
var NQL = {
    enabled: false,
    type: null,
    status: null,
    min: null,
    aplay: null,
    playingItem: null,
    listFetched: false,
    items: [],
    customData: {},
    getIdFromLink: function(lnk) {
        return /.*\/([0-9a-zA-Z]){10,10}\/[^\/]*/.exec(lnk)[1];
    },
    getCookieSettings: function() {
        var cookie_settings = urlDecode(Cookies.read('NQL'));
        cookie_settings = cookie_settings ? cookie_settings.evalJSON() : {};
        return cookie_settings;
    },
    setCookieSettings: function(name, value) {
        var cookie_settings = NQL.getCookieSettings();
        cookie_settings[name] = value;
        Cookies.create('NQL', Object.toJSON(cookie_settings));
    },
    getCurPlayIndex: function() {
        if(NQL.items.length < 1) return false;
        var cur_id = NQL.getCurrPlayItem();
        for (var i = NQL.items.length - 1; i >= 0; i--) {
            if (NQL.items[i].id == cur_id) return i;
        }
        return false;
    },
    play: function(i) {
        NQL.disablePopulate = true;
        if(NQL.items[i]) {
            document.location = NQL.prepareLink(NQL.items[i].link);
        } else if (! NQL.listFetched) {
            NQL.fetchList({callbackFn: function() {NQL.play(i)}});
        }
    },
    playPrev: function() {
        var  cur_idx = NQL.getCurPlayIndex();
        if (cur_idx == 0) return false;
        NQL.play(cur_idx - 1);
    },
    playNext: function() {
        var  cur_idx = NQL.getCurPlayIndex();
        if (cur_idx == (NQL.items.length - 1)) return false;
        NQL.play(cur_idx + 1);
    },
    typeMap: {'fz' : 'Filmele zilei', 'ql': 'Quicklist', 'playlist': 'Playlist', 'uhist': 'Istoric'},
    init: function() {
        var q_param = document.location.href.toQueryParams();
        var type = q_param.play_from || 'fz';
        var cookie_settings = NQL.getCookieSettings();
        //if (!NQL.typeMap[type]) return;
        if (! $('newQL')) return;
        this.enabled = true;
        this.type = type;
        if (cookie_settings.type != NQL.type) {
            NQL.setCookieSettings('type', NQL.type);
        }

        if (NQL.type == 'playlist') {
            NQL.customData.playlist_id = document.location.href.toQueryParams()['playlist_id'];
        }

        try {
            var cur_index = NQL.getCurPlayIndex();
        } catch (e) {};

        if (cookie_settings.aplay || (cur_index == 0 && (type == 'ql' || type == 'playlist'))) {
            if (document.location.href.toQueryParams()['play_from'] == NQL.type) NQL.toggleAplay(null, true);
        }
        $('nql_lista_optiune').update(NQL.typeMap[type]);

        if (NQL.type == 'ql'){
            $('nql_shuffle').show();
        }
        if (NQL.type != 'playlist'){
            $$('#nql_submeniu button')[2].hide();
        }
        NQL.bindButtonsActions();
        if (!NQL.listFetched) NQL.fetchList();
        NQL.bindInfoTools();
        //if (true || NQL.getCookieSettings().min) {
        //    setTimeout(function() {NQL.toggleBox(undefined, true)}, 1500);
        //}
    },
    bindButtonsActions: function() {
        $('nql_prev').onmouseover = function(){$('nql_i_prev').show()};
        $('nql_prev').onmouseout = function(){$('nql_i_prev').hide()};
        $('nql_next').onmouseover = function(){$('nql_i_next').show()};
        $('nql_next').onmouseout = function(){$('nql_i_next').hide()};
        Event.observe($('nql_min'), 'mouseover', function(){$('nql_i_toggle').show()});
        Event.observe($('nql_min'), 'mouseout', function(){$('nql_i_toggle').hide()});

        Event.observe($('nql_min'), 'click', this.toggleBox.bindAsEventListener());
        Event.observe($('nql_shuffle'), 'click', this.toggleShuffle.bindAsEventListener());
        Event.observe($('nql_autoplay'), 'click', this.toggleAplay.bindAsEventListener());
        Event.observe($('nql_prev'), 'click', this.playPrev.bindAsEventListener());
        Event.observe($('nql_next'), 'click', this.playNext.bindAsEventListener());
        Event.observe($('nql_lista'), 'click', this.togglePlTypeMenu.bindAsEventListener());
        Event.observe($$('#nql_submeniu button')[0], 'click', this.changeType.bindAsEventListener(null, 'fz'));
        Event.observe($$('#nql_submeniu button')[1], 'click', this.changeType.bindAsEventListener(null, 'ql'));
        Event.observe($$('#nql_submeniu button')[2], 'click', this.changeType.bindAsEventListener(null, 'playlist'));
    },
    bindInfoTools: function() {
        var cur_index = NQL.getCurPlayIndex();
        if (!cur_index) {
            $('nql_prev').onmouseover = $('nql_prev').onmouseout = function() {};
        } else {
            $$('#nql_i_prev .nql_text')[0].update('Anterior: ' + NQL.items[cur_index - 1].title);
        }
        if (NQL.items.length == 0 || cur_index == (NQL.items.length - 1)) {
            $('nql_next').onmouseover = $('nql_next').onmouseout = function() {};
        } else {
            $$('#nql_i_next .nql_text')[0].update('Urmeaza: ' + NQL.items[cur_index + 1].title);
        }
    },
    getCurrPlayItem: function() {
        return window.contentId;
    },
    isExpanded: function() {
        return $('NQLmain').hasClassName('nql_minimize') == false;
    },
    getItemsIds: function() {
        var ids = [];
        NQL.items.each(function(itm) {ids.push(itm.id);});
        return ids;
    },
    addOneItem: function(id) {
        if (NQL.listFetched) {
            NQL.fetchOneItem(id);
            return;
        } else {
            var itm = NQL.getCookieSettings()['items'];
            if (itm == undefined) {
                itm = id;
            } else {
                itm.push(id);
            }
        }
    },
    deleteOneItem: function(id) {
        var idx = NQL.getItemsIds().indexOf(id);
        if (idx === -1) return;
        NQL.items.splice(idx, 1);
        $$('#nql_lista_filme ul')[idx].remove();
    },
    fetchOneItem: function(id) {
        if (NQL.getItemsIds().indexOf(id) != -1) return;

        sn_getAjax('get_item_4mix', {c: id});
        if (window.sn_getItem4mixHandler === undefined) {
            window.sn_getItem4mixHandler = function(result, resultElementName, userData) {
                var els, items;
                if (result.code != 0) return;
                el = result.text.evalJSON();
                items = NQL.items;
                items.push(el);
                NQL.populateList(items);
            }
        }
    },
    fetchList: function(prm) {
        var params = {type: NQL.type, c: NQL.getCurrPlayItem()};
        if (NQL.type == 'playlist') {
            params['playlist'] = NQL.customData.playlist_id;
        }
        if (NQL.type == 'fz' && document.location.href.toQueryParams()['play_from'] == null) {
            params['force_new'] = 1;
        }
        sn_getAjax('get_mixlist', params, null, prm);

        if (window.sn_getMixlistHandler === undefined) {
            window.sn_getMixlistHandler = function(result, resultElementName, userData) {
                var els, index, ids = [];
                if(result.code == 0) {
                    NQL.populateList(result.text.evalJSON());
                    if (typeof userData.callbackFn == 'function') userData.callbackFn.call(null);
                    NQL.setCookieSettings('type', NQL.type);
                    NQL.positionPlayingItem();
                } else {
                    //new MessageBox(result.text);
                }
            }
        }
    },
    populateList: function(els) {
        NQL.listFetched = true;
        NQL.items = [];
        var index = 0, items = [], ids = [], cont = $$('#nql_lista_filme ul')[0];
        if (! NQL.disablePopulate) cont.update('');
        els.each(function(el) {
            index++;
            if (!NQL.disablePopulate) cont.insert({bottom: new Element('li').update(
            '<a title="' + el.title + '" class="nql_film' + (el.id == NQL.getCurrPlayItem() ? ' nql_activ' : '') + '" href="' + NQL.prepareLink(el.link) + '"><img src="' + el.tb100 + '">' +
			'<span class="nql_durata">' + (el.duration ? el.duration : '') + '</span><button class="nql_play">&nbsp;</button>' +
			'<span class="nql_titlu">' + el.title + '</span>' +
			(NQL.type == 'ql' ? '<button class="nql_inchide" onclick="quicklist.del(\'' + el.id + '\');return false">&nbsp;</button>' : '') + '</a>'
            )});

            items.push(el);
            ids.push(el.id);
        });
        NQL.items = items;
        NQL.positionPlayingItem();
    },
    setPopulateListOnToggle: function(els) {
        if (!(els.length > 0)) return false;
        NQL.listFetched = true;
        NQL.items = els;
        NQL.populateOnToggle = true;
    },
    setPlayNext: function(set) {
        var prev = false;
        if (set) {
            NQL.playNextLink = set;
            if (NQL.aplay) {
                player220Control.nextLink = NQL.playNextLink;
            }
            return;
        }

        if (NQL.items.length > 0) {
            for (var i = 0; i < NQL.items.length; i++) {
                if (prev.id == NQL.getCurrPlayItem()) {
                    NQL.playNextLink = NQL.prepareLink(NQL.items[i].link);
                    break;
                }
                prev = NQL.items[i];
            }
        } else {
            $$('#nql_lista_filme a.nql_film').each(function(a) {
                if (prev && prev.id === NQL.getCurrPlayItem()) {
                    NQL.playNextLink = NQL.prepareLink(prev.link);
                    return;
                }
                prev = {id: NQL.getIdFromLink(a.href), link: a.href};
            });
            if (! NQL.playNextLink && prev.link) NQL.playNextLink = NQL.prepareLink(prev.link);
        }
        if (NQL.aplay) {
            player220Control.nextLink = NQL.playNextLink;
        }
    },
    toggleBox: function(e, hide) {
        if (!NQL.enabled) return;
        try {Event.stop(e)} catch(e) {}

        if(! NQL.listFetched) {
            NQL.fetchList();
        }
        var next_state = $('nql_lista_filme').visible();
        if (hide == undefined) {
            hide = next_state;
        }
        if (hide) {
            Effect.SlideUp('nql_lista_filme', {duration: 0.1});
            $('nql_min').addClassName('nql_minimize');
            $$('#nql_i_toggle .nql_text')[0].update('Afiseaza lista filme');
        } else {
            if (NQL.populateOnToggle) {
                NQL.populateOnToggle = false;
                NQL.populateList(NQL.items);
            }
            Effect.SlideDown('nql_lista_filme', {duration: 0.1});
            $('nql_min').removeClassName('nql_minimize');
            $$('#nql_i_toggle .nql_text')[0].update('Ascunde lista filme');
        }
        NQL.min = hide ? 1 : 0;
        if (NQL.getCookieSettings().min != NQL.min) {
            NQL.setCookieSettings('min', NQL.min ? 1 : 0);
        }
        NQL.positionPlayingItem();
        //$('newQL').toggleClassName('nql_minimize');
    },
    togglePlTypeMenu: function(e, hide) {
        try {Event.stop(e)} catch(e) {}
        if (!NQL.enabled) return;
        if (hide === undefined) {
            hide = $('nql_submeniu').hasClassName('nql_submeniu');
        }
        if (hide) {
            $('nql_submeniu').removeClassName('nql_submeniu');
        } else {
            $('nql_submeniu').addClassName('nql_submeniu');
            setTimeout(function() {NQL.togglePlTypeMenu(undefined, true);}, 2000)
        }
    },
    toggleAplay: function(e, set) {
        try {Event.stop(e);} catch(e){};
        if (!NQL.enabled) return;
        if (set === undefined) {
            set = !NQL.aplay;
        } else {
            set = (set == true);
        }
        player220Control.aplay = NQL.aplay = set;
        if (NQL.aplay) {
            $('nql_autoplay').update('Autoplay (on)').addClassName('on');
            if (NQL.items == undefined || NQL.items.length == 0){
                //if ($('nql_lista_filme').hasClassName('minified')) NQL.disablePopulate = true;
                NQL.fetchList({callbackFn: function() {NQL.setPlayNext();NQL.disablePopulate = false;}});
                return;
                //NQL.fetchList();
            }
            NQL.setPlayNext();
            if (player220Control.finishedPlay) player220Control.PlayNext();
        } else {
            $('nql_autoplay').update('Autoplay (off)').removeClassName('on');
        }
        //if (e && e.button !== undefined) NQL.setCookieSettings('aplay', NQL.aplay ? 1 : 0);
        if (NQL.getCookieSettings().aplay != NQL.aplay) {
            NQL.setCookieSettings('aplay', NQL.aplay ? 1 : 0);
        }
    },
    toggleShuffle: function(e) {
        try {Event.stop(e)} catch(e) {};
        if (!NQL.enabled) return;
        if (NQL.type != 'ql') return;
        if (!NQL.listFetched) {
            NQL.fetchList({callbackFn: function() {NQL.toggleShuffle()}});
            return;
        }
        if(arguments[1] === undefined) {
            if (NQL.shuffleing == 1) return;
            NQL.shuffleing = 1;
            $('nql_shuffle').addClassName('on');
            setTimeout(function() {NQL.toggleShuffle(null, 1)}, 300);
            return;
        }
        var l = NQL.items.length, items = NQL.items, i, sh_items = [],  ids = [];
        if (!(l > 0)) return;
        if (['ql'].indexOf(NQL.type) === -1) return;

        if (NQL.type == 'ql') {
            quicklist.shuffle();
            var ql_tmp = getQLItems().keys();
            var map_ids = {};
            items.each(function(v, i) {map_ids[v.id] = i});
            ql_tmp.each(function(id) {
                sh_items.push(items[map_ids[id]]);
            });
        }
        NQL.populateList(sh_items);
        $('nql_shuffle').removeClassName('on');
        NQL.shuffleing = false;
        //NQL.setCookieSettings('items', ids);
        NQL.positionPlayingItem();
        NQL.setPlayNext();
    },
    changeType: function(e, type) {
        try {Event.stop(e)} catch(e) {}
        NQL.togglePlTypeMenu();
        if (type == NQL.type) return;

        if (type == 'ql' && !(getQLItems().keys().length > 0)
        ) {
            new MessageBox('Nu exista iteme in aceasta lista!!');
            return;
        }

        NQL.type = type;
        NQL.listFetched = false;
        NQL.items = [];
        NQL.play(0);
    },
    prepareLink: function(link) {
        //if (!link) return '';
        if (/[\W]play_from\=/.test(link)) return link;
        link = link + (link.indexOf('?') == -1 ? '?' : '&') + 'play_from=' + NQL.type;
        if (NQL.type == 'playlist') {
            link = link + '&playlist_id=' + NQL.customData.playlist_id;
        }
        return link;
    },
    positionPlayingItem: function() {
        var h = 0, finished = false, delta = 0;
        $$('#nql_lista_filme UL A').each(function(el) {
            if (finished || el.hasClassName('nql_activ')) {
                finished = true;
                return;
            }
            h += 120;
            //h += el.getWidth();
        });
        if (finished) $('nql_lista_filme').scrollLeft = h + 0;
    }
};
//document.observe('dom:loaded', function() {NQL.init();});

(function(){
    return;
    if (!Prototype.Browser.IE) return;
    //if (Cookies.read('HeadNotifie6alert') == '1') return;
    var mVer = /.*MSIE ([0-9]{1,}[\.0-9]{0,}).*/.exec(navigator.userAgent)[1];
    mVer = parseFloat(mVer);
    if (mVer >= 7) return;
    new HeadNotif('ie6alert', 'Browserul tau e preistoric, navigheaza cu unul mai acatarii: <a href="http://www.opera.com/browser/" target="_blank">Opera</a>, <a href="http://www.google.com/chrome/" target="_blank">Google Chrome</a>, <a href="http://www.mozilla.com/" target="_blank">Firefox</a>, <a href="http://www.apple.com/safari/" target="_blank">Safari</a> ... ori fa-ti upgrade: <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx" target="_blank">Internet Explorer</a>!');
})();

var FbConnect = {
    init: function(callback) {
        if (FbConnect.inited) return false;
        if (!window.FACEBOOK_APPID) return false;
        if (window.FB && window.FB.init) {
            clearInterval(FbConnect.intLoad);
            FB.init({appId: window.FACEBOOK_APPID, status: true, cookie: true, xfbml: false});
            FbConnect.inited = true;
            if (typeof callback == 'function') {
                callback.call();
            }
        } else if(!$('fb-root')) {
            var newEl = new Element('script', {'src': 'http://connect.facebook.net/en_US/all.js', type: 'text/javascript', async: 'async'});
            document.getElementsByTagName('head')[0].appendChild(newEl);
            newEl = new Element('div', {'id': 'fb-root'});
            document.body.appendChild(newEl);
            if (!FbConnect.intLoad) FbConnect.intLoad = setInterval(function(){FbConnect.init(callback);}, 100);
        }
    },
    loginFB: function() {
        if (!FbConnect.inited) {
            FbConnect.init(FbConnect.loginFB);
            return;
        }
        FB.login(function(response) {
            if (response.session) {
                if (response.perms) {
                    FbConnect.login();
                } else {
                    new MessageBox('err_notif', 'Conectare esuata prin Facebook', 'Pentru a va loga este necesar sa dati drepturi de acces pe facebook pentru site-ul 220.ro');
                    // user is logged in, but did not grant any permissions
                }
            } else {
                //new MessageBox('err_notif', 'Conectare prin Facebook', 'Nu te-ai logat');
                //user is not logged in
            }
        }, {perms: 'user_about_me,user_birthday,email'}
        );
    },
    login: function() {
        if (!FbConnect.inited) {
            FbConnect.init(FbConnect.login);
            return;
        }
        sn_getAjax('login_facebook', {});
        if (window.sn_loginFacebookHandler == undefined) {
            window.sn_loginFacebookHandler = function(result, resultElementName, userData) {
                if (result.code == 7) {
                    FbConnect.registerBox();
                } else if (result.code == 0) {
                    window.location.href = SITE_BASE;
                } else {
                    new MessageBox(result.text);
                }
            }
        }
    },
    register: function() {
        if (!FbConnect.inited) {
            FbConnect.init(FbConnect.register);
            return;
        }
        var box_err = $$('#fb_registebox .facebook_error')[0];
        if (!$('frm_fb_register')) return false;
        if (!$('fb_register_terms').checked) {
            box_err.update('Trebuie sa fii de acord cu termenii si conditiile pentru a putea continua').show();
            return false;
        }
        box_err.hide();

        params = $('frm_fb_register').serialize(true);

        sn_getAjax('register_facebook', params);

        if (window.sn_registerFacebookHandler == undefined) {
            window.sn_registerFacebookHandler = function(result, resultElementName, userData) {
                if(result.code == 0) {
                    window.location.href = SITE_BASE;
                } else {
                    box_err.update(result.text).show();
                }
            }
        }
    },
    registerBox: function() {
        if (!FbConnect.inited) {
            FbConnect.init(FbConnect.registerBox);
            return;
        }
        var tpl = '<form id="frm_fb_register"><br>' +
        '<div class="check_div"><input type="checkbox" class="check_btnx" id="fb_register_nl" name="newsletter" value="1" checked="checked"/><label for="fb_register_nl">Dresc sa ma abonez la newsletter zilnic</label></div>' +
        '<div class="check_div"><input type="checkbox" class="check_btnx" id="fb_register_terms" name="terms" value="1" checked="checked"/><label for="fb_register_terms">Am citit si sunt de acord cu </label><a class="facebook" href="' + SITE_BASE + 'index.php?module=rules" target="_blank" title="termenii si conditiile 220.ro">termenii si conditiile</a></div>' +
        '<p class="facebook_error" style="display: none"></p>' +
        '</form>';
        new MessageBox('fb_registebox', 'Te-ai autentificat folosind Facebook', tpl, {ok: {0: 'Inregistrare', 1: FbConnect.register, dontClose: 1}, cancel: ['Cancel', function(){}]});
    }
};
//FbConnect.init();
if($('quicklogin_fb')) $('quicklogin_fb').onmouseover = FbConnect.init;

// colorpicker2
var CPicker2 = {
    reg: [],
    init: function(callback) {
        if (CPicker2.inited) return false;
        if (window.Control && Control.ColorPicker) {
            clearInterval(CPicker2.intLoad);
            CPicker2.inited = true;
            if (typeof callback == 'function') {
                callback.call();
            }
        } else if(!window.Control || !Control.ColorPicker) {
            var css = ['css/colorPicker.css'];
            var jss = ['js/yahoo.color.js', 'js/colorPicker.js'];
            var x, hd = document.getElementsByTagName('head')[0];
            $A(css).each(function(i) {
                x = document.createElement('link');
                x.rel = 'stylesheet';
                x.type = 'text/css';
                x.href = WEB_BASE + i;
                hd.appendChild(x);
            });
            $A(jss).each(function(i) {
                x = document.createElement('script');
                x.src = WEB_BASE + i;
                hd.appendChild(x);
            });
            if (!CPicker2.intLoad) CPicker2.intLoad = setInterval(function(){CPicker2.init(callback);}, 100);
        }
    },
    instance: function(id, options) {
        if (!CPicker2.inited) {
            CPicker2.init(function() {CPicker2.instance(id, options);});
            return;
        }
        if (this.reg[id]) {
            return this.reg[id];
        }
        options = options || {};
        options.IMAGE_BASE = WEB_BASE + 'img/colorpicker2/';
        new Control.ColorPicker(id, options);
        return this.reg[id] = Control.colorPickers[Control.colorPickers.length - 1];
    }
}

var toggle_get_embed = function(open) {

    if (!window.elementCache.exists('get_embed_maker')) {
        sn_updateByAjax('get_embed_maker', {}, 'video_options_container', {
            onComplete: function(t) {
                window.elementCache.save('get_embed_maker', $('video_options_container'));
                window.elementCache.addPostSaveDeploy(function() {CPicker2.instance('emb_picker').close()});
                toggle_get_embed(true);
            }
        });
        return;
    } else if (!$('embed_opt') && window.elementCache.exists('get_embed_maker')) {
        window.elementCache.deploy('get_embed_maker', $('video_options_container'));
        CPicker2.instance('emb_picker').open();
        return;
    }
    CPicker2.inited || CPicker2.init(function() {
        CPicker2.instance('emb_picker',
        {
            getPopUpPosition: function() {
                var p = $('embed_opt').positionedOffset();
                return [p[0] + 10, p[1] + 220];
            },
            onUpdate: function(v) {
                EmbedCode.set('color', v);
            }
        }).open();
    });
    if (open || !$('embed_opt').visible()) {
        $('embed_opt').show();
        !CPicker2.inited || CPicker2.instance('emb_picker').open();
        EmbedCode.make();
    } else {
        $('embed_opt').hide();
        CPicker2.instance('emb_picker').close();
    }
};

EmbedCode = {
    opt: {width: '450'},
    asp_ratio:  3/4,
    bar:  28,
    setWidth: function(width, v) {

        this.opt.width = width;
        if  (!(width >= 300 && width <= 450)) {
            this.opt.width = 450;
            v = 'mare';
        }
        if (window.content.ctype != 2) {
            this.opt.height =  Math.round((this.opt.width * this.asp_ratio) + this.bar);
        } else {
            this.opt.height = 106;
        }
        if (v) {
            $('embed_opt').custom_width.value = this.opt.width;
            $('embed_opt').custom_height.value = this.opt.height;
        }
        $A(['mic', 'mediu', 'mare', 'custom']).each(function(d) {
            $('dim_' + d).removeClassName('activ');
        });
        $('dim_' + v).addClassName('activ');
        this.make();
    },
    set: function(option, v) {
        this.opt[option] = v;
        if (option == 'color' && $('masca_player')) $('masca_player').setStyle({'backgroundColor' : '#' + v});
        this.make();
    },
    make: function(e) {
        var c = window.content;
        //sizes = [[], [320,240], [450,370], [250,130]];
        //sizes = [450, 400, 300];

        var aplay = this.opt.aplay ? '&aplay=true'  : '';
        var color_player = this.opt.color ? '&rgb=' + this.opt.color : '';
        var from = (window.lUser) ? '&from=' + lUser.nameb64 : '';

        if (c.ctype != 2) {
            this.opt.height =  Math.round((this.opt.width * this.asp_ratio) + this.bar);
        } else {
            this.opt.height = 106;
        }

        sz = [this.opt.width, this.opt.height];

        s = '<embed width="' + sz[0] + '" height="' + sz[1] + '" src="' + SITE_BASE + 'emb/' + c.id + color_player + aplay + from + '" ';
        s += 'allowfullscreen="true" allowscriptaccess="always" ';
        s += 'type="application/x-shockwave-flash" ';
        s += '></embed><br><small>Vezi mai multe din <a href="' + c.category + '" target="_blank">' + c.category + '</a> pe <a href="http://www.220.ro" target="_blank">220.ro</a></small>';
        script = '<script type="text/javascript" src="' + SITE_BASE + 'embjs?id=' +  c.id + '&width=' + sz[0] + '&height=' + sz[1] + color_player + aplay + from + '"></script>' +
        '<noscript>Vezi <a href="' +  c.link + '" target="_blank">' + c.title + '</a> pe <a href="http://www.220.ro" target="_blank">220.ro</a></noscript>';
        $('embed_opt').player_embed.value = s;
        $('embed_opt').player_embed2.value = script;
        return true;
    }
}

var gUtilities = {
    isValidUrl: function(url) {
        return /\/(https?\:\/\/)?(www\.)?google\.[^\/]{2,6}(\/.*)/.test(url);
    },
    getSearchTerm: function(url) {
        if (!url) return '';
        if (!this.isValidUrl(url)) return '';
        return /.+[\?&]q\=([^&]{1,}).*/.exec(url)[1] || '';
    }
}

var roDateUtils = {
    months: ['Ianuarie', 'Februarie', 'Martie', 'Aprilie', 'Mai', 'Iunie', 'Iulie', 'August', 'Septembrie', 'Octombrie', 'Noiembrie', 'Decembrie'],
    weekDays: ['Luni', 'Marti', 'Miercuri', 'Joi', 'Vineri', 'Sambata', 'Duminica']
};

(function(){
    /*
    if (isLogged && !Cookies.read('HeadNotifupdPData')) {
        new HeadNotif('updPData', '<a href="javascript:void(0)" onclick="onDemandJsLoader(\'' + WEB_BASE + 'js/rare_r' + JS_SERIAL + '.js\', function() {addUpdateUserDataBox()})">Actualizeaza-ti datele personale si ai sansa sa castigi saptamal un cadou surpiza oferit de BitDefender!</a>');
    } else
    */
    if ((Math.random() * 1000) > 500) {
	//new HeadNotif('votca_camp', '<a href="http://www.220.ro/concursuri/vreau-o-tara-ca-afara/"><img src="http://static.220.ro/_templates/_default/img/notificari/votca_header.png"></a', 'background-color: #000!important;padding: 0');
    } else {
	//new HeadNotif('farsa_vacan', '<a href="http://www.220.ro/concursuri/farsa-pentru-vacanta/"><img src="http://static.220.ro/_templates/_default/img/notificari/farsa_header.jpg"></a', 'background-color: #1b3c5e!important;padding: 0');
    }
})();

document.observe("dom:loaded", function() {
    if (window.isLogged) return false;
    var func_login = function() {if (this.href) this.href = 'javascript:void(0)'; LoginPop.show()};
    if (window.contentId) {//content detail
        toggleStar =
        $('optiune_3').onclick =
        $('optiune_4').onclick =
        $('optiune_5').onclick =
        $('optiune_6').onclick =
        $$('#starsLog a')[0].onclick =
        $('add_comment_f_content_tarea_main').onclick =
        $('posteaza_comentariu').onfocus =
        $('posteaza_comentariu').onclick =
        $$('#is_not_subscribed a')[0].onclick =
        $$('#is_friend a')[0].onclick =
        $$('a[title="Trimite mesaj"]')[0].onclick =
        func_login;
    } else if (window.userId) {//user detail
        $$('a.replay').each(function(i) {i.onclick = func_login;});
        $$('.user_det_menu a')[0].onclick =
        $$('.user_det_menu a')[1].onclick =
        $$('.user_det_menu a')[2].onclick =
        $$('.user_det_menu a')[3].onclick =
        $$('.user_det_menu a')[4].onclick =
        $$('.user_det_menu a')[5].onclick =
        $$('#poz_7 a.replay')[0].onclick =
        $('add_comment_f_content_tarea').onclick =
        func_login;
    }
});

(function(){
    if (true || Cookies.read('qlUseNot')) return;
    var str = '<div class="ql_tt_wrapper">' +
    '<span class="ql_tt_img">&nbsp;</span><span class="ql_tt_continut">' +
    '<span class="ql_tt_titlu">Bifezi si te uiti mai tarziu!</span>' +
    'Ai vazut un filmulet interesant si nu ai timp sa te uiti la el? Quicklist-ul nostru te ajuta sa pui deoparte ce vrei si sa vezi oricand vrei tu.' +
    '<a href="javascript:void(0)" onclick="$(\'ql_tt_video\').toggle()" title="Vezi demonstratia" class="ql_tt_link" id="ql_tt_functionare">vezi cum functioneaza</a>' +
    '</span>' +
    '<div class="clearAll"></div>' +
    '<span id="ql_tt_video" style="display:none">' +
    '<embed width="300" height="253" src="http://www.220.ro/emb/flccAi4vVp&aplay=true" allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash"></embed>' +
    '</span></div>' +
    '<div class="ql_tt_bottom">&nbsp;</div>';
    $('lgnql').insert({after: new Element('div', {id: 'ql_tooltip_box', 'class': 'ql_tooltip_box'}).update(str)});
    var a = new Element('a', {id: 'ql_tt_inchide','class':'ql_tt_inchide', 'href':'javascript:void(0)', 'title':'Inchide'}).update('&nbsp;');
    a.onclick = function() {Cookies.create('qlUseNot', 1, 7); $('ql_tooltip_box').remove(); $('ql_tt_inchide').remove();};
    $('ql_tooltip_box').insert({before: a});
})();

onDemandJsLoader = function(url, cback) {
    var idName = 'dl_' + url.replace(/[^A-Za-z0-9_\:\.\-]/g, '');
    if (document.getElementById(idName)) {
        if (cback) cback.call();
        return;
    }
    var nE = document.createElement('script');
    nE.src = url;
    nE.id = idName;
    nE.type = 'text/javascript';
    nE.async = 'async';
    nE.defer = 'defer';
    if (cback != undefined) {
        if (Prototype.Browser.IE) {
            nE.onreadystatechange = function() {
                if (!cback) return;
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    cback.call();
                    cback = undefined;
                }
            }
        } else {
            nE.onload = cback;
        }
    }
    document.getElementsByTagName('head')[0].appendChild(nE);
}

if (Cookies.read('addUpdateUserData')) {
    //onDemandJsLoader(WEB_BASE + 'js/rare_r' + JS_SERIAL + '.js', function() {addUpdateUserDataBox()});
};

var Content = {
    addV: function(id) {
    }
}

function popBuyAdPlaceBursa(link) {
    if(!$('buyAdspace')) document.body.appendChild(new Element('div', {id: 'buyAdspace'}));
    onDemandJsLoader('http://leads.bursadereclama.ro/Scripts/LeadCollector.js', function(){
	_gaq.push(['_trackEvent', 'buyAdspace', link]);
	return LeadCollector('buyAdspace', link);
    });
    return false;
}

var strReplacer = {
    init: function(){
        var r = '<a href="http://www.220.ro/fara-publicitate/" title="Te-ai saturat de reclama? Nu mai carcoti, fa ceva!" class="no_ads">tpl</a>';
        this.list = {'reclame': r, 'reclamele': r, 'reclama': r, 'publicitate': r, 'publicitatea': r};
        for (var i in this.list) {
            this.ptr = (i.replace(/([\W])/g, "\\$1")) + "|" + this.ptr;
            this.listPrep[i.replace(/<|>|&/g, function($m) {return strReplacer.sChars[$m]}).toUpperCase()] = this.list[i].replace(/tpl/g, i);
        }
        this.ptr = this.ptr.substr(0, this.ptr.length-1);
        this.ptr = this.ptr.replace(/<|>|&/g, function($m) {return strReplacer.sChars[$m]});
    },
    ptr: '',
    sChars: {"<":"&LT;", ">":"&GT;", "&": "&AMP;"},
    list: null,
    listPrep: {},
    replace: function(selector) {
        var re = new RegExp (this.ptr, "gmi");
        $$(selector).each(function(i) {
            var text = i.innerHTML;
            text = (' ' + text + ' ').replace(re, function ($m) {return strReplacer.listPrep[$m.toUpperCase()]});
            i.update(text.substr(1, text.length - 2));
        });
    }
};

strReplacer.init();
strReplacer.replace('#comments .emoticable');

var topMenu = {
	init: function(){
		$$('#meniu>li').each(function(li){
//		    var menu = $(li).findChildElements('div');
//		    console.log(menu);
		    //$(menu).show();
//			if(menu.length){
//			    Event.observe(menu, 'mouseenter', function(){
//			        console.log('enter');
////			        $(menu).addClassName('activ');
//			    });
//			    Event.observe(menu, 'mouseleave', function(){
//    			    console.log('leave');
////			        $(menu).removeClassName('activ');
//			    });
//			}
		});
	}
};

topMenu.init();

$$('.refresh').each(function(r){
    Event.observe(r, 'click', function(e) {
        setTimeout('location.reload(true);', 2000);
//        console.log(e);
    });
});
var HTML_SWITCHER = {
    replace: function() {
        if (typeof HTMLSW == 'undefined' || !HTMLSW.length) return;
        for (var i = 0, l = HTMLSW.length; i < l; i++ ) {
            var e = HTMLSW[i];
            var o = document.getElementById('hsworig_' + e), h = document.getElementById('hswhold_' + e);
            //o.parentNode.replaceChild(h, o); h.style.display = 'block';
            //o.parentNode.insertBefore(h, o);
            o.innerHTML = h.innerHTML; h.parentNode.removeChild(h);
            //o = e = h = null;
        }
    }
};
var jsLoadAsync = function(url, t) {
    setTimeout(function(){onDemandJsLoader(url)}, t);
};

document.observe("dom:loaded", function() {
    HTML_SWITCHER.replace();
});
