var ispro = false;
var adblock = true;
var istouch = false;

var operation = "";

var key = "86bb5c";

var pro_calcs = {};
var pro_id = "";

var img_server = "/img/";

Prototype.Browser.Chrome = !!navigator.userAgent.match('Chrome');


var ProRevision = Class.create();
ProRevision.prototype = {
  initialize: function(revision, input, output) {
    this.revision = revision;
    this.input = input;
    this.output = output;
    this.date = new Date();
  }
};

var ProCalc = Class.create();
ProCalc.prototype = {
  initialize: function(id) {
    this.id = id;
    this.revision = 0;
    this.revisions = new Array();
    this.tags = "";
    this.title = "Untitled";
    this.date = new Date();
  },
  addRevision: function(revision) {
    this.revision = revision.revision;
    this.revisions[revision.revision]=( revision );
  }
};




function getInputCaretPosition () 
{
	var input = $("input");
	var pos = input.length;
	
	if (document.selection) 
	{			    
	    try{ if (!istouch) input.focus (); } catch (e){}		    
		 
		var Sel = document.selection.createRange ();	
		Sel.moveStart ('character', -input.value.length);	
		pos = Sel.text.length;	
	}
	else if (input.selectionStart || input.selectionStart == '0')
		pos = input.selectionStart;
	
	
	    if (Prototype.Browser.IE || Prototype.Browser.Opera)
	      pos-=getInputSelectionLength();
	
	 return (pos);
}
	    
function getInputSelectionLength ()
{	
	var input = $("input");
	var pos = input.length;
	
	if (document.selection) 
	{			    
	    try{ if (!istouch) input.focus (); } catch (e){}	    
		 
		var Sel = document.selection.createRange ();	
		pos = Sel.text.length;
	}
	else if (input.selectionEnd  || input.selectionEnd  == '0')
		pos = input.selectionEnd-input.selectionStart ;
	
	 return (pos);
}
    
