function suggestFriendlyName(n)
{
   f = n.form;
   n = n.value;
   var pt = /[^0-9a-z_]/gi;
   var ptn = /^[0-9]+/gi;
   n = n.replace(/\s+/g,"_").replace(pt,"").toLowerCase();

   f.friendly_name.value = n.replace(ptn,"");
}

function suggestCallbackFriendlyName(n)
{
   f = n.form;
   n = n.value;
   var pt = /[^0-9a-z_]/gi;
   var ptn = /^[0-9]+/gi;
   n = n.replace(/\s+/g,"_").replace(pt,"").toLowerCase();

   f.target_friendly_name.value = n.replace(ptn,"");
   if(f.target_autorun.options[f.target_autorun.selectedIndex].value == 0)
   {
      displayCallBackExample(n);
   }
}


function displayCallBackExample(v)
{
   var e = document.getElementById("cb_instructions"), t = document.getElementById("cd_title");
   if(v.length > 1)
   {
      t.style.display = "block";
      e.innerHTML = '<p>&lt;script type=&quot;text/javascript&quot;&gt;<br><b style="color:#003399">$BTB.execCallback(&quot;'+v.toLowerCase()+'&quot;);</b><br>&lt;/script&gt;</p>';
   }
   else
   {
      t.style.display = "none";
   }
}

function toggleAutoRunCallBack(n)
{
   var t = document.getElementById("cd_title").style, tu = document.getElementById("target_urls_wrapper").style, f = n.form.target_friendly_name.value;
	if(n.options[n.options.selectedIndex].value == 0)
   { 
	  displayCallBackExample(f);
      t.display = "block";
	  tu.display = "none";
   }
   else
   {
      if(f != "")
      {
         displayCallBackExample(f);
         t.display = "none";
		 tu.display = "block";
      }
   }
}

function resetTargetURLs()
{
	var exec_url_opt = document.getElementById("exec_url_opt");
	exec_url_opt.style.display = "none";
	var tu = document.getElementById("target_urls_elm");
	tu.innerHTML = "";
}

function bringBackTargetURLs()
{
	var exec_url_opt = document.getElementById("exec_url_opt");
	exec_url_opt.style.display = "block";
}

function addNewTargetURL()
{
	var tu = document.getElementById("target_urls_elm");
	if(tu.childNodes.length >= 1)
	{
		document.getElementById("plus"+(tu.childNodes.length-1)).style.display="none";
	}	
	
	var newLi = document.createElement("li");
	newLi.id = "ru" + tu.childNodes.length;
	newLi.style.padding = "5px";
	var elem = '<input onkeydown="return addTargetURLByKeyBoard(event)" type="text" name="target_url[]" class="cmp" value="http://" size="130"> <img src="/img/close.png" onclick=removeTargetURL('+tu.childNodes.length+') style="cursor:pointer">&nbsp;<img src="/img/add.png" id="plus'+tu.childNodes.length+'" onclick=addNewTargetURL();this.style.display="none" style="cursor:pointer">';
	newLi.innerHTML = elem;
	tu.appendChild(newLi);
	newLi.firstChild.focus();
}

function addTargetURLByKeyBoard( e )
{
	var numCharCode;
	var elTarget;
	var strType;
	
	if (!e) var e = window.event;
	
	if (e.keyCode) numCharCode = e.keyCode;
	else if (e.which) numCharCode = e.which;
   
	if ( numCharCode == 13 )
   {
		addNewTargetURL();
		return false;
   }	
}


function removeTargetURL(ei)
{
	var tu = document.getElementById("target_urls_elm");
	tu.removeChild(tu.childNodes[ei]);
	if(ei > 1)
	{
		document.getElementById("plus"+(ei-1)).style.display="";
	}	
}

