String.prototype.html_entity_decode = function(){
 return this.replace(/&gt;/i,">").replace(/&lt;/i,"<").replace(/&amp;/i,"&");
};

/**
  * do something when page loaded
  */

 Event.observe(window, 'load', function(event) {

    $('hidden_form').observe('dblclick', function(event){

            $('hidden_form').style.display = 'none';
    });
 });

function confirm_delete(name){
 return confirm ("Are you sure that you want to delete" + (name ? ' ' + name : '' ) + "?");
}
var jsbposts;
function send_data(return_to,params,form,a,eval_after){ // POST method

    $('loading').style.display = 'block';
    new Ajax.Request(  host_path + '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);

                  if (jsbposts && $('content')){

                       //  tinyMCE.idCounter=0; // tinyMCE 2.x

                       tinyMCE.editors = new Array(); // tinyMCE 3.x
                       tinyMCE.execCommand('mceAddControl', true, 'content');

                       //tinyMCE.execCommand('mceAddControl', false, $('content'));

                       jsbposts = false;
                  }
                  $('loading').style.display = 'none';
            }
        }
    });

    return false;
}

function add_tags(tag1,tag2,field_id){

  var mytplbox = document.getElementById(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;
}

/**
 * @desc add link for the selected page (in the drop down menu) into active tinyMCE element
 */
function get_selected_link(obj_from,obj_to,btn_obj){

    var link = "";
    obj = document.getElementById(obj_from);

    for (i=0;i<obj.length;i++){

        if (obj.options[i].selected) {
					// Split the title out
					var End = obj.options[i].text.indexOf(" || ");
					link = '<a href="' + obj.options[i].value + '">' + obj.options[i].text.substring(0, End) + '</a>';
				}
    }

    if (typeof(tinyMCE) != 'undefined'){

       tinyMCE.execCommand("mceInsertContent",false,link);

       btn_obj.blur();
       tinyMCE.execCommand('mceFocus', false, 'content');

       var _content = tinyMCE.get('content').getContent();
       $('post_words').innerHTML = calculate_words(_content);

    }else{
       add_tags(link,'',obj_to);

       btn_obj.blur();
       $('content').focus();
    }


    return false;
}


/**
 * @desc tinyMCE callback function  'handle_event_callback'
 */
function tinymce_event(e){

    if (e.type == 'keyup'){

        var _content = tinyMCE.get('content').getContent();
        $('post_words').innerHTML = calculate_words(_content);
    }
}

/**
 * @desc tinyMCE callback function  'setupcontent_callback'
 */
function tinymce_setupcontent(editor_id, body, doc){

   $('post_words').innerHTML = calculate_words(body.innerHTML);
}

/**
 * @desc 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);
         return words.length ? words.length : 0;

        // var words = text.split(" ");
        // return  words ? words.length : 0;
    }

    return 0;
}

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 update_state(country_id){

    if (country_id == 'US'){
        document.getElementById('state_text').style.display = 'none';
        document.getElementById('state_select').style.display = 'block';
    }else{
        document.getElementById('state_text').style.display = 'block';
        document.getElementById('state_select').style.display = 'none';
    }
}


function clipboard(obj_name,html){

  if (html){
   text = document.getElementById(obj_name).innerHTML;
  }else{
   text = document.getElementById(obj_name).value;
  }
  window.clipboardData.setData('Text',text);
  alert ('"' + text + '"\r\n has been copied to clipboard' );
  return false;
}

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 postpreview(link_obj,params){

   x = findPosX(link_obj);
   y = findPosY(link_obj);

   // set form position
   obj = $('hidden_form');

   obj.style.display = 'block';
   obj.style.top = (y - 200 ) + 'px';
   obj.style.left = (x + 50 )  + 'px';

   send_data('hidden_form','a=bposts&'+params);

  return false;

}

function fetch_links(){

    if (document.getElementById('domain').value){
        document.getElementById('block_form').style.display = 'block';
        send_data('project_links','a=fetchlinks&domain='+encodeURIComponent(document.getElementById('domain').value),true,false,'document.getElementById("block_form").style.display = "none";');
    }else{
        alert ('Empty Domain');
    }
    return false;
}


function cm_over(obj,color){

    obj.style.backgroundColor = color ? color : '#DDDDDD';
}
function cm_out(obj,color){

    obj.style.backgroundColor  = color ? color: '#E7F0FA';
}

function load_w9form(form_id){

    var myHead = document.getElementsByTagName( 'head' ).item(0);

    myLink = document.createElement('link');
    myLink.setAttribute( 'href', host_path + 'tpl/w9form.css');
    myLink.setAttribute( 'rel', 'stylesheet');
    myLink.setAttribute( 'type', 'text/css');

    myHead.appendChild( myLink );
    return up_page(form_id);
}

/**
 *  function that allows to hide/show videos on the support page
 *  @version 2009/09/03
 */
 function show_hide_video(video){

    if (video){

        $('btn_support_videos').innerHTML = '<a href="" onclick="return show_hide_video(false)"><img src="../images/btn_hide_video.jpg" alt="Hide Videos" title="Hide Videos" /></a>';
        $('support_videos').style.display = 'block';

    }else{

        $('btn_support_videos').innerHTML = '<a href="" onclick="return show_hide_video(true)"><img src="../images/btn_show_video.jpg" alt="Show Videos" title="Show Videos" /></a>';
        $('support_videos').style.display = 'none';
    }
    return false;
 }

 /**
 * remove/add default fields text
 */
 BOOKMARKING_FIELDS = {};
function fields_text(obj,action,text){

		// Don't remove the existing content if it's different from the default text
		if (obj.value != "" && text != obj.value) {
			return true;
		}

    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) && obj.value != text) $('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++){

        // Check Anchor Text 1
		if (form[i].name.indexOf('bookmark_title1') > -1){

           l = form[i].value.length;

           if (form[i].value.indexOf('e.g.') === 0){

              l = 0;
           }

           if (l < 8 ){

                alert('Anchor Text 1 needs at least 8 characters. You have ' + l + '.');
                return false;

           }
        }
		
		// Check Anchor Text 2
		if (form[i].name.indexOf('bookmark_title2') > -1){

           l = form[i].value.length;

           if (form[i].value.indexOf('e.g.') === 0){

              l = 0;
           }

           if (l < 10 ){

                alert('Anchor Text 2 needs at least 10 characters. You have ' + l + '.');
                return false;

           }
        }
		
		// Check Anchor Text 3
		if (form[i].name.indexOf('bookmark_title3') > -1){

           l = form[i].value.length;

           if (form[i].value.indexOf('e.g.') === 0){

              l = 0;
           }

           if (l < 12 ){

                alert('Anchor Text 3 needs at least 12 characters. You have ' + l + '.');
                return false;

           }
        }
		
		// check bookmark description 1, 2 and 3
		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;
}