function setInputCaretPosition( pos)
{
	var input = $("input");
	if(input.setSelectionRange)
	{
		try{ if (!istouch) input.focus (); } catch (e){}
		input.setSelectionRange(pos,pos);
	}
	else if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

function setLoadingImg(show)
{
 $("input").setStyle( {backgroundPosition:(show?"top right":"111% 110%")} );
}


 

function smartinsert( input, parameters )
{
      
      var sellen;
      if ((sellen=getInputSelectionLength())>0 )
      {
      var inp = $("input").value;
      
      var selpos = getInputCaretPosition();
      
      $("input").value=( inp.substring(0, selpos )+input+"("+  inp.substr(selpos, sellen )+ (parameters==1?"":", ") +")"+inp.substring( selpos+sellen )  );
      if (parameters==1)
       setInputCaretPosition( input.length+selpos+sellen+2 );
      else 
       setInputCaretPosition( input.length+selpos+sellen+3 );      	         
         
      } else
      {      
      
      var regex = /^[-]?[0-9.abcdef]+$/; 
	  if (!regex.test($("input").value))
      {
       if (parameters==1)
       ins( input+"(" );
       else
       ins( input+"(" );
      } else
      {
       if (parameters==1)
       $("input").value=( input+"("+$("input").value+")" );
       else
       $("input").value=( input+"("+$("input").value+", " );
      } 
      
      }
      
}


var historyscroll_en = true;
var historyscroll_en_timeout = null;

function historyScrollLock()
{
      try{ 
        historyscroll_en=false;
        if (historyscroll_en_timeout!=null)
         window.clearTimeout( historyscroll_en_timeout );
        historyscroll_en_timeout = window.setTimeout( function(){ 
          historyscroll_en=true; 
          historyscroll_en_timeout=null; 
        }, 500 );
       } catch (e)
       {
       } 
}   
    

var historyScrollIndex = 0;
function historyScroll( down )
{  
      if (historyscroll_en==false)
       return;
    
      var index = historyScrollIndex+(down?1:-1);
      if (index<1) index = 1;
      if (index>$("history").length-1 ) index = $("history").length-1;
      historyScrollIndex = index;
      
      $("input").value = $("history").options[ index ].value;
}

function historyMouseUp(evt, select)
{
   
    try{
     
     if ((evt.originalTarget+"")=='[object HTMLOptionElement]') 
      historyChange(select);
    } catch (e)
    {
    }
       
}

function historyChange(select)
{
 
 if (select.selectedIndex>0)
 {
  if (ispro)
  {
    if (select.selectedIndex>0)
    {
     var obj = select.options[select.selectedIndex];
     if (obj.className=="pro")
     {
       selectcalc( obj.value );
     } else
      ins( obj.value+"\n" );
    }  
  } else
  {
   if (select.selectedIndex>0)
   {
     var obj = select.options[select.selectedIndex];
     if (obj.className=="pro")
     {
       showpro();
       selectcalc( obj.value );
     } else
      $('input').value=select.options[select.selectedIndex].value;
   } 
  } 
 }
}

function historyMouseUp(evt, select)
{
   if (Prototype.Browser.IE)
    return;
    
    try{
     
     if ((evt.originalTarget+"")=='[object HTMLOptionElement]') 
      historyChange(select);
    } catch (e)
    {
    }
         
}

 function inputKeyChange()
 {
   var input = $("input").value;
   var parans = 0;
   
   var len = input.length;
   for (var i=0;i<len;i++)
   {
     var ch = input[i];
     if (ch=='(') parans++;
     if (ch==')') parans--;
   }
   
   if (request==null)
   $("input").setStyle( { backgroundImage:(parans>0?"url(/img/paranr.gif)":"url(/img/loading.gif)"), backgroundPosition:(parans>0?"top right":"110% 110%")} );
  
 }

function paranl()
{
    ins( "(" );
    operation="(";
    inputKeyChange();
}
function paranr()
{
    ins( ")" );
    inputKeyChange();
}


function cmd(name)
{
    if (name=="exp")
    smartinsert( "exp",1 );
    else
    if (name=="logyx")
    {
      smartinsert( "log",2 );
      return false;
    }else
    if (name=="sqrty")
    {
      smartinsert("sqrt",2);
      return false;
    } else
    if (name=="x^2" || name=="x^3")
    {
      var sellen;
      if ((sellen=getInputSelectionLength())>0)
      {
        
      	var inp = $("input").value;
      	var selpos = getInputCaretPosition();
      	$("input").value=( inp.substring(0, selpos )+"("+  inp.substr(selpos, sellen )+ ")"+name.substr(1) +inp.substring( selpos+sellen )  );
      	setInputCaretPosition( selpos+sellen+4 );
            	    
      } else
      ins((name=="x^2")?"^2":"^3");
    }
    else
    if (name=="1/x")
    smartinsert("1/",1);
    else    
    if (name=="10^x")
    smartinsert("10^",1);
    else
    if (name=="faculty")
    ins( "!" );
    else    		
    smartinsert(name,1 );
    
    checkForInputChanges();
    checkForInputChanges();
    
    return false;
} 	




function clearall()
{
  var input = $("input");
  
  if (input.value.length==0)
  {
	  showcmd(1);
	  $("display").setStyle({minHeight:("20px")});
  }
 
  $("result").hide();
  $("plot").hide();
  
  var value = "";
  var len = 0;
 
  if(Prototype.Browser.WebKit || Prototype.Browser.Gecko || Prototype.Browser.IE)
    {
      var input = $("input").value;
      
      len = getInputSelectionLength();
      var pos = getInputCaretPosition ();
     
      if (len>0)
         value = input.substring(0, pos)+input.substring(pos+len);
      else
      {   
        if (ispro)
        {
         value = "";
         $("output").value = "";
        } else
         value = "";
      }
     
    } else
    {
     if (ispro)
     {
      value = "";
      $("output").value = "";
     } else 
      value = "";
    }
 
 if (!ispro && len<=0)
 {
  checkforinputchanges_input = value;
  $("result").src="/img/loading.gif";
 }  
  
 $("input").value = value; 
 
 setLoadingImg(false);
 
 if (!istouch)
 $("input").focus();
 
 if (ispro)
   setInputCaretPosition(0);
} 

function setoperation(op)
{
  	ins(op);
  	operation=op;
}

var insertposition = 0;
function ins(s)
{
     if( Prototype.Browser.Gecko || Prototype.Browser.WebKit || Prototype.Browser.Opera || Prototype.Browser.IE )
     {
      var input = $("input").value;
          	  
      var len = getInputSelectionLength();
      var pos = getInputCaretPosition ();
            
      if (len>0)
         input = input.substring(0, pos)+input.substring(pos+len);

      $("input").value=( input.substring(0,pos)+s+input.substring(pos) );
      
      if (s=="\n" && Prototype.Browser.Opera)
       pos++;
      
      setInputCaretPosition( insertposition=pos+s.length );
     } else
       $("input").value=( $("input").value+s );
         	 
     operation="";
     
     checkForInputChanges();
     checkForInputChanges();
     
     return false;
}



Ajax.Request.prototype.doabort = function() {
 this.transport.abort();
 if(Prototype.Browser.Opera || Prototype.Browser.WebKit){ 
   if (Ajax.activeRequestCount>0) Ajax.activeRequestCount--;
 }
}


function sign()
{
	var input = $("input").value;
	for (var i=input.length-1;i>=0;i--)
	{
		var ch = input.substring(i,i+1);
		if ("0123456789e.".indexOf(ch)>=0)
		{    			
		} else if (ch=="-")
		{
			input = input.substring(0,i)+input.substring(i+1);
			break;
		} else
		{
			input = input.substring(0,i+1)+"-"+input.substring(i+1);
			break;
		}
		if (i==0)
		 input = "-"+input;
	}
	$("input").value = input;
}


var calculation = 0;
var request = null;

var currencyconversion=false;

 
function equal_pro()
{
 setLoadingImg(true);
 if (request)
 {
  try{ request.doabort(); } catch (e){}
 }
 
 var parameters = $("form").serialize(true);
 parameters.id = pro_id;
 var display = $("display_pro_"+parameters.id).down(".lines");
 
 if (!display)
 {
  setLoadingImg(false);
  alert("internal error! (no calculation available)"); 
  return;
 }
 
 if (display)
 {
  parameters.x=parseInt($("display_pro_"+parameters.id).getStyle('left'));
  parameters.y=parseInt($("display_pro_"+parameters.id).getStyle('top'));
  parameters.w=parseInt($("display_pro_"+parameters.id).getStyle('width'));
  parameters.h=parseInt($("display_pro_"+parameters.id).getStyle('height'));
  $("display_pro_"+pro_id).show();
 }
  
 
 
 
		    	   
		    	   
 
 
 request = new Ajax.Request("/api/?key="+key,
 {
    method: "post",
    parameters: parameters,
    onSuccess: function (oXHR, oJson) {
       
       if (oXHR.status==503)
       {
         alert("503 Service Unavailable, try again in 5 minutes");
       } else
       if (oXHR.status>0)
       {  
          var json = oXHR.responseText.evalJSON()          
          var results = json["results"];
          var textresults = new Array();
          var lastline = 1;

		  var imgs = display.childElements();
		  
		  setLoadingImg(false);
		  
		  for (var r=0;r<results.length;r++)
          {
            var result = results[r];
            var line = parseInt( result["line"] );
            {
            
              for (var i=lastline+1;i<line;i++)
              {
                textresults.push( "" ); 
              }
              lastline = line;
              
              switch(result["type"])
              { 
                case "result":
                var values = result["values"];
                for (var v=0;v<values.length;v++)
                {
                  var value = values[v];
                  switch (value["type"])
                  {
                    case "plot":
                     if (value["hash"])
                     {
                       var created = null;
                       var result = imgs.length>0?imgs.shift():(created=Builder.node("img",{"alt":""}));
                       result.className = "plot";
                       result.src = "/img/?plotid="+value["hash"];
                       if (created)
                       {
                        display.appendChild( created );
                        if (Prototype.Browser.Opera)
                         display.setStyle({left:parameters.x+"px"});
                       }
                     }
                    break;
                    case "image":
                    if (value["hash"])
                     {
                       var created = null;
                       var result = imgs.length>0?imgs.shift():(created=Builder.node("img",{"alt":""}));
                       result.className = "image";
                       
                       
                       if ($("style") && $("style").checked)
						 {
                    	   
						   var url = img_server + "?texid="+value["hash"]+"&png";
						   if ($('col_func'))
						    url+="&f="+rgb2hex($("col_func").getStyle("color"));
						   if ($('col_ident'))
						    url+="&i="+rgb2hex($("col_ident").getStyle("color"));
						   if ($('col_unittype'))
						    url+="&u="+rgb2hex($("col_unittype").getStyle("color"));
						   if ($('col_text'))
						    url+="&t="+rgb2hex($("col_text").getStyle("color"));
						
						  result.src = url;
						 } else                       
                           result.src = img_server+"?texid="+value["hash"];
                           
                       if (created)
                       {
                        display.appendChild( created );
                        if (Prototype.Browser.Opera)
                         display.setStyle({left:parameters.x+"px"});
                       }
                     }
                    break;
                    case "value":
                     if (value["string"])
                     {
                       textresults.push( value["string"] ); 
                     }
                    break;
                    case "error":
                     if (value["desc"])
                     {
                       alert( "line "+line+": "+value["desc"] );
                       //textresults.push( value["desc"] ); 
                     }
                    break;
                  }
                }                
                break;
                case "error":
                 
                 if (result["desc"])
                   alert( "line "+line+": "+result["desc"] );
                 if (result["input"])
                   textresults.push( result["input"] );  
                break;
              }
              
            }
          }
          
          var currency = false;
          if (json["currency"] && json["currency"]=="true")
            currency = true;
            
          if (currency!=currencyconversion)
          {            
            if (currency)
             new Effect.Appear($("currency_notify"), { afterFinishInternal: function(effect) {
          		new Effect.Fade($("currency_notify"),{ delay: 6.6 });
      		 }});
            
            currencyconversion = currency;
          }  
          
          
          for (var i=imgs.length-1;i>=0;i--)
           imgs[i].remove();
          
          var input = "";
          for (var i=0;i<textresults.length;i++)
          {
             input+=textresults[i].replace(/\n/g,"")+(i+1<textresults.length?"\n":"");
          }
          $("output").value = input;
         
         
         if (pro_calcs[pro_id] && json["revision"])
         {
           
           var procalc = pro_calcs[pro_id];
           procalc.addRevision( new ProRevision( parseInt(json["revision"]), $("input").value, $("output").value ) );
           procalc.tags = json["tags"]?json["tags"]:"";
           procalc.title = $("share_title").value;
           
           selectcalc( pro_id );
           
           
           window.setTimeout( function() 
           {
	          var history=$("history_calulations");
	          try 
	          {
	           var option=new Option( procalc.title.length>50?procalc.title.substring(0,50)+"..":procalc.title+" ("+pro_id+")", pro_id );
	           option.className="pro";
	           if (procalc.revision==1)
	           {
	            if (history.length>1)
	      		 history.add( option, history.options[1]);
	      		else
	      		 history.add( option, null );
	            
	            history.selectedIndex = 1;
	           } else
	           {
			      for (var i=history.options.length-1;i>=0;i--)
				    if (history.options[i].value==pro_id)
				    {
				      history.options[i]=option; history.selectedIndex = i;
				      break;
				    }
	           }
	          } catch(e)
	          {
	             
	          } 
	       }, 100 );          
         }
         
         try { if (!istouch) $("input").focus();}catch(e){}
         request = null;
       }
    },
    onFailure: function (oXHR, oJson) {
    
       if (oXHR.status==503)
       {
         alert("503 Service Unavailable, try again in 5 minutes");
       } else
       {
         alert("Request was unsuccessful.");
       }
    
       setLoadingImg(false);
       request = null;        
    }
 } );

  
}



function rgb2hex(color) {
    if (color.substr(0, 1) === '#')
      return color.substring(1);
   try{   
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
    
    var r = parseInt(digits[2]);
    var g = parseInt(digits[3]);
    var b = parseInt(digits[4]);
    
    var tmp = (b | (g << 8) | (r << 16)).toString(16);
    while (tmp.length<6)
     tmp="0"+tmp;
    return tmp;
   } catch(e)
   {
   }
   return ""; 
};

 

var equals = 0;  



function doundo()
{

  if (getInputSelectionLength()>1)
  {
   clearall();
   return;
  } 
  
  var pos = getInputCaretPosition();
  var input = $("input").value;
  
  if (pos<0) return;
  if (pos>input.length) return;
  
  if (pos==0 && input.length>0)
   pos=1;
  
  input = (pos>0?input.substring(0, pos-1):"")+input.substring(pos);

  $("input").value=input;  
  setInputCaretPosition(pos>0?pos-1:0);
  
}

var checkforinputchanges_input = "";

var checkforinputchanges_lasttime = new Date();
var checkforinputchanges_interval = 0.1; // 0.1sec
var checkforinputchanges_count = 0;

var checkforinputchanges_extrawait = 0.0;
var checkforinputchanges_input_last = "_"; 

var checkForInputChanges_lastinterval = new Date(2010,0,1);


var lastheight = 0;
function checkForInputChanges()
{
	 
  if (ispro)
   return;
   
  if (request)
   return; 
   
  
	  var height = parseInt($("display").down().getHeight());
	  if (height<20)
		  height = 20;
		  
	  if (height>parseInt($("display").getStyle("min-height")))
	   $("display").setStyle({minHeight:(height+"px")});
 
  
  var now = new Date();
  var timediff=(now.getTime()-checkforinputchanges_lasttime.getTime())/1000.0;
  if (timediff<checkforinputchanges_interval)
   return;
  
  // window.status = ""+(checkforinputchanges_interval )+"s";
  
  
  var input = $("input").value;
  
  if (input==checkforinputchanges_input)
   return;
  
  
  if (input!=checkforinputchanges_input_last)
  {
	  checkforinputchanges_input_last = input;
	  return;
  }
  checkforinputchanges_input_last = input;
   
  
//  if ($("style") && $("style").checked)
  // return; 
   
  if ($("inputpreview") && !$("inputpreview").checked)
   return; 
  
  
   
   
  var result=$("result");
  
  
  if ($("style") && $("style").checked)
  {
    var url = img_server+"?preview="+encodeURIComponent(input)+"&key="+key+($("trigorad").checked?"&rad":"");
    if ($('col_func'))
     url+="&f="+rgb2hex($("col_func").getStyle("color"));
    if ($('col_ident'))
     url+="&i="+rgb2hex($("col_ident").getStyle("color"));
    if ($('col_unittype'))
     url+="&u="+rgb2hex($("col_unittype").getStyle("color"));
    if ($('col_text'))
     url+="&t="+rgb2hex($("col_text").getStyle("color"));

   result.src = url;
  } else  
   result.src = img_server+"?preview="+encodeURIComponent(input)+"&key="+key+($("trigorad").checked?"&rad":""); 
 
  if (Prototype.Browser.Chrome || Prototype.Browser.WebKit)
  result.setStyle({width:"auto",height:"auto"});
 
  Effect.Appear( "result" );  
    
  checkforinputchanges_input = input;
  checkforinputchanges_count++;
  
  
  if ((now.getTime()-checkForInputChanges_lastinterval.getTime())/1000.0>60.0)
  {
    var startTime=new Date();
    var endTime=new Date();
    
    checkForInputChanges_lastinterval = new Date();
    	
    new Ajax.Request(img_server ,
    {
     method: "get",
     asynchronous: true,
     parameters: {preview:encodeURIComponent("1+2+3"),interval:checkforinputchanges_interval,key:key},
     onSuccess: function (oXHR, oJson) {
       if (oXHR.status>0)
       {    	   
    	   
         endTime=new Date();
       	 var time= (endTime.getTime()-startTime.getTime())/1000.0;
       	 if (time>0.5)
       		 time = 0.5;
       	 if (time<0.1)
      		 time = 0.1;
       //	 if (time<checkforinputchanges_interval)
       	 {
       	  checkforinputchanges_interval=time;
       	//   window.status = "new interval time: "+ time+"ms";
       	 } 
       }
      }
    });
 
  
  }
  
  checkforinputchanges_lasttime = new Date();
}


function amand()
{
   var html = document.getElementsByTagName('HTML')[0];
   if (!html) return;
   html.style.backgroundImage="url(/img/amanda.jpg)";
   html.style.backgroundColor="black";
   html.style.backgroundRepeat="no-repeat";
   html.style.backgroundPosition="right top";
   
   $("logo").hide();
   return "";
}

function equal()
{
 if (ispro)
 {
  equal_pro();
  return;
 }
 
  if ($("input").value.indexOf("steroids")>0)
  {
   window.open("http://asteroids.web2.0calc.com/",'win','left=250,top=40,width=502,height=520,toolbar=0,resizable=0');
   return;
  }
  if ($("input").value.indexOf("manda")>0)
  {
   amand();
   return;
  } 
 
 if ($("feedback_btn") && equals%6==5)
 {
  new Effect.Highlight($("feedback_btn"), { endcolor : '#515F6D', startcolor: '#9AB4CE' });
 }
 equals++;
 
 var regex = /^[a-zA-Z][a-zA-Z0-9]{9}$/;
 if (regex.test($("input").value))
 {
  showpro();
  selectcalc( $("input").value );
  equal_pro();
  return;
 }
  
 setLoadingImg(true);
 
  try{
  if (historyscroll_en_timeout!=null)
        window.clearTimeout( historyscroll_en_timeout );
       historyscroll_en=true; 
  } catch (e)
  {
  } 

 if (request)
 {
  try{ request.doabort(); } catch (e){}
 }
 
 var parameters = $("form").serialize("true");
 
 parameters.texid = "";
 parameters.adblock = adblock;
 
  for (var i=0;i<32;i++)
   parameters.texid+="0123456789abcdeff".substr( Math.floor( Math.random() * 200000000) % 16 ,1 );

 var result=$("result");
 var lastvalidresultsrc=result.src;
 
 if ($("style") && $("style").checked)
 {
   var url = img_server+"?texid="+parameters.texid+"&png";
   if ($('col_func'))
    url+="&f="+rgb2hex($("col_func").getStyle("color"));
   if ($('col_ident'))
    url+="&i="+rgb2hex($("col_ident").getStyle("color"));
   if ($('col_unittype'))
    url+="&u="+rgb2hex($("col_unittype").getStyle("color"));
   if ($('col_text'))
    url+="&t="+rgb2hex($("col_text").getStyle("color"));

  result.src = url;
 }
 else
 result.src = img_server+"?texid="+parameters.texid;
 
  
 if (Prototype.Browser.Chrome || Prototype.Browser.WebKit)
  result.setStyle({width:"auto",height:"auto"});
 
 request = new Ajax.Request("/api/?key="+key,
 {
    method: "post",
    parameters: parameters,
    onSuccess: function (oXHR, oJson) {
    
       
       if (oXHR.status>0)
       {
         
         var showplot = false;
         
          
        
          
          var json = oXHR.responseText.evalJSON();
          
           setLoadingImg(false);
          
          var results = json["results"];
          var textresults = new Array();
          for (var r=0;r<results.length;r++)
          {
            var result = results[r];
            if (result["line"]=="1")
            {
              switch(result["type"])
              { 
                case "result":
                var values = result["values"];
                
                var historyinput = "";
                if (result["input"])
                 historyinput = result["input"];
                
                for (var v=0;v<values.length;v++)
                {
                  var value = values[v];
                  switch (value["type"])
                  {
                    case "image":
                    	img_server = value["server"];
                    break;
                    case "plot":
                     if (value["hash"])
                     {
                       $("plot").src = img_server+"?plotid="+value["hash"]+(($("style") && $("style").checked)?"&black":"");
                       $("plot").onclick=function(){
                         $("plot").src=$("plot").src+"&wide"+(($("style") && $("style").checked)?"&black":"");
                       };
                       showplot = true;
                     }
                    break;
                    case "value":
                     if (value["string"])
                     {
                       textresults.push( value["string"] ); 
                     }
                    break;
                    case "error":
                     if (value["desc"])
                     {
                       alert( value["desc"] );
                       historyinput = null;
                       //textresults.push( value["desc"] ); 
                     }
                    break;
                  }
                }       
                
                
                historyScrollIndex = 0;
                window.setTimeout(function()
                {
                try
                {
                 var history=$("history");
                 var option = new Option((historyinput.length>45)?(historyinput.substr(0,45)+"..."):historyinput, historyinput);
	      		 if (history.length>1)
	      		  history.add( option, history.options[1]);
	      		 else
	      		  history.options[history.length] = option;
	      		 history.selectedIndex = 1;
	      		} catch(e)
	      		{
	      		}
	      		}, 250); 
	      		
	      		$("result").title = historyinput;
	      		try{
	      		 $("result").onclick = function()
	      		 {
			        $( "input" ).value = historyinput;
			     };
			    } catch (oce)
			    {
			    } 
                         
                break;
                case "error":
                 result.src=lastvalidresultsrc;
                 if (result["desc"])
                   alert( result["desc"] );
                 if (result["input"])
                   textresults.push( result["input"] );  
                break;
              }
              
            }
          }
          
          var currency = false;
          if (json["currency"] && json["currency"]=="true")
            currency = true;
            
          if (currency!=currencyconversion)
          {            
            if (currency)
             new Effect.Appear($("currency_notify"), { afterFinishInternal: function(effect) {
          		new Effect.Fade($("currency_notify"),{ delay: 6.6 });
      		 }});
            
            currencyconversion = currency;
          }  
          
          var input = "";
          for (var i=0;i<textresults.length;i++)
          {
             input+=textresults[i]+(i+1<textresults.length?"; ":"");
          }
          if (textresults.length>0)
            $("input").value = input.replace(/\n/g,"");
          
         
         
         if (showplot)
          Effect.Appear( "plot" );
         else
          $("plot").hide();
         
         Effect.Appear( "result" );
         
         checkforinputchanges_input = $('input').value;
         request = null;
       }
    },
    onFailure: function (oXHR, oJson) {
    
       if (oXHR.status==503)
       {
         alert("503 Service Unavailable, try again in 5 minutes");
       } else
       {
         alert("Request was unsuccessful.");
       }
       result.src=lastvalidresultsrc;
       setLoadingImg(false);
       
       checkforinputchanges_input = $('input').value;
       request = null;        
    }
 } );
 
 
 

 
 if (!istouch)
 $("input").focus();
}

function cmddiff()
{
 var input = $("input").value;
 if (input.length==0) 
 {
  $("input").value=('diff( 2*2x, x )');
  equal();
 } 
 else 
 { 
  if (ispro)
   ins("diff(");
  else 
  if (input.indexOf('diff')==-1) 
   $("input").value=( 'diff( '+input+((input.indexOf('x')==-1)?'*x':'')+', x)' );
 }
}

function cmdplot()
{
 var input = $("input").value;
 if (input.length==0) 
 {
  $("input").value=('plot( sin(x), x='+($('trigodeg').checked?'-90..90':'-pi/2..pi/2')+' )');
  equal();
 } 
 else 
 { 
  if (ispro)
   cmd("plot");
  else 
  if (input.indexOf('plot')==-1) 
   $("input").value=( 'plot( '+input+((input.indexOf('x')==-1)?'*x':'')+', x='+($('trigodeg').checked?'-90..90':'-pi/2..pi/2')+' )' );
 }
}

function formatDate(date)
{
 return (date.getFullYear())+"-"+((date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1))+"-"+(date.getDate()<10?"0"+date.getDate():date.getDate())+"&#160;"+(date.getHours()<10?""+date.getHours():date.getHours())+":"+(date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes());
}

var proinitcomplete = false;
var calcinitcomplete = false; 

function showcalc()
{
  ispro = false;
  
  $("link_calc").hide();
  $("link_pro").show();
  
  
  $("share").hide();
  
  $("input").disabled=true;
  $("input").name = "input_pro";
  $("input").id = "input_pro";
  $("input_simple").disabled=false;
  $("input_simple").name = "input";
  $("input_simple").id = "input";
  $("output").id = "output_pro";
  
  $("history_calulations").hide();
  
  $("ops_eq_pro").hide();
  $("ops_eq").show();
  
//  $("display_pro").hide();
  $("display").show();
  
 // $("center").setStyle({position:"inherit"});
  
  

 if (!($("style") && $("style").checked))
  $("html").setStyle({backgroundImage:"url(/img/bge.png)"});
  
  $( "inputfields_slider" ).hide();
  $( "inputfields" ).hide();
  $( "inputfield" ).show();
  
  for (var calc in pro_calcs)
     $("display_pro_"+calc).hide();
  
  calcinitcomplete = true;
}

function formatDate(date)
{
 return (date.getFullYear())+"-"+((date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1))+"-"+(date.getDate()<10?"0"+date.getDate():date.getDate())+" "+(date.getHours()<10?""+date.getHours():date.getHours())+":"+(date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes());
} 

function createselectcalc(id, revision)
{
 return function()
 {
   selectcalc(id, revision);
 };
}

function sortnum(a,b)
{
  return a - b;
}
 
 
function loadcalc(id, revision)
{
  
 var loadrequest = new Ajax.Request("/api/?key="+key,
 {
    method: "post",
    parameters: {loadprocalc:"true",id:id,revision:revision},
    asynchronous : false,
    onSuccess: function (oXHR, oJson) {
       if (oXHR.status>0)
       {
         try{
	         var json = oXHR.responseText.evalJSON();
	         if (json["status"])
	         {
	            
	           switch (json["status"])
	           {
	             case "ok":
	                  
	                  var owner = json["owner"] && (json["owner"]=="true");
	                  var tags = json["tags"]?json["tags"]:"";
	                  var input = "";
	                  	                  
	                  if (json["input"])
	                  {
	                    var lines = json["input"];
	                    for (var i=0;i<lines.length;i++)
	                    {
	                     var line = lines[i];
	                     input+=line.input+((i+1)<lines.length?"\n":"");
	                    }
	                  }
	                  
	                  if (owner)
	                  {
	                  
		                  var title = json["title"]?json["title"]:"";
		                  //var revision = json["revision"]?parseInt(json["revision"]):0;
		                  
		                  var date = new Date();
		                  if (json["time"])
		                  {
		                   var time = json["time"];
		                   date = new Date( parseInt(time.substring(0,4)),parseInt(time.substring(5,7))-1,parseInt(time.substring(8,10)),parseInt(time.substring(11,13)),parseInt(time.substring(14,16)),0  );
		                  }
		                  // var revision = 0;
		                  var procalc = null;
		                  		             
		                  if (revision)
		                  { // loaded revision
		                   procalc = pro_calcs[pro_id];
		                   procalc.revisions[revision] = new ProRevision( revision, input, "" );
		                  } else
		                  {
		                   revision = 0;		                  
						   createcalc(pro_id=id);
						  
						   procalc = pro_calcs[pro_id];
				           procalc.addRevision( new ProRevision( revision, input, "" ) );
				          }
				          procalc.revisions[revision].date=date;
				          procalc.tags = tags;
				          procalc.title = title;
				          
				          if (json["y"])
						  {
						   $("display_pro_"+id).setStyle({left:parseInt(json["x"])+"px",top:parseInt(json["y"])+"px"});
						  }
						  
						  
						   
						  
						  if (revision==0)
						  {
						   selectcalc();
						   equal_pro();
						  } else
						  {
						   selectcalc( pro_id, revision );
						  }
						   
						  
					  } else // !owner
					  {
					     createcalc(id);
					     selectcalc();
					     $("input").value = input;
					     $("output").value = "";					     
					     $("share_tags").value = tags;
					     
					     equal_pro();
					  }
	             
	             break;
	             case "error":
	             if (json["desc"])
	             {
	              alert(json["desc"]);
	             }
	             break;
	           }
	           
	         }   
	      } catch (e)
	      {
	       alert(e);
	      }         
 	   }
 	} ,
    onFailure: function (oXHR, oJson) {
       alert("Request was unsuccessful.");
    }
 });	 
 	  	
}
 
 
function selectcalc(id, revision)
{
  var idchanged = false;
  if ($("display_pro_"+pro_id) && pro_id!=id)
  {
   idchanged = true;
   $("display_pro_"+pro_id).setStyle({opacity:0.5});
  } 

  if (!id)
   id = pro_id;
   
  if ($("display_pro_"+id))
   $("display_pro_"+id).setStyle({opacity:1});
   
   
  var procalc = pro_calcs[id];  
  if (!procalc)
  {
   loadcalc(id, revision);
   return;
  }
  if (!revision)
   revision = procalc.revision;
  
  var date;
  if (procalc.revisions[ revision ])
  {
   $("input").value = procalc.revisions[ revision ].input;
   $("output").value = procalc.revisions[ revision ].output;
   date = procalc.revisions[ revision ].date;
  } else
  {
   date = procalc.date;
   $("input").value="";
   $("output").value="";
   if (revision && revision>0)
   {
    loadcalc(id, revision);
    return;  
   }
  }
  
  $("share_title").value = procalc.title;
  $("share_url_link").href = $("share_url").value = $("share_url").value.substring(0, $("share_url").value.lastIndexOf('/')+1)+id;
  var embedurl = $("share_url").value.substring(0, $("share_url").value.lastIndexOf('/'))+"/embed/"+id;
  $("share_embed_link").href = embedurl;
  $("share_embed").value = "<iframe width=\"200\" height=\"300\" src=\""+embedurl+"\"> </iframe>";
  $("share_revision").update( revision==procalc.revision?revision:(revision+"/"+procalc.revision) );
  $("share_date").update( formatDate(date) );
  $("share_tags").value = procalc.tags;
  
  
   var timeline =$("revision_timeline");
   window.setTimeout(function()
   {
	   var imgs = timeline.childElements();
	   
	   var revs = new Array();
	   for (var i=1;i<=procalc.revision;i++)
	    revs.push( i );
	   for (var i=0;i<revs.length-32;i++)
	   {
	     var index;
	     while ( (index=Math.round(Math.random()*(revs.length-2)+1))>0 && revs[index]==-1 );
	     revs[index]=-1;
	   }	   
	   revs = revs.sort(sortnum);
	   for (var i=0;i<=revs.length;i++)
	   {
	    var rev = revs[i];
	    if (rev>0 && rev<=procalc.revision)
	    {
	     var created=null;
	     var img = imgs.length>0?imgs.shift():(created=Builder.node("img",{src:"/img/rev.png", alt:""}));
	     img.title = "Revision "+rev+" ("+(procalc.revisions[ rev ]?formatDate(procalc.revisions[ rev ].date):"-")+")";
	     img.setStyle({borderBottom:(rev==revision?"1px solid silver":"0px")});
	     img.onclick=createselectcalc(id, rev);
	     if (created)
	      timeline.appendChild(created);
	    } 
	   }
	   
	   for (var i=imgs.length-1;i>=0;i--)
	    imgs[i].remove();
   },100);
  
  
  pro_id = id;
}


function createcalc_helper(id, div, loadingimg)
{
  pro_calcs[pro_id]=new ProCalc(pro_id);
	
  div.id = "display_pro_"+pro_id;
  loadingimg.remove();
  
  var a = Builder.node("a", { "class":"close", "title":"close", "href":"#" }, "x" );
  a.setStyle({"position":"absolute","right":"2px" ,"textDecoration":"none"});
  a.onclick = closecalc(pro_id);
  div.appendChild(a);
  
 
  var linesdiv = Builder.node("div", { "class":"lines" } );
  div.appendChild(linesdiv);
	
  calczindex++;
	
  $("center").setStyle({zIndex:calczindex});  
					 
  var drag = new Draggable( div, { snap: [5, 5], starteffect:null, endeffect:null} );
  drag.onEnd = function(){
	 div.setStyle({opacity:1});
  }; 
  drag.onStart = function(){
	 div.setStyle({opacity:1});
  };  
				 
}

function closecalc(id)
{
  var _id = id;
  return function()
  {
    $("display_pro_"+_id).hide();
    return false;
  }
}

var calczindex = 1;
function createcalc(id)
{ 
 if (pro_id && $("display_pro_"+pro_id)) 
   $("display_pro_"+pro_id).setStyle({opacity:0.5}); 
 
 var div = Builder.node("div", { "class":"display_pro" } );
 div.setStyle({position:"absolute", left:((5+5*calczindex)+"px"), top:((90+5*calczindex)+"px"), zIndex:calczindex});
 
 $("body").appendChild(div);
 
 var loadingimg = Builder.node("img",{src:"/img/loading.gif", alt:""});
 div.appendChild( loadingimg );
  
 if (id)
 {
   pro_id = id;
   createcalc_helper(pro_id, div, loadingimg); 
 } else
 { 
  var createrequest = new Ajax.Request("/api/?key="+key,
  {
    method: "post",
    parameters: {createprocalc:"true"},
    asynchronous : false,
    onSuccess: function (oXHR, oJson) {
       if (oXHR.status>0)
       {
         var json = oXHR.responseText.evalJSON();
         if (json["status"])
         {
           switch(json["status"])
           {
            case "error":
             if (json["desc"])
             {
               alert(json["desc"]);
             }
            break;
            case "ok":
             if ((pro_id=json["id"]))
             {				
 				createcalc_helper(pro_id, div, loadingimg);
             }
            break;
           }
         }
       }
    },
    onFailure: function (oXHR, oJson) {
       alert("Request was unsuccessful.");
       request = null;        
    }
  } );  
 } 
 
  
}

function showpro()
{
  ispro = true;
  
  var input = $("input").value;
  
  if ($("chat"))
   $("chat").hide();
  
  if ($("footer"))
	   $("footer").hide();
  
  $("link_pro").hide();
  $("link_calc").show();
  
  if ($("ifr"))
   $("ifr").hide();
  
  if ($("examples"))
	   $("examples").hide();
  
  $("share").show();
  
  if (!($("style") && $("style").checked))
   $("html").setStyle({backgroundImage:"url(/img/bge.png)"});
   
  $( "inputfield" ).hide();
  
  
  $( "inputfields_slider" ).show();
  $( "inputfields" ).show();

    var inputfields_slider = $('inputfields_slider'),
        inputfields_slider_handle = $('inputfields_slider_handle');
       
  $("history_calulations").show();       
        
  if (!proinitcomplete)
  {
    new Control.Slider(inputfields_slider.down('.handle'), inputfields_slider, {
      range: $R(0, 613),
      sliderValue: 490,
      onSlide: function(value) {
        $("input").setStyle({ width: value + 'px' });        
        $("output").setStyle({ width: ((613-value) + 'px') });
      },
      onChange: function(value) { 
        $("input").setStyle({ width: value + 'px' });        
        $("output").setStyle({ width: (((613)-value) + 'px') });
      }
    });   
  }
  
  
  $("input").disabled=true;
  $("input").name = "input_simple";
  $("input").id = "input_simple";
  
  $("input_pro").name = "input";
  $("input_pro").disabled=false;
  $("input_pro").id = "input";
  $("output_pro").id = "output"; 
  
  
  $("display").hide();
 // $("display_pro").show();
  
  $("ops_eq").hide();
  $("ops_eq_pro").show();
  
  $("center").setStyle({ position: 'absolute', zIndex:"1000", top:"57px",left:(document.viewport.getWidth()/2-678/2)+"px" });
  
  
  if (!proinitcomplete)
  {
   var centerdrag = new Draggable("center", { snap: [5, 5], starteffect:null, endeffect:null});
//   centerdrag.starteffect = new Effect.Opacity('center', { queue: { position: 'end', scope: 'centerscope', limit: 3 }, from: 1.0, to: 0.8, duration: 0.5 });
  }
  
  var iscentervisible = true;
  
 
       
   if (!proinitcomplete)
   { 
    Event.observe(document, 'click', 
     function(e){
        if (!ispro)
         return;
         
        if (!Event.isLeftClick(e))
         return; 
     
        var element = $(Event.element(e));
        while (element.parentNode!=null)
        {
          if(element.className=="links")
          {
            return;
          } else
          if(element.className=="display_pro")
          {
             var id = element.id.substr(12);
             
             if (id!=pro_id)
             {
//               Effect.Queues.get('calcbgscope').each(function(effect) { effect.cancel(); });
//               $("display_pro_"+pro_calcid).fade({ duration: 0.1, from: 1, to: 0.2, queue: { position: 'end', scope: 'calcbgscope', limit: 2 } });
//               $("display_pro_"+id).appear({ duration: 0.1, from: 0.2, to: 1, queue: { position: 'end', scope: 'calcbgscope', limit: 2 } });
             }
             
             selectcalc( id );
             
            return;
          }
          element = element.parentNode;
        }
        var oncenter = false;
        
        if (!iscentervisible)
        {
          Effect.Queues.get('centermovescope').each(function(effect) { effect.cancel(); });
          Effect.Appear( 'center' ,{ duration: 0.1, queue: { position: 'end', scope: 'centerscope', limit: 3 } } );
          //$("center").show();
          iscentervisible=true;
          return;
        }
        
        element = $(Event.element(e));
        while (element.parentNode!=null)
        {
          if (element.id == "center")
          {
           oncenter = true;
           break;
          } else if(element.className=="display_pro")
            return;
            
          element = element.parentNode;
        }
        
        if (!oncenter)
        {
         if (iscentervisible)
         {
          //Effect.Queues.get('centermovescope').each(function(effect) { effect.cancel(); });
          //Effect.Fade( 'center' ,{ duration: 0.1, from: 1, to: 0.01, queue: { position: 'end', scope: 'centerscope', limit: 3 } } );
          $("center").hide();
          
          iscentervisible=false;
         }
        }
     }
    );
   }   
  
  
  $("inputfields_slider_handle").show();
  Effect.Fade( "inputfields_slider_handle", { queue: { scope: 'init_slider_handle_scope' } } );
  
  $("input").value = input;  
  setInputCaretPosition(0);
  
  
  				   
				  
  for (var calc in pro_calcs)
     $("display_pro_"+calc).show();
  
  
  if (!proinitcomplete)
  {
   createcalc();
   selectcalc();
   
   window.setTimeout(function(){Effect.Fade($("expander_pro_span"),{duration:2});},1500);
  }
    
  proinitcomplete = true;  
}


function showshare(share_expanded)
{
   
   if (share_expanded)
   {
    $("share_exp").hide();
    $("share_col").show();
    Effect.SlideDown("revision_panel");
   } else
   {
    $("share_col").hide();
    $("share_exp").show();
    Effect.SlideUp("revision_panel");
   }
    
    
}


function share()
{

 var div = Builder.node("div", { "class":"calc" } );
 var left = document.viewport.getWidth()-240;
 var top = 30;
 div.setStyle({top:(top+"px"),left:(left+"px")});
 new Draggable(div);
 
 var textarea = Builder.node("textarea");
 div.appendChild(textarea);
 textarea.value = $("input").value;
 
 $("body").appendChild( div );

}



function init() {
    var cmds_slider = $('cmds_slider'),
        cmds_slider_handle = $('cmds_slider_handle'),
        cmds = $('cmds'),
        cmdspane = $('cmdspane'),
        inputfields_slider = $('inputfields_slider'),
        inputfields_slider_handle = $('inputfields_slider_handle');
     
  $("input").value="";
  if ($("input_pro")) 
   $("input_pro").value="";
  if ($("output_pro")) 
   $("output_pro").value=""; 
  if ($("history"))
   $("history").selectedIndex=0;   
  if ($("history_calulations"))
   $("history_calulations").selectedIndex=0; 
  
  try{
   $("input").setAttribute( "autocomplete", "off");
  } catch(e)
  {
  }
  
  if ($("style_div"))
  {
   new Draggable($("style_div"));
  }  
        
  var url = window.location.href;
  if (url.lastIndexOf("#pro")+4==url.length)
  {
   ispro = true;
   $("center").hide();
  }
  
  try{
    if ((navigator.userAgent.match(/iPad/i) != null)||(navigator.userAgent.match(/iPhone/i) != null)||(navigator.userAgent.match(/iPod/i) != null)||(navigator.userAgent.match(/droid/i) != null))
	  istouch = true;  
  } catch(e)
  {
  }
     
   if (cmds_slider)
   {  
    Event.observe(cmds_slider,'mouseenter', 
     function(e){
        Effect.Queues.get('sliderscope').each(function(effect) { effect.cancel(); });
        Effect.Appear( cmds_slider_handle ,{ queue: { position: 'end', scope: 'sliderscope', limit: 2 } } );
     }
    );
    Event.observe(cmds_slider,'mouseleave', 
     function(e){
        Effect.Queues.get('sliderscope').each(function(effect) { effect.cancel(); });
        Effect.Fade( cmds_slider_handle ,{ queue: { position: 'end', scope: 'sliderscope', limit: 2 } } );
     }
    );
    Effect.Fade( cmds_slider_handle ,{ queue: { position: 'end', scope: 'sliderscope', limit: 2 } } );
  }

  if (inputfields_slider)
  {
    Event.observe(inputfields_slider,'mouseenter', 
     function(e){
        Effect.Queues.get('sliderscope1').each(function(effect) { effect.cancel(); });
        Effect.Appear( inputfields_slider_handle ,{ duration: 0.01, queue: { position: 'end', scope: 'sliderscope', limit: 2 } } );
     }
    );
    Event.observe(inputfields_slider,'mouseleave', 
     function(e){
        Effect.Queues.get('sliderscope1').each(function(effect) { effect.cancel(); });
        Effect.Fade( inputfields_slider_handle ,{ queue: { position: 'end', scope: 'sliderscope1', limit: 2 } } );
     }
    );
    
    Effect.Fade( inputfields_slider_handle ,{ queue: { position: 'end', scope: 'sliderscope1', limit: 2 } } );
   }


  if ($("result"))
    Effect.Fade( "result" );
  if ($("plot"))  
    Effect.Fade( "plot" );
    
    
    
   if (cmds_slider)  
    new Control.Slider(cmds_slider.down('.handle'), cmds_slider, {
      axis:'vertical',      
      range: $R(0, 10*30+2+20+43),
      sliderValue: 0,
      onSlide: function(value) {
        cmdspane.setStyle({ top: -value + 'px' });
      },
      onChange: function(value) { 
        cmdspane.setStyle({ top: -value + 'px' });
      }
    });
     


 if ($('warranty'))
	window.setTimeout(function(){
	    new Effect.Pulsate('warranty');
     }, 1500 ); 		 
 
 
 if ($('quickstartguide_image'))
	window.setTimeout(function(){
	    Effect.BlindUp("quickstartguide_image",{duration:0.5});
     }, 2500 ); 		 
 


  
 /*  
 if ($("center").hasClassName("moveable"))
 {
	 var centertopposition = 0;
	 
	 window.setInterval( function(){
	 window.status = parseInt($("display").getHeight());
	 
	  var height = parseInt($("display").getHeight());
	  var top = parseInt($("center").getStyle("top"));
	   
	  height = 25*(1+Math.round(height / 25));
	 	 $("center").setStyle({top:(height+80)+"px"});
	  
	 }, 1000 );
 }
 */
    
    window.setInterval( checkForInputChanges, 100 );   
   
    if ($("feedback"))
     window.setTimeout( function(){ $("feedback").appear() }, 1*100 );
     
    
    if ($("sociable"))
    	$("sociable").appear();
    
    
    if ($('cmd_f1'))
     showcmd(1);
    
    
    
     
   if ($("center").hasClassName("moveable"))
    {
    // var centerdrag = new Draggable("center", { snap: [5, 5], starteffect:null, endeffect:null});
    // $("center").setStyle({position:"absolute",left:(document.viewport.getWidth()/2-339)+"px", top:"122px"});
    }
    
  };


Event.observe(window, 'load', function() {

  var activate = true;
  try{
    if (window.location.href.indexOf("embedded")>0)
    	activate = false;
  } catch (e)
  {
  }
  
  if (activate)
   $("input").activate();
  init();
    
  if (ispro)
  {
   $("center").show();
   showpro();
  }
  
});




var centerdragstarted = false;
function startcenterdrag()
{
	if (!centerdragstarted && $("center").hasClassName("moveable"))
    {
     var centerdrag = new Draggable("center", { snap: [5, 5], starteffect:null, endeffect:null});
     $("center").setStyle({position:"absolute",left:(document.viewport.getWidth()/2-339)+"px", top:"122px"});
     centerdragstarted = true;
    }
}


function showStyle()
  {
   createColorPicker('col_text');
   createColorPicker('col_func');
   createColorPicker('col_ident');
   createColorPicker('col_unittype');
   
   $('style_div').show();
  }
  
   

  function createColorPickerClickEvent(id, color)
  {
    return function()
    {
       $(id+"_input").value = color;
       $(id).setStyle({color:color});
    }
  }
  function createColorPickerKeyEvent(id, color)
  {
    return function()
    {
       $(id).setStyle({color:$(id+"_input").value});
    }
  }
  
  function createColorPicker(id, defaultcolor)
  {
    if ($(id+"_colors").childElements().length>0)
     return;
     
    var colors=new Array( "#FFFFFF", "#EEEEEE", "#FFFF88", "#FF7400", "#CDEB8B", "#6BBA70", "#006E2E", "#C3D9FF", "#4096EE", "#356AA0", "#FF0096", "#B02B2C", "#000000");
    
    if (defaultcolor)
    	colors.unshift(defaultcolor);
    
    var bar = $(id+"_colors");
    for (var i=0;i<colors.length;i++)
    {
     var color = colors[i];
     var div=Builder.node("div");
     div.setStyle({backgroundColor:color,margin:"3px",width:"12px",height:"12px", border:"1px solid silver",float:"left",cursor:"pointer"});
     div.onclick = createColorPickerClickEvent(id,color);
     $(id+"_input").onkeyup = createColorPickerKeyEvent(id,color);
     
     bar.appendChild( div );
    } 
    bar.appendChild( Builder.node("div",{style:"clear: both;"}) );
    
  }

  function changeStyle()
  {
   if ($('style_background') && $('style_background').value!="")
    return true;
    
   if ($("style") && $("style").checked)
   {
    $("col_text").setStyle( {color:$("col_text_input").value} );
    $("col_func").setStyle( {color:$("col_func_input").value} );
    $("col_ident").setStyle( {color:$("col_ident_input").value} );
    $("col_unittype").setStyle( {color:$("col_unittype_input").value} );
    
    
    //$("html").setStyle( {backgroundAttachment:"fixed",backgroundRepeat:"repeat", backgroundImage:"url("+$("style_background").value+")"} );
    $("logo").hide();
    
    $("input").value="styleexample="+Math.round(1000000*Math.random())+"*sin(90)+5meter";
    equal();
   } else
   {
    $("html").setStyle( {backgroundImage:"url(/img/bge.png)"} );
    $("logo").show();
   } 
   new Ajax.Request("/user/style/?save", { method: "post", parameters: $("style_form").serialize(true) });
   
   return false;
  }  
  
  
  
 function quickstartguide()
 {
   if ($("quickstartguide"))
   { 
     $("quickstartguide").remove();
     return;
   }  
   var div = Builder.node("div",{id:"quickstartguide"});
   var a = Builder.node("a",{href:".",title:"close"},"x");
   a.onclick=function(){
    $("quickstartguide").remove();
    return false;
   };
   a.setStyle({float:"right",color:"black",textDecoration:"none",padding:"2px"});
   div.setStyle({width:"420px",height:"334px",position:"absolute",right:"1px",top:"61px",border:"3px solid silver",zIndex:2134567,backgroundColor:"silver",cursor:"move",textAlign:"center"});
   var iframe = Builder.node("iframe",{src:"/quickstartguide/"});
   iframe.setStyle({width:"400px",height:"330px"});
   div.appendChild(a);
   div.appendChild(iframe);
   var body = $("body");
   body.appendChild(div);
   
   new Draggable( div, { snap: [5, 5] } );
 } 
 
 function showcmd(id)
 {
	 for (var i=1;i<=6;i++)
	 {
		 if (i==id)
		 {
			 $('cmds_'+i).show();
			 $('cmd_f'+i).setStyle("text-decoration:underline;");
			// $('cmd_f'+i).setStyle("background-image:url(/img/cmdsh.png);");
		 }
		 else
		 {
			 $('cmds_'+i).hide();
			 $('cmd_f'+i).setStyle("text-decoration:none;");
			// $('cmd_f'+i).setStyle("background-image:url(/img/cmds.png);");
		 }
	 }
 }
 
 
 
 Element.addMethods({
		imgloader: function(element, options)
		{
	 	   try{	
	 		if (element.readAttribute("alt").indexOf("/h")==0)
	 		{
	 		 element.writeAttribute({src:element.alt, alt:""});
	 		}
	 	   } catch (e)
	 	   {	 		   
	 	   }	
		}
 });
 

 var imgloaderinterval = window.setInterval( function(){

	try{
	 var offsety = parseInt( self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop );
	 
	 if (offsety>0)
	 {
	  window.clearInterval(imgloaderinterval);	 
	  $$('img').invoke('imgloader');
	 }
	} catch (e)
	{
	}
	 
 }, 250 );
 
 