var bAjaxInProgress = false;

var displayWidth=155;
var displayHeight=219;
var g_div_width;
var g_div_height;
var g_img_small_preview_height;
var g_img_small_preview_width;
var g_ratio = 0;

function set_preview_image_ratio(ratio)
{
	var bUpdate = false;	
	if(ratio!= g_ratio)
		bUpdate = true;
	g_ratio = ratio;
	return bUpdate;
}

function convertBookPdf()
{
	if(bAjaxInProgress) return;

	// get the parameters for the converter
	var converterParameters = getConverterParameters();
	
	// show the ajax working gif
	$('display').update('<img id="ajax_working" src="media/ajax_green.gif" alt="ajax_working"/><br/>Ihr Buch wird konvertiert. Dieser Vorgang kann einige Minuten dauern');
	
	// call convert script via ajax
	bAjaxInProgress = true;
    new Ajax.Request('bookPreviewPdfConvert.php?book='+g_book+converterParameters,
     {
      onSuccess: convertPdfResHandler
     });	
}

function convertPdfResHandler(xml_http)
{
	// get the response, which is either the filename of the converted pdf or FAILURE
	var response = xml_http.responseText.split(",");
	var code = response[0];
	var msg = response[1];
	bAjaxInProgress = false;

	if(code == "OK")
	{
		// the pdf has been converted, create new page preview images
		create_preview_image(cur_page);		
	}
	else if(code == -1) // the user isn't logged in
	{			
		// the pdf has been converted, create new page preview images
		create_preview_image(cur_page);	
	}
	else
	{
		$('convert_info').update(msg);
		// hide the ajax working gif
		$('display').update('');
	}
	ajaxRunning--;
}	


function create_preview_image(page_number) 
{
	if(bAjaxInProgress) return;
	ajaxRunning++;
	
	if(page_number<0)
    {
        $('display').update("<font color=red>Sie sind bereits auf der ersten Seite</font>");
        ajaxRunning--;
        return;
    }
    else if(page_number > max_page)
    {
        $('display').update("<font color=red>Dies ist die letzte Seite des Buches</font>");
        ajaxRunning--;
        return;
    }

	// call the create_page_preview.php to create the image
	
	// get the parameters for the pdf converter
	var converterParameters = getConverterParameters();
	
    cur_page = page_number;
    
    // if the current page is 0, then skip the creation of the left cover image, and trigger the creation of the right one
    if(page_number==0)
    {
    	$('display').update('<img id="ajax_working" src="media/ajax_green.gif" alt="ajax_working"/><br/>erstelle rechte Seite...');
        $('page1').update('');
		bAjaxInProgress = true;
        new Ajax.Request('create_page_preview.php?page_number=1&book='+g_book+converterParameters,
         {
          onSuccess: resHandler2
         });
    }
    else
    {
    	$('display').update('<img id="ajax_working" src="media/ajax_green.gif" alt="ajax_working"/><br/>erstelle linke Seite...');
		bAjaxInProgress = true;
        new Ajax.Request('create_page_preview.php?page_number='+page_number+'&book='+g_book+converterParameters,
          {
            onSuccess: resHandler
          }
        );
    }
}

function create_preview_imageShop(page_number) 
{
	if(bAjaxInProgress) return;
	
	// set the book page divs to the correct size.
	g_div_width = displayWidth;
	g_div_height = g_ratio!=0 ? displayWidth/g_ratio : displayHeight;
	$('page1').style.width = g_div_width+"px"; 
	$('page1').style.height = g_div_height+"px"; 
	
	$('page2').style.width = g_div_width+"px"; 
	$('page2').style.height = g_div_height+"px"; 
	
	
	if(page_number<0)
    {
        $('display').update("<font color=red>Beginn der Vorschau</font>");
        return;
    }
    else if(page_number > 5)
    {
        $('display').update("<font color=red>Ende der Vorschau</font>");
        return;
    }

    cur_page = page_number;
    $('display').update('<img id="ajax_working" src="media/ajax_green.gif" alt="ajax_working"/><br/>erstelle linke Seite...');
    // if the current page is 0, then skip the creation of the left cover image, and trigger the creation of the right one
	//alert('create_page_previewShop.php?page_number='+page_number+'&book='+g_book);
    if(page_number==0)
    {
        $('page1').update('');
		bAjaxInProgress = true;
        new Ajax.Request('create_page_previewShop.php?page_number=1&book='+g_book,
         {
          onSuccess: resHandler2
         });
    }
    else
    {
		bAjaxInProgress = true;
        new Ajax.Request(
         'create_page_previewShop.php?page_number='+page_number+'&book='+g_book,
          {
            onSuccess: resHandlerShop
          }
        );
    }
}