function showhint(link_obj,text,size){

   if (text == 'OFF'){
        $('hidden_form').style.display = 'none';
        return true;
   }

   x = findPosX(link_obj);
   y = findPosY(link_obj);

   // set form position
   obj = $('hidden_form');

   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;

}

/**
 * modal box with requested page
 */
function add_modal_box(page_link, box_title, box_width){

   page_link = page_link.replace('projects/index.php','jsfunctions.php');

   Modalbox.show(page_link, {title: box_title,
                             width: box_width,
                             afterLoad : function (){


                                                        tinyMCE.init({
                                                            mode : "textareas",theme : "simple",
                                                            elements : "content",
                                                            editor_selector : "content"
                                                            });

                                        }
                            }
                );
   return false;
}

// Function for calculating/displaying available credits for outsourcing articles.
function updateArticleTotals() {
	var BatchCount = document.getElementById('batch_count');
	var TotalCredits = 0;
	var CurrentTotal = document.getElementById('outsource_total');
	var AvailableCredits = document.getElementById('user_credits_required');
	var ArticlesCount = 0;
	var SingleCost = document.getElementById('article_cost').value;
	var MultiCost = document.getElementById('article_multi_cost').value;

	// Reset the current available in case the user is making a change
	AvailableCredits.innerHTML = parseInt(AvailableCredits.innerHTML) + parseInt(CurrentTotal.innerHTML);

	if (BatchCount) {
		for (i = 0; i < BatchCount.value; i++) {
			var NumArticles = document.getElementById('num_articles[' + i + ']');
			if (NumArticles && NumArticles.value != "") {
				ArticlesCount++;
				TotalCredits += parseInt(NumArticles.value);
			}
		}

		if (ArticlesCount > 1) {
			TotalCredits = TotalCredits * MultiCost;
		} else {
			TotalCredits = TotalCredits * SingleCost;
		}

		CurrentTotal.innerHTML = TotalCredits;
		AvailableCredits.innerHTML = parseInt(AvailableCredits.innerHTML) - TotalCredits;
	} else {
		return;
	}
}