var FORMFUN = 
{
    orderCombo:function(e){
    op = document.getElementById(e).options
    trocou = 1;
    for(i=0;i<op.length-1;i++){
    for(j=i+1;j<op.length;j++){
    if(op[i].text.toLowerCase() > op[j].text.toLowerCase()){
    t = op[i].text
    op[i].text = op[j].text
    op[j].text = t
    t = op[i].value
    op[i].value = op[j].value
    op[j].value = t

    t = op[i].style.fontWeight
    op[i].style.fontWeight = op[j].style.fontWeight
    op[j].style.fontWeight = t
    t = op[i].style.color
    op[i].style.color = op[j].style.color
    op[j].style.color = t
    t = op[i].style.backgroundColor
    op[i].style.backgroundColor = op[j].style.backgroundColor
    op[j].style.backgroundColor = t        
    }
    }
    }
   },
   moveAllOptions:function(from,to)
   {
       ops = document.getElementById(from).options
       x = document.getElementById(from).options.length;
       for(i=0; i<x; i++)
       {
       o = new Option();
       o.text = ops[i].text;
       o.value = ops[i].value;
   
       o.style.fontWeight = ops[i].style.fontWeight;
       o.style.color = ops[i].style.color;
       o.style.backgroundColor = ops[i].style.backgroundColor;
   
       o.id = ops[i].id;
       try {
       document.getElementById(to).add(o,null);
       }
       catch (e) {
       document.getElementById(to).add(o,document.getElementById(to).length)
       }
       }
       for(i=0; i<x; i++)
       {
       document.getElementById(from).remove(ops[i]);
       }
       FORMFUN.orderCombo(to)
       FORMFUN.orderCombo(from)
   },
   moveOption:function(from,to){
       while(document.getElementById(from).selectedIndex != -1){
       op = document.getElementById(from).options[document.getElementById(from).selectedIndex];
       o = new Option();
       o.text = op.text;
       o.value = op.value;
   
       o.style.fontWeight = op.style.fontWeight;
       o.style.color = op.style.color;
       o.style.backgroundColor = op.style.backgroundColor;
   
       o.id = op.id;
       try {
       document.getElementById(to).add(o,null);
       }
       catch (e) {
       document.getElementById(to).add(o,document.getElementById(to).length)
       }
       document.getElementById(from).remove(document.getElementById(from).selectedIndex);
       }
       FORMFUN.orderCombo(to)
       FORMFUN.orderCombo(from)
       FORMFUN.checkAllList(to)
       FORMFUN.checkAllList(from)
   },
   checkAllList:function(id)
       {
       var chkBoxes = document.getElementById(id).options
       for(i=0; i<chkBoxes.length; i++)
       {
       chkBoxes[i].selected = true;
       } 
   }
}

