/** @version 2009/10/06
 */

var tpl_field =null;

String.prototype.trim = function(){
 a = this.replace(/^\s+/, '');
 return a.replace(/\s+$/, '');
};

Event.observe(window, 'load', function(event) {

     if ($('content_help')){
         var a = new Draggable('content_help');
         a.element.setStyle({ cursor: 'move' });

        $('content_help').observe('dblclick', function(event){

                $('content_help').style.display = 'none';
        });
     }
 });


function confirm_delete(name){
 return confirm ("Are you sure that you want to delete?");
}

function _id(element_id){
    return document.getElementById(element_id);
}

function cm_over(obj,color){

    obj.style.backgroundColor = color ? color : '#DDDDDD';
}
function cm_out(obj,color){

    obj.style.backgroundColor  = color ? color: '#FFFFFF';
}

function send_data (params,path){

     path = path ? '' : '../';

/*  alert (path + 'jsfunctions.php?' + params);
  return false;*/

    var myBody = document.getElementsByTagName( 'body' ).item(0);
    myScript = document.createElement('script');
    myScript.setAttribute( 'src', path + 'jsfunctions.php?' + params);
    myBody.appendChild( myScript );
}

/**
  * send post data using XMLHTTP
  * return_to ID of element in which returned data should be added using .innerHTML property
  *      if return_to = eval  than function returned response will be used in eval() function
            return_to = nothing do nothing with returned response
  * params data to send
  */
function send_post_data(return_to,params){ // POST method for url encoded form

     var timeval = new Date().getTime();
     var http;
     try {
        http = new ActiveXObject('Msxml2.XMLHTTP');
     }catch (e){
            try {
                   http = new ActiveXObject('Microsoft.XMLHTTP');
            }catch (e2){
                try {
                   http = new XMLHttpRequest();
                }catch (e3) {
                   http = false;
                }
            }
     }
     if (!http){
         alert('Couldn\'t initializate object in your browser.');
         return false;
     }

     var url = host_path + "jsfunctions.php?timeval=" + timeval;

     http.open("POST", url, true);

     //Send the proper header information along with the request
     http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     http.setRequestHeader("Content-length", params.length);
     http.setRequestHeader("Connection", "close");

     //Call a function when the state changes.
     http.onreadystatechange = function() {
             if(http.readyState == 4 && http.status == 200){
                   // alert(http.responseText);
                  if (return_to == 'eval'){

                      eval(http.responseText);

                  }else if (return_to != 'nothing'){

                      _id(return_to).innerHTML = http.responseText;
                  }

                  http = null;
                  url = null;
             }
     }
     http.send(params);
     return false;
}

function display_progress_box(status){

    if (status){

          scroll_position = getScrollXY();
          win_size = getWindowSize();

          _id('progress_box').style.width = win_size[0] + 'px';
          _id('progress_box').style.height =  (scroll_position[1] + win_size[1]) + 'px' ;

          _id('progress_image').style.marginTop = (win_size[1]/2 - 16) + 'px';

    }
    _id('progress_box').style.display = status ? 'block' : 'none';
}

function findPosX(obj){
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;

    return curleft;
}
function findPosY(obj){
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}



function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }

  return [ myWidth, myHeight ];

}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

/* **************************************************************************************************************************************** */

function add_token(token,field_id){

  var mytplbox = _id(field_id);
//   var mytplbox = document.tplform.field_id;

       //IE support
       if (document.selection) {
           mytplbox.focus();
           sel = document.selection.createRange();
           sel.text = token;
//           document.tplform.insert.focus();
       }

       //MOZILLA/NETSCAPE support
       else if (mytplbox.selectionStart || mytplbox.selectionStart == "0") {
           var startPos = mytplbox.selectionStart;
           var endPos = mytplbox.selectionEnd;
           var now_tpl = mytplbox.value;

           mytplbox.value = now_tpl.substring(0, startPos) + token + now_tpl.substring(endPos, now_tpl.length);
       } else {
           mytplbox.value += token;
       }

   return false;
}

function add_item_token(token){

  if (!tpl_field){

     alert ('Field is not selected.');
     return false;
  }

  var mytplbox = _id(tpl_field);
//   var mytplbox = document.tplform.field_id;

       //IE support
       if (document.selection) {
           mytplbox.focus();
           sel = document.selection.createRange();
           sel.text = token;
//           document.tplform.insert.focus();
       }

       //MOZILLA/NETSCAPE support
       else if (mytplbox.selectionStart || mytplbox.selectionStart == "0") {
           var startPos = mytplbox.selectionStart;
           var endPos = mytplbox.selectionEnd;
           var now_tpl = mytplbox.value;

           mytplbox.value = now_tpl.substring(0, startPos) + token + now_tpl.substring(endPos, now_tpl.length);
       } else {
           mytplbox.value += token;
       }

  return false;
}

