﻿/*
	QuickLaTeX.com rendering service.
	
	Project homepage: http://www.quicklatex.com/
	Contact e-mail:   pavel@holoborodko.com

 	Copyright 2008-2011 Pavel Holoborodko
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions
	are met:
	
	1. Redistributions of source code must retain the above copyright
	notice, this list of conditions and the following disclaimer.
	
	2. Redistributions in binary form must reproduce the above copyright
	notice, this list of conditions and the following disclaimer in the
	documentation and/or other materials provided with the distribution.
	
	3. Redistributions of any form whatsoever must retain the following
	acknowledgment:
	"
         This product includes software developed by Pavel Holoborodko
         Web: http://www.holoborodko.com/pavel/
         e-mail: pavel@holoborodko.com
	
	"

	4. This software cannot be, by any means, used for any commercial 
	purpose without the prior permission of the copyright holder. 

	5. This software is for individual usage only. It cannot be used as a part
	of "software as a service" systems (blog hosting services for multiple 
	users like WordPress MU or alike) without the prior permission of 
	the copyright holder. 
	
	Any of the above conditions can be waived if you get permission from 
	the copyright holder. 

	THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
	ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
	FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
	DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
	LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
	OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
	SUCH DAMAGE.
*/

jQuery(document).ready(function($) 
{
	//Populate font size
	for (i=5;i<100;i++) $("#fontsize").append('<option value="'+i+'">'+i+'px</option>');
	$("#fontsize option:eq(12)").attr("selected", "selected");
	
	// Advanced Section
	is_visible = false;
	$(".toggle").hide();

	$("p#advanced").click(function(event)
	{
		is_visible = !is_visible;
		
		if(is_visible)
			{
				$("img#advanced").attr('src', "images/minus.gif" );
				$("div#adv_wrap").css('padding-bottom','20px');
				$(".toggle").show();							
			}else{
				$("img#advanced").attr('src', "images/plus.gif" );				
				$("div#adv_wrap").css('padding-bottom','10px');	
				$(".toggle").hide();							
			}
	})
	.hover(
		function(){
			$(this).css('color', '#0000FF');},
		function(){
			$(this).css('color', '#333333');}
	)
	.css('cursor','pointer');
	
		
	// Color selection + input fields sync
	var txtcolor = $("#textcolor").val();
    
	hex = parseInt(txtcolor, 16);
    r   = hex >> 16; 
    g   = (hex & 0x00FF00) >> 8; 
    b   = hex & 0x0000FF;
    if(0.213 * r +	0.715 * g +0.072 * b < 128)
    {
       $("#textcolor").css('color','#FFFFFF');                                
    }else{
       $("#textcolor").css('color','#000000');                                	
    }
	
    $("#textcolor").css('background-color','#'+txtcolor);                                		
   
    
	var bkgcolor = $("#bkgcolor").val();
	hex = parseInt(bkgcolor, 16);
    r   = hex >> 16; 
    g   = (hex & 0x00FF00) >> 8; 
    b   = hex & 0x0000FF;
    if(0.213 * r +	0.715 * g +0.072 * b < 128)
    {
       $("#bkgcolor").css('color','#FFFFFF');                                	
    }else{
       $("#bkgcolor").css('color','#000000');                                		   
    }
    $("#bkgcolor").css('background-color','#'+bkgcolor);                                		   
	
	
	// Ajax 
    $("#compile").click(function(event){ // live('click', function(event){ 
		
		event.preventDefault(); 	
	
		// Extract parameters
		var fontsize  = $('#fontsize').val();
		var formula   = $.trim($('#qltext').val());
		var textcolor = $('#textcolor').val();
		var bkgcolor  = $('#bkgcolor').val();    
		var latexmode = $('#latexmode').val();    
		var preamble  = $.trim($('#pretext').val());    

		if(formula!="")
		{
			// Build url for the request
			//var url = "http://localhost/ql/latex2.f";
			//var url = "http://www.quicklatex.com/latex2.f";		
			//var url = "http://localhost/latex3.f";					
			var url = "latex3.f";
			var body;
			
			formula = formula.replace(/%/g,"%25");
			formula = formula.replace(/&/g,"%26");

			preamble = preamble.replace(/%/g,"%25");
			preamble = preamble.replace(/&/g,"%26");
			
			body =        'formula=' +formula;
			body = body + '&fsize='  +fontsize+'px';
			body = body + '&fcolor=' +textcolor;
			body = body + '&mode=0';
			body = body + '&out=1&remhost=quicklatex.com';
			if(preamble!='') body = body+'&preamble='+preamble;
			

			if ($('#showerrors').is(':checked'))	body = body + "&errors=1";		

			// Prevent ajax request from  caching
			body = body + '&rnd='+Math.random()*100;
			
			$("#math").css('border','none');	
			$("#math").html("<p style=\"text-align:center;\"><img src=\"images/progressbar.gif\" style=\"vertical-align:middle;\"/></p>");
			
			// Make XMLHttp query to the server		
			$.ajax({
				url: encodeURI(url),
				type: 'POST',
				dataType: 'text/plain',
				data: body,
				processData: false,
				timeout: 100000,
				//traditional: false,
				//global: false,
				success: function(data){
						if(data.length)
						{
								//Parse server response
								//                (status)\r\n(url) (align)  (errormsg)
								var pattern = /^([-]?\d+)\r\n(\S+)\s([-]?\d+)\s(\d+)\s(\d+)\r?\n?([\s\S]*)/;

								var regs = data.match(pattern);	
								var status = regs[1];
								var imgurl = regs[2];
								var valign = regs[3];
								var imgw   = regs[4];
								var imgh   = regs[5];
								var errmsg = regs[6];

								$("#math").css('border','1px solid #C0C0C0');		

								if(status=='0') // Ok
								{
										$("#math").html("<p style=\"font-size:13px;position:relative;top:-10px;\">Output Image:</p>"
														+"<p style=\"text-align:center;\">"+"<img style=\"padding:10px;background-color:"+"#"+bkgcolor+";\""+"src=\""+imgurl+"\"/>"+"</p>"
														+"<p style=\"font-size:13px;position:relative;bottom:-15px;\">"+imgurl+"</p>");

								}else{ //Error
										$("#math").html("<p style=\"font-size:13px;position:relative;top:-10px;\">Server Returns Error Message:</p>"
														+"<pre style=\"padding-left:20px;position:relative;top:-10px;\">"+errmsg+"</pre>"); 					
								} //error
						}
				}, //$.ajax.success()

				error: function(xhr,textStatus){
					alert("Cannot connect to quicklatex.com\n"/*+xhr.statusText*/);
				}
			}); //$.ajax
		}// if(formula!="")	
		
		// disable complete refresh of the window 
		// http://stackoverflow.com/questions/1155952/how-do-i-prevent-scrolling-to-the-top-of-a-page-when-popping-up-a-jquery-ui-dialo 		
		return false; 
	}); // button click
 }); //document.ready