var PRE_CODES = 
{
   codes:
   {
		"code_0":'',
		"code_1":'<script>var funnel_url = "{FUNNEL}";var conversion_url = "{CONVERSION}";function askFeedback(){k_push.popup_init();k_push.openPopup();}if(location.href.indexOf(funnel_url) == -1 && location.href.indexOf(conversion_url) == -1){if(window.addEventListener){window.addEventListener("load",askFeedback,false);}else{window.attachEvent("onload",askFeedback);}}</script>',
		"code_2":'<script>var btb_redirect="{URL}";location.href=btb_redirect;</script>',
		"code_3":'<link rel="stylesheet" type="text/css" href="http://btbuckets-static.appspot.com/static/shadowbox/shadowbox.css"><script type="text/javascript" src="http://btbuckets-static.appspot.com/static/shadowbox/shadowbox.js"></script><script type="text/javascript">Shadowbox.init({skipSetup:true,players:[\'html\']});function btbshadowbox(){Shadowbox.open({content: "<div style=\'color:#FFFFFF;padding:15px;\'>{HTML_CODE}</div>", player:\'html\',title:\'{TITLE}\',height:{H},width:{W}});} if(window.addEventListener) {window.addEventListener(\'load\', btbshadowbox,false);} else { window.attachEvent(\'onload\', btbshadowbox);}</script>',
		"code_4":'<script src=\'http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js\' type="text/javascript"></script><script>$(document).ready(function(){$(\'#{DIV_NAME}\').append(\'{HTML_CODE}\');});</script>',
		"code_5":'<script src=\'http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js\' type="text/javascript"></script><script>$(document).ready(function(){$(\'#{DIV_NAME}\').prepend(\'{HTML_CODE}\');});</script>',
		"code_6":'<link rel=\'stylesheet\' type=\'text/css\' href=\'http://btbuckets-static.appspot.com/static/shadowbox/shadowbox.css\'><script type=\'text/javascript\' src=\'http://btbuckets-static.appspot.com/static/shadowbox/shadowbox.js\'></script><script type=\'text/javascript\'>Shadowbox.init({skipSetup:true,players:[\'html\']});function btbshadowboxVideo(){Shadowbox.open({content: \'{HTML_CODE}\', player:\'html\',title:\'{TITLE}\',height:{H},width:{W}});} if(window.addEventListener) {window.addEventListener(\'load\', btbshadowboxVideo,false);} else { window.attachEvent(\'onload\', btbshadowboxVideo);}</script>',
		"code_7":'{RSS_POST}',
		"code_8":'{TWITTER_POST}',
		"code_9":'<script>(new Image).src="{URL}";</script>'
   },
   wizards:
   {"code_0":function(e){bringBackTargetURLs();},
	   "code_1":function(e)
      {
         var furl = prompt("STEP 1:\nPlease insert your shopping cart URL pattern:","http://");
         if(furl == null)
         {
         	return;
         }         
         var fcv = prompt("STEP 2:\nPlease insert your conversion URL pattern:","http://");
         if(fcv == null)
         {
         	return;
         }           
         if(furl != null && fcv != null)
         {
            e.value = PRE_CODES.codes.code_1.replace("{FUNNEL}",furl).replace("{CONVERSION}",fcv);
            e.form.target_type_id.value = "1";
            bringBackTargetURLs();
         }
      },
      "code_2":function(e)
      {
         var furl = prompt("STEP 1:\nPlease insert the URL where the user will be redirected:","http://");
         if(furl != null)
         {
            e.value = PRE_CODES.codes.code_2.replace("{URL}",furl);
            e.form.target_type_id.value = "1";
            bringBackTargetURLs();
         }
      },
      "code_3":function(e)
      {
            var w = prompt("STEP 1:\nPlease input box width:","300");
            if(w == null)
            {
            	return;
            }
            var h = prompt("STEP 2:\nPlease input box height:","300");
            if(h == null)
            {
            	return;
            }    
            var t = prompt("STEP 3:\nPlease input box title:","Title here");
            if(t == null)
            {
            	return;
            }   
            var hc = prompt("STEP 4:\nPlease input box HTML content:","");
            if(hc == null)
            {
            	return;
            }            
			
         if(w != null && h != null && t != null && hc != null)
         {
            e.value = PRE_CODES.codes.code_3.replace("{HTML_CODE}",hc.replace(/'/g,"\\'")).replace("{TITLE}",t.replace(/'/g,"\\'").replace(/"/g,'\\\\"')).replace("{W}",w).replace("{H}",h);
            e.form.target_type_id.value = "1";
            bringBackTargetURLs();
         }
      },
      "code_4":function(e)
      {
         var d = prompt("STEP 1:\nPlease input DIV id","");
         if(d == null)
         {
         	return;
         }            
		 var hc = prompt("STEP 1:\nPlease input box HTML content:","");
         if(hc == null)
         {
         	return;
         }   		 
			
         if(hc != null && d != null)
         {
            e.value = PRE_CODES.codes.code_4.replace("{DIV_NAME}",d).replace("{HTML_CODE}",hc.replace(/'/g,"\\'")).replace(/"/g,'\\\\"');
            e.form.target_type_id.value = "1";
            bringBackTargetURLs();
         }
      },
      "code_5":function(e)
      {
         var d = prompt("STEP 1:\nPlease input DIV id","");
         if(d == null)
         {
         	return;
         }            
		 var hc = prompt("STEP 1:\nPlease input text or HTML code to prepend:","");
         if(hc == null)
         {
         	return;
         }   			
         if(hc != null && d != null)
         {
            e.value = PRE_CODES.codes.code_5.replace("{DIV_NAME}",d).replace("{HTML_CODE}",hc.replace(/'/g,"\\'").replace(/"/g,'\\\\"'));
            e.form.target_type_id.value = "1";
            bringBackTargetURLs();
         }
      },		
      "code_6":function(e)
      {
         var w = prompt("STEP 1:\nPlease input box width:","300");
         if(w == null)
         {
         	return;
         }            
		 var h = prompt("STEP 2:\nPlease input box height:","300");
         if(h == null)
         {
         	return;
         }   		 
		var t = prompt("STEP 3:\nPlease input box title:","Title here");
	    if(t == null)
	    {
	       return;
	    }   			
			var hc = prompt("STEP 4:\nPlease input the video EMBED code:","");	
	         if(hc == null)
	         {
	         	return;
	         }   
         if(w != null && h != null && t != null && hc != null)
         {
            e.value = PRE_CODES.codes.code_6.replace("{HTML_CODE}",hc.replace(/'/g,"\\'").replace(/"/g,'\\\\"')).replace("{TITLE}",t.replace(/'/g,"\\'")).replace("{W}",w).replace("{H}",h);
            e.form.target_type_id.value = "1";
            bringBackTargetURLs();
         }
      },
      "code_7":function(e)
      {
         var w = prompt("STEP 1:\nPlease input the rss/feed content:","Text");
         if(w != null)
         {
            e.value = PRE_CODES.codes.code_7.replace("{RSS_POST}",w.replace(/'/g,"\\'").replace(/"/g,'\\\\"'));
            e.form.target_type_id.value = "3";
            e.form.target_name.value = e.form.target_name.value.replace(/(Twitter post\s|RSS\s)/g,"");
            e.form.target_name.value = "RSS " + e.form.target_name.value;
            suggestCallbackFriendlyName(e.form.target_name);
            resetTargetURLs();
         }
      },
      "code_8":function(e,v)
      {
    	 var defaultText = "Text";
    	 if(v)
    	 {
    		defaultText = v;
    	 }
         var w = prompt("STEP 1:\nPlease input twitter post content (max 140 chars):",defaultText);
         if(w != null)
         {
        	if(w.length <= 140)
        	{
                e.value = PRE_CODES.codes.code_8.replace("{TWITTER_POST}",w); 
                e.form.target_type_id.value = "2";
                e.form.target_name.value = e.form.target_name.value.replace(/(Twitter post\s|RSS\s)/g,"");
                e.form.target_name.value = "Twitter post " + e.form.target_name.value ;
                suggestCallbackFriendlyName(e.form.target_name);
                resetTargetURLs();
        	}
        	else
        	{
        		alert("Your post have more than 140 characters, please review it.");
        		PRE_CODES.wizards["code_8"](e.form.target_code,w);
        	}
         }
      },
      "code_9":function(e)
      {
         var furl = prompt("INTEGRATION SETTINGS:\nPlease insert Predicta Maestro Remarketing integration URL:","http://");
         if(furl != null)
         {
            e.value = PRE_CODES.codes.code_9.replace("{URL}",furl);
            e.form.target_type_id.value = "1";
            resetTargetURLs();
         }
      }      
   }   
}

function setPredefinedCode(e)
{
   var codeID = e.options[e.selectedIndex].value;
   if(codeID != "")
   {
      PRE_CODES.wizards["code_"+codeID](e.form.target_code);
   }
}

function displayPassword(f,displayIt)
{
   var passFieldType = (displayIt)?"text":"password";
   f.user_password.type = passFieldType;
   f.user_password_conf.type = passFieldType;
}