function add_tags(tag1,tag2,field_id){

  var mytplbox = _id(field_id);

       //IE support
       if (document.selection) {
           mytplbox.focus();
           sel = document.selection.createRange();
           sel.text = tag1 + sel.text + tag2;
           // document.tplform.insert.focus();
       }
       //MOZILLA/NETSCAPE support
       else if (mytplbox.selectionStart || mytplbox.selectionStart == "0") {
           var startPos = mytplbox.selectionStart;
           var endPos = mytplbox.selectionEnd;
           var now_tpl = mytplbox.value;

           mytplbox.value = now_tpl.substring(0,startPos) + tag1 + now_tpl.substring(startPos, endPos)  + tag2 + now_tpl.substring(endPos,now_tpl.length);

       } else {
           sel_text  = mytplbox.value;
           mytplbox.value = tag1 + mytplbox.value + tag2;
       }

   return false;
}
function get_tpl(project_id,tpl_name){

    send_data ('ads=' + tpl_name + '&project_id=' + project_id);
    return false;
}

function get_color(token_name){

    params = 'color_item=' + token_name + '&project_id=' + _id('project_id').value +  '&color_new=' + _id('color_value').value;
    send_data (params);
    return false;
}

function update_basic_templage(obj){ // update template info on the basic page

    send_data ('basic_tpl=' + (obj.value ? obj.value : 'custom&project_id=' + _id('project_id').value) );
    return false;
}

function set_box_color(color){

   if (color.length == 6 ){

         _id('color_box_2').style.backgroundColor ='#'+color;

         switch (_id('tmp_token').value){
           case 'background':
              setStyleById('example_box', 'backgroundColor', color);
             break;
           case 'logobackground':
              setStyleById('example_logo', 'backgroundColor', color);
            break;
           case 'largefont':
              setStyleById('example_logo', 'color', color);
            break;
           case 'largefont2':
              setStyleById('example_article2', 'color', color);
            break;
           case 'articlebackground':
              setStyleById('example_article', 'backgroundColor', color);
              setStyleById('example_article2', 'backgroundColor', color);
            break;
           case 'articlefont':
               setStyleById('example_article', 'color', color);
            break;
           case 'link':
                cssrule = find_css_class('#example_box a');
                cssrule.style.color =color;
            break;
           case 'linkhover':
                cssrule = find_css_class('#example_box a:hover');
                cssrule.style.color =color;
            break;
         }
   }
}

function update_font(font){

  _id('color_box').style.fontFamily = font;
  _id('color_box_2').style.fontFamily = font;

  setStyleById('example_box', 'fontFamily', font);
  send_data ('fontsize_text=' + _id('fontsize').value +'&font_family='+font);
}

function update_fontsize(fontsize){

  _id('color_box').style.fontSize = fontsize;
  _id('color_box_2').style.fontSize = fontsize;

  setStyleById('example_box', 'fontSize', fontsize);
  send_data ('fontsize_text=' + fontsize +'&font_family='+_id('font').value);

}

function page_preview(){

 if ( _id('page_id').value ) _id('preview_area').innerHTML = '<iframe src="index.php?a=siteupload&project_id=' +
                                                         _id('project_id').value +
                                                         '&preview=' +
                                                         _id('page_id').value +
                                                         '" width="700" height="400"></iframe>';
 if (_id('message_box')) _id('message_box').style.display = 'none';
}

function setStyleById(i, p, v) {

        var n = _id(i);
        n.style[p] = v;
}

function find_css_class (findstr){

         var mysheet=document.styleSheets[0]
         var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules
         for (i=0; i<myrules.length; i++){
               if(myrules[i].selectorText.toLowerCase()== findstr){
               targetrule=myrules[i];
               break;
              }
         }
         return targetrule;
}

/*  ******************************************************************************* */
function check_items(obj_id,item){

   form  =  _id('frm_site_pages');

   for (i=0; i < form.elements.length; i++){
      ele = form.elements[i];

      if (ele.id.indexOf(obj_id) > -1 ){
            _id(ele.id).checked = item;
      }
   }
}