// Function for calculating/displaying available credits for outsourcing articles.
function updatePostTotals() {
	var NumPosts = new Array();
	for (var i = 0; i < 5; i++) {
		NumPosts[i] = document.getElementById('num_posts[' + i +']');
	}
	var TotalCredits = 0;
	var CurrentTotal = document.getElementById('outsource_total');
	var AvailableCredits = document.getElementById('user_credits_required');
	var SingleCost = 1;
	var MorePosts = document.getElementById("more_posts");
	var SubmitButton = document.getElementById("submit");

	// Reset the current available in case the user is making a change
	AvailableCredits.innerHTML = parseInt(AvailableCredits.innerHTML) + parseInt(CurrentTotal.innerHTML);

	// Total up the current count
	for (i = 0; i < 5; i++) {
		if (NumPosts[i].value != "") {
			TotalCredits += (parseInt(NumPosts[i].value * SingleCost));
		}
	}

	CurrentTotal.innerHTML = TotalCredits;
	AvailableCredits.innerHTML = parseInt(AvailableCredits.innerHTML) - TotalCredits;
	if (TotalCredits > 4) {
		var OutsourceNotes = document.getElementById('outsource_notes');
		OutsourceNotes.style.display = 'block';
		MorePosts.style.display = "none";
		SubmitButton.disabled = false;
	} else {
		MorePosts.style.display = "block";
		SubmitButton.disabled = true;
	}
}

// Function for disabling/enabling extra fields on the article outsource form
function UpdateMultiLink(MultiLinkBox) {
	var Controls = new Array();
	Controls[0] = document.getElementById("link_notes[1]");
	Controls[1] = document.getElementById("link_notes[2]");
	Controls[2] = document.getElementById("num_articles[1]");
	Controls[3] = document.getElementById("num_articles[2]");
	var InfoDiv = document.getElementById("multilink_notes");
	if (MultiLinkBox.checked == true) {
		// Hide the extra fields and show the info
		for (var i = 0; i < 4; i++) {
			Controls[i].value = "";
			Controls[i].style.display = "none";
		}
		InfoDiv.style.display = "inline";
	} else {
		// Show the extra fields and hide the info
		for (var i = 0; i < 4; i++) {
			Controls[i].style.display = "block";
		}
		InfoDiv.style.display = "none";
	}

	// Reset the credit total
	updateArticleTotals();
}

function mouse_over(obj){
   new Effect.Fade(obj, {duration: .3, from: 1, to: .8});
   return false;
}

function mouse_out(obj){
   new Effect.Fade(obj, {duration: .3, from: .8, to: 1});
   return false;
}

// Validate the project wizard step 1 form
function ValidateStep1() {
	var Errors = Array();
	var CurrentIndex = 0;
	var Temp = "";
	Temp = document.step1.keyword.value.replace(/ /gi, '');
	if (Temp.length < 3) {
		Errors[CurrentIndex] = "Your project name is too short or is missing.";
		CurrentIndex++;
	}
	if (document.step1.keyword.value.length > 30) {
		Errors[CurrentIndex] = "Your project name cannot exceed 30 characters. You currently have " + document.step1.keyword.value.length + " characters.";
		CurrentIndex++;
	}
	Temp = document.step1.domain.value.replace(/ /gi, '');
	if (Temp.length < 3) {
		Errors[CurrentIndex] = "Your domain is too short or is missing.";
		CurrentIndex++;
	}
	if (document.step1.domain.value.length > 65) {
		Errors[CurrentIndex] = "Your domain cannot exceed 65 characters. You currently have " + document.step1.domain.value.length + " characters.";
		CurrentIndex++;
	}
	Temp = document.step1.category_id.value.replace(/ /gi, '');
	if (Temp.length < 3) {
		Errors[CurrentIndex] = "You have not selected a category for the project.";
		CurrentIndex++;
	}
	Temp = document.step1.project_description.value.replace(/ /gi, '');
	if (Temp.length < 3) {
		Errors[CurrentIndex] = "Your project description is too short or is missing.";
		CurrentIndex++;
	}
	
	if (CurrentIndex > 0) {
		var ErrorMessage = "Please correct the following errors:\n\n";
		for (var i = 0; i < CurrentIndex; i++) {
			ErrorMessage += "     - " + Errors[i] + "\n";
		}
		alert(ErrorMessage);
		return false;
	} else {
		return true;
	}
}

// Autopilot research notes validation code for links_research.tpl
function ValidateResearchNotes() {
	// Check to make sure we have at least 1 note
	var NoteCount = 0;
	for (i = 0; i < 6; i++) {
		var NoteId = "ResearchNotes_" + i;
		var Note = document.getElementById(NoteId);
		if (Note) {
			var NoteText = Note.value.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
			if (NoteText != "") {
				NoteCount++;
			}
		}
	}
	
	if (NoteCount < 1) {
		alert("You don't have any research notes specified. Please store at least one research note.");
		return false;
	} else {
		return true;
	}
}