function resHandler(xml_http)
{
	// parse the reponse
	var response_array = xml_http.responseText.split(",");

	// calculate the image dimensions
	var thumbnail_src = response_array[0];
	var width = parseInt(response_array[1]);
	var height = parseInt(response_array[2]);
	var large_preview_src = response_array[3];
	var isRegisteredUser = response_array[4];
	
	
	// set the book page divs to the correct size.
	if(isRegisteredUser)
	{
		// set the book page divs to the correct size.
		g_div_width = displayWidth;
		var ratio = width / height;
		g_div_height = ratio!=0 ? displayWidth/ratio : displayHeight;
	
		$('page1').style.width = g_div_width+"px"; 
		$('page1').style.height = g_div_height+"px"; 
	
		$('page2').style.width = g_div_width+"px"; 
		$('page2').style.height = g_div_height+"px";
	}
	
	var img_ratio = width/height;
	var div_ratio = g_div_width / g_div_height;
	
	if(img_ratio >  div_ratio) 
	{
		g_img_small_preview_width = g_div_width;
		g_img_small_preview_height = g_div_width / img_ratio;
	}
	else
	{
		g_img_small_preview_height = g_div_height;
		g_img_small_preview_width = g_div_height * img_ratio;
	}
	
	var date = new Date();
	timestamp = date.getTime();
	
	$('page1').update('<div style="padding-top:'+(g_div_height-g_img_small_preview_height)/2+'px;">'+
					' <a href="image.php?fileName='+large_preview_src+'&cache='+timestamp+'" class="highslide" onclick="return hs.expand(this)">'+
						' <img src="image.php?fileName='+thumbnail_src+'&cache='+timestamp+'" alt="Highslide JS"'+
							' title="Click to enlarge" height="'+g_img_small_preview_height+'" width="'+g_img_small_preview_width+'" border="0" /></a>'+
					' <div class="highslide-caption">'+ 
					    'Klicken Sie in das Bild um die Vorschau zu schlie&szlig;en.'+
					'</div>'+
					'</div>');

	
	
    // create the preview for the right page if one exists.
	
	// get the parameters for the pdf converter	
	var converterParameters = getConverterParameters();
	
    if(cur_page+1<=max_page)
    {
    	$('display').update('<img id="ajax_working" src="media/ajax_green.gif" alt="ajax_working"/><br/>erstelle rechte Seite...');
        new Ajax.Request('create_page_preview.php?page_number='+(cur_page+1)+'&book='+g_book+converterParameters,
         {
           onSuccess: resHandler2
         }
        );
    }
    else
    {
        //remove the old image
        $('page2').update('');
        $('display').update('Seite '+cur_page);
		bAjaxInProgress = false;
		ajaxRunning--;
    }
}