function check_group(obj,group,keyword){

    form  =  _id('keyword_form');
    theStr = '';

    if (group){

      if (obj.checked){
             _id('keywords_' + group).checked = obj.checked;
      }

    }else if(keyword){

      for (i=0; i < form.elements.length; i++){


         ele = form.elements[i];
         if (ele.id.indexOf('group_'+ keyword) > -1 ) _id(ele.id).checked = obj.checked;
      }
    }
}

function update_link2(item_id){ // update status of link from url submission list

   send_data ('url_id=' + item_id);
   return true;
}

function copy_paste(obj,title){

   if ((navigator.appName=="Microsoft Internet Explorer")&&(parseInt(navigator.appVersion)>=4)){

     obj.select();
      obj.focus();
      textRange = obj.createTextRange();
     textRange.execCommand("RemoveFormat");
      textRange.execCommand("Copy");
      alert(title + ' has been copied to clipboard');

   }else{
      obj.select();
      obj.focus();
   }
}
function submit_aw_page(obj_id,phrase,aw_id){ /*submit new project page using awstat search keyphrase */


  send_data ('awstat_phrase='+phrase+'&aw_id='+aw_id+'&obj_id='+obj_id);
  return false;
}
/* domain info tools */

function fetch_domain_info(name,item){

    _id('update_box'+ (item ? '_'+item : '' )).src = (item == 'alldomains' ? '../img/progress2_1.gif' : '../img/progress2.gif');
    send_data ('fetch_domain=' + (name ? name : _id('domain_name').value )+ (item ? '&item='+item : ''));

  return false;
}

function update_awstats(){

    if (_id('domain_id') && _id('domain_id').value){

        _id('update_box_aw').src = '../img/progress2.gif';

        send_data('awstats=1&id=' + _id('domain_id').value +
                                   '&ftplogin=' + base64encode(_id('domain_ftplogin').value) +
                                   '&ftppwd=' + base64encode(_id('domain_ftppwd').value) +
                                   '&ftppath=' + _id('domain_ftppath').value);

    }else{
       alert ('Unknown Error.');
    }
    return false;
}

