String.prototype.html_entity_decode = function(){
 return this.replace(/&gt;/ig,">").replace(/&lt;/ig,"<").replace(/&amp;/ig,"&").replace(/&nbsp;/ig," ");
};

String.prototype.wordWrap = function(m, b, c){
      var i, j, l, s, r;
      if(m < 1)
          return this;
      for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
         for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
              j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
              || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
      return r.join("\n");
};

 Event.observe(window, 'load', function(event) {

     if ($('hidden_box')){
         var a = new Draggable('hidden_box');
         a.element.setStyle({ cursor: 'move' });

        $('hidden_box').observe('dblclick', function(event){

                $('hidden_box').style.display = 'none';
        });
     }
 });

function confirm_delete(text){
 return confirm (text ? text : "Are you sure that you want to delete this item?");
}

function cm_over(obj,color){

    obj.style.backgroundColor = color ? color : '#DDDDDD';
}
function cm_out(obj,color){

    obj.style.backgroundColor  = color ? color: '';
}

/**
  * send data to the server
  * @param string return_no - object ID in which content if need to be returned
  * @param string params - string with parameters
  * @param bool form - true if you want to return reponse in the form field
  * @param string eval_after - javascript code that need to be evaluated after response recevied
  *
  */
function send_data(return_to,params,form,eval_after){ // POST method

    // $('loading').style.display = 'block';
    new Ajax.Request(  'jsfunctions.php', {
        parameters: params ,
        onComplete:  function(transport) {
            if (200 == transport.status){

                  if (form){ // return form field results
                       $(return_to).value = transport.responseText;

                  }else if (return_to){ // return html object results
                       $(return_to).innerHTML = transport.responseText;
                  }
                  if (eval_after) eval(eval_after);

                  //$('loading').style.display = 'none';
            }
        },
        onFailure : function(){

            alert('Couldn\'t complete request. Please try later.');
        }
    });

    return false;
}

/**
  * get object X coordinate
  */
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;
}

/**
  * get object Y coordinate
  */
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;
}

/**
 * tinyMCE callback function  'handle_event_callback'
 */
function tinymce_event(e){

   // $('debug').innerHTML = $('debug').innerHTML + e.type + '<br>';

    if (e.type == 'keyup'){

        $('post_words').innerHTML = calculate_words(tinyMCE.get('content').getContent());
        check_completed();
    }

    return true;
}

/**
 *  Add green checkmark in realtime in
 *  @version 2010/04/12
 */
function check_completed(){

    var content = tinyMCE.get('content').getContent();
        content = content.html_entity_decode();

    var nwords = calculate_words(content);

    var post_type = $F('post_type');
    var enough_words = false;
    var prefix = '';
    var keyword_id = $F('keyword_id');

    switch (post_type){
        case 'blurbpost':
            enough_words = (nwords > REQUIREMENTS.blurbpost);
            prefix = 'b';
        break;
        case 'biz_blurb':
            enough_words = (nwords > REQUIREMENTS.biz_blurb);
            prefix = 'bb';
        break;
        case 'minipost':
            enough_words = (nwords > REQUIREMENTS.minipost);
            prefix = 'm';
        break;
        case 'article':
            enough_words = (nwords > REQUIREMENTS.article);
            prefix = 'a';
        break;
        case 'medium_article':
            enough_words = (nwords > REQUIREMENTS.medium_article);
            prefix = 'ma';
        break;
        case 'large_article':
            enough_words = (nwords > REQUIREMENTS.large_article);
            prefix = 'la';
        break;
        case 'original':
            prefix = 'o';
            enough_words = (nwords > $F('num_words'));
        break;
        case 'rewritten':
            prefix = 'r';
            enough_words = (nwords > $F('num_words'));
        break;
        case 'sales':
            prefix = 's';
            enough_words = (nwords > $F('num_words'));
    }

    keywords_found = 0;
    keywords_exist = 0;

    el = $('project_posts').descendants();
    for (i=0;i<el.length;i++){

        if (el[i].tagName == 'INPUT' && el[i].name.indexOf('post_keyword') === 0){

           keywords_found++;

            x_id = el[i].name.replace(/[^\d]+/g,"");
            if (el[i].value && content.indexOf(el[i].value) > -1){ // keyword exists in article content

                $('keyword_checkmark_' + x_id).innerHTML = '<img src="images/done.gif" alt="" />';
                keywords_exist++;

            }else{

                $('keyword_checkmark_' + x_id).innerHTML = '';
            }
        }
    }

    if (keywords_found == keywords_exist && enough_words && $F('post_title')){

        $(prefix + '_keyword_' + keyword_id).src = 'images/done.gif';
    }else{
        $(prefix + '_keyword_' + keyword_id).src = 'images/details.gif';
    }
    return true;
}