function resHandlerShop(xml_http)
{
	// parse the reponse
	var response_array = xml_http.responseText.split(",");

	// calculate the image dimensions
	var thumbnail_src = response_array[0];
	var width = parseInt(response_array[1]);
	var height = parseInt(response_array[2]);
	var large_preview_src = response_array[3];
	var isRegisteredUser = response_array[4];
	
	
	// set the book page divs to the correct size.
	if(isRegisteredUser)
	{
		// set the book page divs to the correct size.
		g_div_width = displayWidth;
		var ratio = width / height;
		g_div_height = ratio!=0 ? displayWidth/ratio : displayHeight;
	
		$('page1').style.width = g_div_width+"px"; 
		$('page1').style.height = g_div_height+"px"; 
	
		$('page2').style.width = g_div_width+"px"; 
		$('page2').style.height = g_div_height+"px";
	}
	
	var img_ratio = width/height;
	var div_ratio = g_div_width / g_div_height;
	
	if(img_ratio >  div_ratio) 
	{
		g_img_small_preview_width = g_div_width;
		g_img_small_preview_height = g_div_width / img_ratio;
	}
	else
	{
		g_img_small_preview_height = g_div_height;
		g_img_small_preview_width = g_div_height * img_ratio;
	}
	
	var date = new Date();
	timestamp = date.getTime();
	
	$('page1').update('<div style="padding-top:'+(g_div_height-g_img_small_preview_height)/2+'px;">'+
					' <a href="image.php?fileName='+large_preview_src+'&cache='+timestamp+'" class="highslide" onclick="return hs.expand(this)">'+
						' <img src="image.php?fileName='+thumbnail_src+'&cache='+timestamp+'" alt="Highslide JS"'+
							' title="Click to enlarge" height="'+g_img_small_preview_height+'" width="'+g_img_small_preview_width+'" border="0" /></a>'+
					' <div class="highslide-caption">'+ 
					    'Klicken Sie in das Bild um die Vorschau zu schlie&szlig;en.'+
					'</div>'+
					'</div>');

	
	
    // create the preview for the right page if one exists.
	
	// get the parameters for the pdf converter	
		
    if(cur_page+1<=max_page)
    {
    	$('display').update('<img id="ajax_working" src="media/ajax_green.gif" alt="ajax_working"/><br/>erstelle rechte Seite...');
        new Ajax.Request('create_page_previewShop.php?page_number='+(cur_page+1)+'&book='+g_book,
         {
           onSuccess: resHandler2
         }
        );
    }
    else
    {
        //remove the old image
        $('page2').update('');
        $('display').update('Seite '+cur_page);
		bAjaxInProgress = false;
		ajaxRunning--;
    }
}

function getConverterParameters()
{
	var convertBW = document.getElementById('convertBW').checked ? "1" : "0";
	var isSinglePage = document.getElementById('isSinglePage').checked ? "1" : "0";
	var bookFormat = document.getElementById('papersize').value;
	var covertype = document.getElementById('covertype').options[document.getElementById('covertype').selectedIndex].value;
	
	return "&convertBW="+convertBW+"&isSinglePage="+isSinglePage+"&bookFormat="+bookFormat+"&coverType="+covertype;
}

function resHandler2(xml_http)
{
	// parse the reponse
	var response_array = xml_http.responseText.split(",");

	// calculate the image dimensions
	var thumbnail_src = response_array[0];
	var width = parseInt(response_array[1]);
	var height = parseInt(response_array[2]);
	var large_preview_src = response_array[3];
	var isRegisteredUser = response_array[4];
	
	
	// set the book page divs to the correct size.
	if(isRegisteredUser)
	{
		g_div_width = displayWidth;
		var ratio = width / height;
		g_div_height = ratio!=0 ? displayWidth/ratio : displayHeight;
		
		$('page1').style.width = g_div_width+"px"; 
		$('page1').style.height = g_div_height+"px"; 
		$('page2').style.width = g_div_width+"px"; 
		$('page2').style.height = g_div_height+"px";
	}
	
    var img_ratio = width/height;
	var div_ratio = g_div_width / g_div_height;
	
	if(img_ratio >  div_ratio) 
	{
		g_img_small_preview_width = g_div_width;
		g_img_small_preview_height = g_div_width / img_ratio;
	}
	else
	{
		g_img_small_preview_height = g_div_height;
		g_img_small_preview_width = g_div_height * img_ratio;
	}
	var date = new Date();
	timestamp = date.getTime();
	
	$('page2').update('<div style="padding-top:'+(g_div_height-g_img_small_preview_height)/2+'px;">'+
					' <a href="image.php?fileName='+large_preview_src+'&cache='+timestamp+'" class="highslide" onclick="return hs.expand(this)">'+
						' <img src="image.php?fileName='+thumbnail_src+'&cache='+timestamp+'" alt="Highslide JS"'+
							' title="Click to enlarge" height="'+g_img_small_preview_height+'" width="'+g_img_small_preview_width+'" border="0" /></a>'+
					' <div class="highslide-caption">'+ 
					    'Klicken Sie in das Bild um die Vorschau zu schlie&szlig;en.'+
					'</div>'+
					'</div>');


    if(cur_page == 0)
        $('display').update('Seite 1');
    else
        $('display').update('Seite '+cur_page+' und '+(cur_page+1));
	
	bAjaxInProgress = false;
	ajaxRunning--;
}