var base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function base64encode(str){
    var out, i, len;
    var c1, c2, c3;
    len = str.length;
    i = 0;
    out = '';
    while(i < len){
    c1 = str.charCodeAt(i++) & 0xff;
    if(i == len){
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt((c1 & 0x3) << 4);
        out += '==';
        break;
    }
    c2 = str.charCodeAt(i++);
    if(i == len){
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt((c2 & 0xF) << 2);
        out += '=';
        break;
    }
    c3 = str.charCodeAt(i++);
    out += base64EncodeChars.charAt(c1 >> 2);
    out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
    out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
    out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
}

function preview_page(width,height,pic_id){

  width = width*1+30;
  height = height*1+30;

  window.open('index.php?a=picpreview&pic_id='+pic_id, null, 'height='+height+',width='+width+',status=no,toolbar=no,titlebar=no,menubar=no,location=no, scrollbars=yes');
  return false;
}

function support_movie(path,support_id){
  window.open(path+'index.php?a=support&movie='+support_id, null, 'height=560,width=680,status=no,toolbar=no,titlebar=no,menubar=no,location=no, scrollbars=yes');
  return false;
}

function popup_window(url){
  window.open(url, null, 'height=300,width=400,status=no,toolbar=no,titlebar=no,menubar=no,location=no, scrollbars=yes');
  return false;
}

/* */

function submit_article2site(site_id){
   send_data ('submit_asite=' + site_id);
}
function submit_link2site(site_id){
   send_data ('submit_lsite=' + site_id);
}


function clipboard(obj_name,html){

  if (html){
   text = _id(obj_name).innerHTML;
  }else{
   text = _id(obj_name).value;
  }
  window.clipboardData.setData('Text',text);
  alert ('"' + text + '"\r\n has been copied to clipboard' );
  return false;
}

function last_field(txt){

  tpl_field = txt;
}

function show_hide(obj,block_id){

    if (_id(block_id + '_0').style.display == 'block'){
           _id(block_id + '_0').style.display = 'none';
           _id(block_id + '_1').style.display = 'none';
           obj.innerHTML = '&nbsp;+&nbsp;';
    }else{
           _id(block_id + '_0').style.display = 'block';
           _id(block_id + '_1').style.display = 'block';
           obj.innerHTML = '&nbsp;-&nbsp;';
    }
}

function update_state(country_id){

         if (country_id == 'US'){
             _id('state_text').style.display = 'none';
             _id('state_select').style.display = 'block';
         }else{
             _id('state_text').style.display = 'block';
             _id('state_select').style.display = 'none';
         }
}

function check_all (obj,form_id){


   form  =  _id(form_id);
   for (i=0; i < form.elements.length; i++){
      ele = form.elements[i];

      if (ele.name.indexOf(obj.name) > -1) ele.checked = true;
   }
}

/** check all checkboxes with prefix = item_prefix and numeric sufix 1-100
 *  anchor object
 *  items prefix
*/
function check_all_boxes(anchor_obj,item_prefix){

    var i= 1;
    while(true){

         if (obj_box = _id(item_prefix + i)){

            obj_box.checked = true;
         }else{
            break;
         }
         ++i;
    }
    return false;
}

function outsource_message(type){

   if (type == 'disabled'){
      alert ('The article queue is full. Please try again tomorrow.');
   }else{
      alert ("You've already submitted articles for this project. Please\r\nwait until you've received and imported this project\r\nbefore submitting more.");
   }
   return false;
}

function calc_lines(text,itemprice){

       var keywords = calc_keywords(text);

       obj_info = _id('order_info');
       order_info(obj_info,keywords);

       keywords = (keywords < 10 ?  10 : keywords);

       var total = keywords*itemprice;
       total = total.toFixed(2);

       _id('quantity').value = keywords;
       _id('total_amount').innerHTML = total;
}

function calc_elines(text){

     obj =  _id('order_einfo');
     var keywords = calc_keywords(text);

     order_info(obj,keywords,5);
}

function calc_keywords(text){

    if (text = text.trim()){

       var lines = text.split("\n");
       var keywords = lines.length;

    }else{
         var keywords = 0;
    }
    return keywords;
}

function order_info(obj,keywords,limit){

  limit = limit ? limit : 10;

  if (keywords < limit){
      obj.innerHTML = '(You need to add "' + (limit - keywords) + '" more keywords to this order.)';
  }else{
      obj.innerHTML = '(This project meets the minimum keyword requirement.)';
  }
}

/**
 *  @version 2009/12/01
 */
function insert_link(obj_to,url,keyword){

    if (typeof(tinyMCE) != 'undefined'){

       var inst = tinyMCE.getInstanceById(obj_to);
       var sel = inst.selection.getContent({format : 'text'});

       keyword = sel ? sel : keyword;
       link = '<a  id="mceNewAnchor" href="' + url + '">' + keyword + '</a>';

       tinyMCE.execCommand("mceInsertContent",false,link);
        e = inst.getDoc().getElementById('mceNewAnchor');

        if (e){
            inst.selection.select(e, false, true, true);
            e.removeAttribute('id');
        }

    }else{
       add_token(url,obj_to);
    }
}

function update_khelper(project_id,item_id){

   show_loading('block');
   send_data ('update_khelper='+ item_id + '&project_id=' + project_id);

}

function show_loading(type){

    _id('loading').style.display = type;
}

/**/

function hide_help(){

     _id('content_help').style.display = 'none';
     _id('content_help').innerHTML = '';
     return false;
}
function show_help(link_obj,params){

           x = findPosX(link_obj);
           y = findPosY(link_obj);

           w = getWindowSize();
           s = getScrollXY();

         if (x - s[0] +200 > w[0]){ // left oriented

             _id('content_help').style.top = (y+20)+'px';
             _id('content_help').style.left = (x-220)+'px';

         }else{ // right oriented

             _id('content_help').style.top = (y+20)+'px';
             _id('content_help').style.left = (x+20 )+'px';
         }

         send_post_data('content_help',params);

         _id('content_help').style.display = 'block';
     return false;
}

/**
 * privacy page tool
 */
function save_privacy(){

    if(confirm('Are you sure you want to use the Privacy Page Tool?')){

        alert('We are not responsible for any damages the Privacy Page Tool may cause. Please click "OK" to continue.');

        j=0; projects  = new Array();

        form_obj = _id('privacy_form');
        for (i=0; i < form_obj.elements.length; i++){

                el = form_obj.elements[i];
                if (el.type == 'checkbox' && el.name == 'project_id' && el.checked){

                    projects[j] = el.value;
                    j++;
                }
        }

        if (projects.length){ // all projects submitted

            display_progress_box(1);

            if (typeof(tinyMCE) != 'undefined'){
               var _content = tinyMCE.get('content').getContent();
            }else{
               var _content = _id('content').value;
            }

            send_post_data('eval','a=privacy&p=save_privacy&privacy_text=' + encodeURIComponent(_content) + '&projects_list=' + projects.join(','));
        }else{

            alert('You need to select at least one project to submit privacy page on it.');
        }
    }
    return false;
}

 /**
  * upload privacy pages for all selected projects
  * string projects_list commas separated selected project_id's
  */
function submit_privacy(projects_list){

    projects = projects_list.split(',');
    if (projects_list != ''){

        send_post_data('eval','a=privacy&p=submit_privacy&project_id=' + projects.shift() + '&projects_list=' + projects.join(',') + '&privacy_index=' + (_id('privacy_index').checked ? 1 : ''));
        return false;
   }

   alert('Selected projects have been submitted.');
   document.location = 'index.php?a=privacy';

   return false;
}

 /**
  * select all|none projects on the privacy page
  */
function privacy_select_projects(status){

        form_obj = _id('privacy_form');
        for (i=0; i < form_obj.elements.length; i++){

                el = form_obj.elements[i];
                if (el.type == 'checkbox' && el.name == 'project_id'){

                    el.checked = status;
                }
        }
        return false;
}

/*
 *          OUTSOURCE PROJECTS
*/

/**
  * hide or displayy fields when user tries to purchase new outsrouce posts
  */
function display_out_posts(link_id){

   _id('outsource_posts_' + link_id).style.display == 'block' ? _id('outsource_posts_' + link_id).style.display = 'none' : _id('outsource_posts_' + link_id).style.display = 'block';

}

/**
  * calculate how many credits requried to submit new outsource project. update fields with number of credits
  * @return number of credits
  */
function calculate_credits(){

//   var paid_bposts = 0;
//   paid_pages = _id('paid_articles').value;

   var credits_blurb = _id('credits_blurb').value;
   var credits_article = _id('credits_article').value;
   var total = 0;

   obj =  _id('outsource_form');
   for (i=0;i<obj.length;i++){ // scan form

       if (obj.elements[i].name.indexOf('blurbs') != -1 && obj.elements[i].value*1 == obj.elements[i].value){

           total += obj.elements[i].value * credits_blurb;

       }else if (obj.elements[i].name.indexOf('articles') != -1 && obj.elements[i].value*1 == obj.elements[i].value){

           total += obj.elements[i].value * credits_article;
       }
   }

   total = total.toFixed(2);
   _id('required_credits').innerHTML = total;
   _id('outsource_submit').style.display = (total > 0 ? 'block' : 'none');

   return total;
}

/**
  * update fields with number of credits. calculate how many credits requried to submit new outsource custom project,
  * @return number of credits
  */
function calculate_custom_project(){

   var word_cost = _id('ezine_word').value * 1;
   var light_research = _id('light_research').value * 1;
   var medium_research = _id('medium_research').value * 1;
   var heavy_research = _id('heavy_research').value * 1;

   var total = 0;

   obj =  _id('outsource_form');
   for (i=0;i<obj.length;i++){ // scan form

       if (obj.elements[i].name.indexOf('ezine_articles') != -1 && obj.elements[i].value*1 == obj.elements[i].value){

          link_id = obj.elements[i].name.match(/([\d]+)/gi);

          research =  _id('ezine_research_' + link_id).value;
          words =  _id('ezine_words_' + link_id).value;

          total += obj.elements[i].value * words * (word_cost + (research == 'light' ? light_research : (research == 'medium' ? medium_research : heavy_research )) );

       }
   }

   total = total.toFixed(2);
   _id('required_credits').innerHTML = total;
   _id('outsource_submit').style.display = (total > 0 ? 'block' : 'none');

   return total;
}

/**
 * tinyMCE callback function  'handle_event_callback'
 */
function tinymce_event(e){

    if (_id('post_words') && e.type == 'keyup'){

       var _content = tinyMCE.get('content').getContent();
       _id('post_words').innerHTML = calculate_words(_content);
    }
}

/**
 * tinyMCE callback function  'setupcontent_callback'
 */
function tinymce_setupcontent(editor_id, body, doc){

   if (_id('post_words')){

        _id('post_words').innerHTML = calculate_words(body.innerHTML);
   }
}

/**
 * calculate amount of words in the received text
 */
function calculate_words(text){

    if (text){
        text = strip_tags(text); // prototype method

        text = text.replace(/&nbsp;/g," ");
        var words = text.match(/[^\s]+/g);

        if (words){
            return words.length ? words.length : 0;
        }else{
        }   return 0;
    }
    return 0;
}

/**
 * http://phpjs.org/functions/strip_tags:535
 */
function strip_tags (str, allowed_tags) {

    var key = '', allowed = false;
    var matches = [];    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };
     // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }
     str += '';

    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
     // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;        }

        // Save HTML tag
        html = matches[key].toString();
         // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {                allowed = true;
                break;
            }
        }
         if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
     return str;
}