/**
 * tinyMCE callback function  'setupcontent_callback'
 */
function tinymce_setupcontent(editor_id, body, doc){

   $('post_words').innerHTML = calculate_words(body.innerHTML);
   return true;
}

/**
 * calculate amount of words in the received text
 */
function  calculate_words(text){

    if (text){
        text = text.stripTags(); // prototype method
        text = text.unescapeHTML(); // prototype method

        text = text.replace(/&nbsp;/g," ");

        //var words = text.match(/\b\w+\b/g);
         var words = text.match(/[^\s]+/g);
         if (!words)return 0;
         return words.length ? words.length : 0;

        // var words = text.split(" ");
        // return  words ? words.length : 0;
    }

    return 0;
}

/**
 *  send request when writer clicks on the row with project on the projects list
 */
function request_project(project_id, mod){

    if (mod == 'queue'){

        $('hidden_box').style.display = 'none';
        $('hidden_box').innerHTML = '';

        send_data('hidden_box','mod=projects&a=notes&project_id=' + project_id,false,'confirm_acception(' + project_id + ')');

    }else if (mod == 'accept' || mod == 'reject'){

        document.location = 'index.php?mod=projects&a=edit&project_id=' + project_id;
    }
    return false;
}

/**
 * confirm project acception when project notes added in the hidden box
 */
function confirm_acception(project_id){

    notes = $('hidden_box').innerHTML;

    notes = notes.replace(/<br>/ig, '\r\n');
    notes = notes.replace(/<br \/>/ig, '\r\n');
    notes = notes.replace(/&gt;/ig, '>');
    notes = notes.replace(/&lt;/ig, '<');
    notes = notes.replace(/&amp;/ig, '&');
    notes = notes.stripTags();

    if (confirm ('Are you sure you want to accept this project? It will be due in ' + acception_timeframe + ' hours.\r\nThe notes for the projects are as follows:\r\n\r\n' +  notes.wordWrap(60, "\r\n", false)) ){

    	if (confirm('This job must be completed by ' + acception_date + '. Do you still accept?')){

        	document.location = 'index.php?mod=projects&a=accept&project_id=' + project_id;
		}
    }

    return false;
}

/**
 * event: mouseover on project row
 */
function project_over(obj,mod,project_id){

    // change cursor
    if (mod == 'queue' || mod == 'accept' || mod == 'reject'){
        mod = (mod == 'queue' ? 'accept' : 'edit');
        obj.style.cursor = 'hand';
    }

    cm_over(obj);
  return false;
}

/**
 * display popup box with project notes
 */
function project_notes(obj,project_id){

  x = findPosX(obj);
  //x = document.body.clientWidth;
  y = findPosY(obj);

   // set form position
  $('hidden_box').innerHTML = '';
  $('hidden_box').style.display = 'block';
  $('hidden_box').style.top = (y-220) + 'px';  // 400 x 370
  $('hidden_box').style.left = (x+20) + 'px';

  send_data('hidden_box','mod=projects&a=notes&project_id=' + project_id + '&notes=1');
  return false;
}

/**
 * display popup box with poor rating notes
 */
function ratings_notes(obj,notes){

   x = findPosX(obj);
  //x = document.body.clientWidth;
  y = findPosY(obj);

   // set form position
  $('hidden_box').innerHTML = notes;
  $('hidden_box').style.display = 'block';
  $('hidden_box').style.top = (y+30) + 'px';  // 400 x 370
  $('hidden_box').style.left = (x+20) + 'px';

  cm_over(obj);
  return false;
}

/**
 * hide rating notes
 */
function hide_notes(obj){

    $('hidden_box').style.display = 'none';
     cm_out(obj);
}