function showLargePreview(side)
{
	if(bAjaxInProgress) return;
	
	bAjaxInProgress = true;
	new Ajax.Request('get_large_page_preview.php?page_number='+(cur_page+side),
         {
           onSuccess: resHandler3
         }
        );
}

var large_preview_max_width = 900;
var large_preview_max_height = 700; 

function resHandler3(xml_http)
{
	var response_array = xml_http.responseText.split(",");
	
	if(response_array[0]=="-1")
		return;
		
	var img_width = parseInt(response_array[1]);
	var img_height = parseInt(response_array[2]);
	var img_ratio = img_width /img_height;
	
	
	$('testdiv').style.visibility = 'visible';
	// set the width and height of the div
	var div_width, div_height;
	
	if(g_ratio < large_preview_max_width/large_preview_max_height) // if the selected format is higher than broad
	{	
		div_height = large_preview_max_height;
		div_width = large_preview_max_height*g_ratio;		
	}
	else
	{
		div_width = large_preview_max_width;	
		div_height = large_preview_max_width/g_ratio;
	}
	
	$('testdiv_c').style.width = div_width+"px";
	$('testdiv_c').style.height = div_height+"px";
	
	// center the div
	$('testdiv_c').style.left = (screen.width/2 - div_width/2)+"px";
	$('testdiv_c').style.top = (window.innerHeight/2 - div_height/2)+"px";
	
	
	// calculate the dimensions of the image
	if(img_ratio >  div_width/div_height) // the image is broader than high
	{
		img_width = div_width;
		img_height = div_width / img_ratio;
	}
	else
	{
		img_height = div_height;
		img_width = div_height * img_ratio;
	}
	
	
	//<div style="paddding-top:'+((div_height-img_height)/2)+'px"></div><img src="image.php?fileName='+response_array[0]+'" alt="large preview" onclick="hideLargePreview()" border="0" height="'+img_height+'" width="'+img_width+'" />
	bAjaxInProgress = false;
}

function hideLargePreview()
{
	document.getElementById('testdiv').style.display = 'none';
}

function getParameters(form)
{

                var title = encrypt(document.getElementById('title').value);
                var subtitle = encrypt(document.getElementById('subtitle').value);

                //var series = document.getElementById('series').value;
                var series = "";
                var author = encrypt(document.getElementById('author').value);
                var temp = document.getElementById('papertype');
                var papertype = temp.options[temp.selectedIndex].value;
                temp = document.getElementById('papersize');
                var papersize = temp.options[temp.selectedIndex].value;
                temp = document.getElementById('covertype');
                var covertype = temp.options[temp.selectedIndex].value;
				temp = document.getElementById('coverstyle');
				var coverstyle = temp.options[temp.selectedIndex].value;
				var binding = document.getElementById('binding').value;
                var bookprice = encrypt(displayWithDot(document.getElementById('basicformatvalue').value));
                var coverprice = encrypt(displayWithDot(document.getElementById('basiccovervalue').value));
                var discount = encrypt(document.getElementById('discountpercentage').value);
                var unitprice = encrypt(displayWithDot(document.getElementById('unitprice').value));
				var publish = document.getElementById('publish').checked ? "1" : "0";
				var convertBW = document.getElementById('convertBW').checked ? "1" : "0";
				var isSinglePage = document.getElementById('isSinglePage').checked ? "1" : "0";

                return "?title="+title+"&subtitle="+subtitle+"&series="+series+"&author="+author+"&papertype="+papertype+"&pageformat="+papersize+
                                "&covertype="+covertype+"&binding="+binding+"&coverstyle="+coverstyle+"&bookprice="+bookprice+"&coverprice="+coverprice+"&discount="+discount+"&unitprice="+unitprice+
									"&published="+publish+"&convertBW="+convertBW+"&isSinglePage="+isSinglePage;

}

function changeTitle(title)
{
        document.getElementById("pageBookTitle").firstChild.nodeValue=title;
}