/**
 * display ticket reply in the blue box at the center of screen
 */
function display_reply(link_obj,reply_id){

   //  x = findPosX(link_obj);
   x = document.body.clientWidth;
   y = findPosY(link_obj);

   // set form position
   $('content_help').style.display = 'block';
   $('content_help').style.top = (y + 20) + 'px';  // 400 x 370
   $('content_help').style.left = (x/2 - 300 )  + 'px';

   send_post_data('content_help','a=messages&p=view&reply_id='+reply_id);

  return false;
}

 /**
 * remove/add default fields text
 */
 BOOKMARKING_FIELDS = {};
function fields_text(obj,action,text){

    f = obj.name;

    // span ID with number of character in the field
    chr_box = obj.name.replace(/.*?_/g,'');


    if (action == 'focus' && !BOOKMARKING_FIELDS[f]){

        obj.value = '';
        obj.setAttribute("className", "f_text_f");
        obj.setAttribute("class", "f_text_f");

        if ($('chr_' + chr_box)) $('chr_' + chr_box).innerHTML = 0;

    }else if (action == 'blur' && obj.value == ''){

        BOOKMARKING_FIELDS[f] = false;
        obj.value = text;
        obj.setAttribute("className", "f_text_b");
        obj.setAttribute("class", "f_text_b");

       if ($('chr_' + chr_box)) $('chr_' + chr_box).innerHTML = 0;

    }else if (action == 'blur'){

        BOOKMARKING_FIELDS[f] = true;
        if ($('chr_' + chr_box)) $('chr_' + chr_box).innerHTML = obj.value.length;
    }
}

/**
 * set number of characters in current field
 */

function fields_chr(obj){


    // span ID with number of character in the field
    chr_box = obj.name.replace(/.*?_/g,'');
    if ($('chr_' + chr_box)) $('chr_' + chr_box).innerHTML = obj.value.length;
}

/**
 *
 */
function check_bookmarking_form(form){

    for(i=0; i < form.length; i++){

        if (form[i].name.indexOf('bookmark_description') > -1){

           d = form[i].name.replace(/[^\d]+/g, '');
           l = form[i].value.length;

           if (form[i].value.indexOf('e.g.') === 0){

              l = 0;
           }

           if (l < 100 ){

                alert('You should add at least 100 characters in "Description ' + d + '". You have ' + l + ' characters there.');
                return false;

           }else if (l > 150){

                alert('You are allowed to add only 150 characters in "Description ' + d + '". You have ' + l + ' characters there.');
                return false;
           }
        }
    }
    return true;
}

/**
 *  display bookmarking project hits
 */
function showhint(link_obj,text,size){

   if (text == 'OFF'){

        $('content_help').style.display = 'none';
        return true;
   }

   x = findPosX(link_obj);
   y = findPosY(link_obj);

   // set form position
   obj = $('content_help');

   obj.innerHTML = '<div style="background-color: #FFFFE0;color:#000000; font-size:10px;border:1px solid #000000;padding:2px;border-bottom:2px solid #000000;border-right:2px solid #000000; width:' + size +'px;">' + text + '</div>';
   obj.style.display = 'block';
   obj.style.top = (y ) + 'px';
   obj.style.left = (x + 30 )  + 'px';


  return false;

}

/**
 *  hide display table with silo pages
 */
function silo_section(obj,silo_section){

    if ($('silo_section_' + silo_section)){

        if ($('silo_section_' + silo_section).style.display  == 'block'){ // hide silo section

            $('silo_section_' + silo_section).style.display = 'none';
            $(obj).innerHTML = '<img src="../img/plus.gif" alt="" />';

        }else{ // display silo section

            $('silo_section_' + silo_section).style.display = 'block';
            $(obj).innerHTML = '<img src="../img/minus.gif" alt="" />';
        }
    }
    return false;
}