function getDiscountData(ordercount)
{
                percentfordiscount = 0;
			
                rabatt_minimum = 0;
        for(i = 0; i < document.booksetup.elements.length; i++)
                {
                        var stname = document.booksetup.elements[i].name;

            var _check = stname.search("discount_")
            if (_check != -1) {
                                var result = document.booksetup.elements[i].name;

                                var mypac = result.replace('discount_','');
                                if(parseInt(trim(ordercount)) < parseInt(trim(mypac)))
                                {
                                        break;
                                }
                                else
                                {
                                        percentfordiscount = parseFloat(document.booksetup.elements[i].value);
                                        // save this percentage for later submit
                                        document.getElementById('discountpercentage').value = percentfordiscount;
                                        rabatt_minimum = parseInt(trim(mypac));
                                }
            }
                }
}

function displayWithComma(str)
{
                        return str.replace(".",",");
}
function displayWithDot(str)
{
                        return str.replace(",",".");
}
    
var percentfordiscount;
var rabatt_minimum;

function clearValues()
{
                document.getElementById('totalprice').value="0";
                document.getElementById('vatprice').value="0";
                //document.getElementById('vattotalprice').value="0";
                document.getElementById('shippingtotaltext').value="Versandkosten*";
                document.getElementById('shippingtotalprice').value="0";
                document.getElementById('deliveryprice').value="0";

                document.getElementById('basicformattext').value="Basispreis " + " (inkl. " + 32 + " Seiten) ";
        document.getElementById('basicformatvalue').value = 0;
                document.getElementById('basiccovertext').value="Preis Einband ";
        document.getElementById('basiccovervalue').value = 0;
}



var calculationResult;

/** 
 * updates the calculation
 */
function updateCalculation(book)
{
	// get the neccessary input for the calculation
	var calculationInput = assembleCalculationInput(book);

	// calculate
	calculationResult = calculate(calculationInput);
	// verify the result of the calculation
	if(!validateCalculation(calculationResult))
		alert(calculationResult.error);
		
	// render the output to the website
	renderCalculation(calculationInput, calculationResult);
}


/**
 * updates the website contents with the values of the calculation
 * @param calculationResult 
 * 		the result of the calculation
 */
function renderCalculation(input, calculationResult)
{
	clearValues();

	var coverType = document.getElementById('covertype');
    var pageFormat = document.getElementById('papersize');
    
    
	var bookPrice = calculationResult.bookPrice;

    document.getElementById('basicformattext').value="Basispreis " + (pageFormat.value != "select" ? pageFormat.options[pageFormat.selectedIndex].text :"") + " (inkl. " + 32 + " Seiten) ";
    document.getElementById('basicformatvalue').value = displayWithComma(bookPrice.toFixed(2));

    var coverPrice = calculationResult.coverPrice;

    document.getElementById('basiccovertext').value="Preis Einband " + (coverType.value != "select" ? coverType.options[coverType.selectedIndex].text : "" )
    												 + " " + (pageFormat.value != "select" ? pageFormat.options[pageFormat.selectedIndex].text :"");
    document.getElementById('basiccovervalue').value = displayWithComma(coverPrice.toFixed(2));

    // render the price for additional sw pages
    var additionaleBWPagePrice = calculationResult.bwPagePrice;
    var additionalBWPages = calculationResult.additionalBWPages;
    document.getElementById('additionalSWPagesText').value = additionalBWPages+" zusätzliche S/W-Seiten (je "+input.bwPagePrice.toFixed(2)+" €)";
    
    // render the price for additional color pages
    document.getElementById('additionalSWPagesValue').value = displayWithComma(additionaleBWPagePrice.toFixed(2)) +" €";

    // price for additional color pages
    var additionalColorPages = calculationResult.additionalColorPages;
    var additionalColorPagePrice = calculationResult.colorPagePrice;
    document.getElementById('additionalColorPagesText').value = additionalColorPages+" zusätzliche Farbseiten (je "+input.colorPagePrice.toFixed(2)+" €)";;
    document.getElementById('additionalColorPagesValue').value = displayWithComma(additionalColorPagePrice.toFixed(2)) + " €";

    // price for additional empty pages (single side print)
    var additionalEmptyPages = calculationResult.additionalEmptyPages;
    var additionalEmptyPagePrice = calculationResult.emptyPagePrice;
    document.getElementById('additionalEmptyPagesText').value = additionalEmptyPages+" leere Seiten (je "+input.emptyPagePrice.toFixed(2)+" €)";
    document.getElementById('additionalEmptyPagesValue').value = displayWithComma(additionalEmptyPagePrice.toFixed(2)) + " €";
    document.getElementById('additionalEmptyPagesText').className  = additionalEmptyPages ? "inputnone"  : "inputnone hidden";
    document.getElementById('additionalEmptyPagesValue').className = additionalEmptyPages ? "inputvalue" : "inputvalue hidden";

    
    // TODO needs to be refactored 
    
    // price per book
    var unitprice = calculationResult.unitPrice;
    document.getElementById('unitprice').value = displayWithComma(unitprice.toFixed(2));
    
    
    var total = unitprice;
    document.getElementById('totalprice').value = displayWithComma(total.toFixed(2));

    // calculate the vat from the brutto price 'total'
    var vat = total * 0.07;
    document.getElementById('vatprice').value =  displayWithComma(vat.toFixed(2));
	//$('balance').value = 'huhu';
    // we calculate with brutto prices already
    var vattotal = total;
    document.getElementById('shippingtotalprice').value = displayWithComma(shipping_price.toFixed(2));
	total -= shipping_price;
	// render the balance if neccessary
	if($('balance') != null)
		$('balance').value = "- "+displayWithComma(calculationResult.balance.toFixed(2));
		
    document.getElementById('deliveryprice').value = calculationResult.total.toFixed(2);
}

/**
 * this method fetches the input for the calculation
 * @return 
 * 		the input object
 */
function assembleCalculationInput(book)
{
	var calculationInput = new Object();
	
	// set the book price. the price is defined by the pageFormat and the paperType
	var selectedBookFormatId = document.getElementById('papersize').value;	
	var selectedPaperTypeId = document.getElementById('papertype').value;
	
    if(selectedBookFormatId == 'select' || selectedPaperTypeId == 'select')
    {
    	book.bookPrice = 0;
    	// set the price for a b/w page
        calculationInput.bwPagePrice = 0;
            
        // set the price for a color page
        calculationInput.colorPagePrice = 0;
        // set the price for a color page
        calculationInput.emptyPagePrice = 0;
    }
    else
    {
    	// get the price from a hidden field
    	book.bookPrice = document.getElementById("book_price_"+selectedBookFormatId+"_"+selectedPaperTypeId).value*1;
    	// set the price for a b/w page
        calculationInput.bwPagePrice = document.getElementById("book_additional_sw_page_price_"+selectedBookFormatId+"_"+selectedPaperTypeId).value*1;
            
        // set the price for a color page
        calculationInput.colorPagePrice = document.getElementById("book_additional_color_page_price_"+selectedBookFormatId+"_"+selectedPaperTypeId).value * 1;        
        // set the price for a color page
        calculationInput.emptyPagePrice = document.getElementById("book_additional_empty_page_price_"+selectedBookFormatId+"_"+selectedPaperTypeId).value * 1;        
    }
    
	calculationInput.isUserTheOwner = true;
    // set a flag if the book is converted to black and white
    calculationInput.isConvertedToBW = document.getElementById('convertBW').checked;
    calculationInput.isSinglePage = document.getElementById('isSinglePage').checked;
    
    // set the coverPrice
    var selectedCoverTypeId = document.getElementById('covertype').value;
    if(selectedCoverTypeId == "select")
    {
    	book.coverPrice = 0;
    }
    else
    {
    	// get the price from a hidden field
    	book.coverPrice = document.getElementById("cover_price_"+ selectedCoverTypeId).value*1;
    }
	
    
	/** pass the amount of books */
	calculationInput.amount = 1;
	
	/** pass the book */
    calculationInput.book = book;
	
    /** pass the discount */
	calculationInput.discount = null;
	   
	/** pass the coupon information */
	calculationInput.coupon = null;
	
	/** pass the selected fabrication */
	calculationInput.fabrication = null;
	
	/** pass the selected shipping */
	var shipping = new Object();
	shipping.country = germany;
	shipping.price = germany.deliveryPrice;
	shipping.isDummy = true;
	shipping.giftPrice = shipping1.giftPrice;
	calculationInput.shipping = shipping;
	
	calculationInput.balance = user.balance;
	
	/** pass the selected country */
	calculationInput.country = germany;
	
	return calculationInput;
}
