var orderwindow;
var orderpage;
var termspage;

var PriceModel;
 
function StartOrder()
{
  CloseOrderForm();
  orderwindow = CreateAjaxPopup("orderform", _DefaultHash["basedir"] + "form.html", OrderFormHeadTemplate, InitOrderForm);
  orderpage = $(orderwindow.document);
  
  //orderwindow = window.open(_DefaultHash["basedir"] + "form.html", "orderform");
  //orderpage = $(orderwindow.document);
}

function CloseOrderForm()
{
  if (orderwindow != null)
  {
    orderwindow.close();
    orderwindow = null;
  }
}

function InitOrderForm()
{
  orderpage.find("#preload").hide();
   
  //init
  orderpage.find("#check-form").click(CheckForm);
  orderpage.find("#submit-form").click(SubmitForm);
  orderpage.find("#print-form").click(PrintForm);
  // deactivate the submit button
  orderpage.find("#submit-form").attr("disabled", "disabled"); 
  
  orderpage.find("#check-connection-msg").hide(); // *************** if (IsOnline())
  orderpage.find("#submit-success-msg").hide();
  orderpage.find("#submit-failure-msg").hide();
  orderpage.find("#check-success-msg").hide();
  orderpage.find("#check-failure-msg").hide();

  // fill watch info
  PriceModel = PriceCollection.getDataSumByModel(ParamsCount - 1, CurrentModel);
  
  var ModelHash = NameCollection.getDataHashByModel(CurrentModel);
  var ModelTable = new Array(); 
  var ModelTableInternal = new Array();
  for (var i = 0; i < ParamsCount; i++)
  {
    ModelTable[i] = new Array(ParamNames[i].getString(), ModelHash[Params[i]].getString());
    ModelTableInternal[i] = new Array(ParamNames[i].getString(), ModelHash[Params[i]].getInternalString());
  }
  //ModelTable.push(new Array(ModelNo.getString(), ReferenceCollection.getDataByModel(ParamsCount - 1, CurrentModel)));
  // no ones interested in that one!
  ModelTableInternal.push(new Array(ModelNo.getInternalString(), ReferenceCollection.getDataByModel(ParamsCount - 2, CurrentModel)));
  ModelTable.push(new Array(ModelPrice.getString(), PricePrefix.getString() + PriceModel.toString() + PriceSuffix.getString()));
  ModelTableInternal.push(new Array(ModelPrice.getInternalString(), PricePrefix.getInternalString() + PriceModel.toString() + PriceSuffix.getInternalString()));
  
  // into table
  var HtmlTable = jQuery.map(ModelTable, function(i) { return '<tr>' + jQuery.map(i, function(i) { return '<td>' + i + '</td>'; }).join("") + '</tr>'; }).join("");
  orderpage.find("#description > table").empty(); // debug only! *********
  orderpage.find("#description > table").append(HtmlTable);
  
  // and into form
  var form = orderpage.find("form"); 
  var PostTable = jQuery.map(ModelTable, function(i) { return i.join("\t"); }).join("\n");
  var PostTableInternal = jQuery.map(ModelTableInternal, function(i) { return i.join("\t"); }).join("\n");
  
  // fill in translations
  var i = 0
  orderpage.find(".lan").each(function() {
    $(this).html(FormTranslations[i++].getString());
  });
  

  // prepare or remove fields for custom
  var customservice = NameCollection.getDataByModel(ParamsCount - 1, CurrentModel);
  if (customservice.hasService1())
  {
    orderpage.find("[name=custom1]").attr("maxlength", customservice.textLimit1);
  }
  else
  {
    orderpage.find("#custom1").remove();
  }
  
  if (customservice.hasService2())
  {
    orderpage.find("[name=custom2]").attr("maxlength", customservice.textLimit2);
  }
  else
  {
    orderpage.find("#custom2").remove();
  }
  
  if (customservice.number == 0)
  {
    orderpage.find("#custom").remove();
    orderpage.find("#custom-font").remove();
  }
  else
  {
    // text limiter
    orderpage.find("[name^=custom]").keyup(function() { 
      if ($(this).val().length > $(this).attr("maxlength")) 
      {
        $(this).val($(this).val().substr(0, $(this).attr("maxlength")));
      }
      $(this).parent().find(".counter").text($(this).attr("maxlength") - $(this).val().length);
    });
    orderpage.find("[name^=custom]").keyup();
  }
  
  // write additional form info
  var FormHash = { 
    modeldata : PostTable,
    modeldatainternal: PostTableInternal, 
    language : Languages[CurrentLanguage], 
    languagefriendlyname : LanguageFriendlyNames[CurrentLanguage]
  };
  form.append(GetHiddenFormCode(FormHash));
  
  // fill watch images
  orderpage.find("#image-container").empty(); // debug only! *********
  
  $(".work:visible").each (function() 
  {
    var temp;
    if (pngprob())
    {
      //temp = '<div class="image" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src=\'${basedir}${id}.png\');"></div>';
      temp = '<img alt="" class="image" src="${basedir}${id}.gif" />';
    }
    else
    {
      temp = '<img alt="" class="image" src="${basedir}${id}.png" />';
    }
    orderpage.find("#image-container").append(
      $.template(temp), 
      DefaultHash({ "id" : $(this).attr("id") }));
  });
  
  // country selector fill
  var CountryInput = orderpage.find("select[name=country]");
  for (var i in Countries)
  {
    CountryInput.append($.template('<option value="${name}">${name}</option>'), { name: Countries[i].getString(), internal: Countries[i].getInternalString(), i: i});
  }
  CountryInput.change(ChangeCountry);
  ChangeCountry();
  
  // price
  orderpage.find("#model-price > .price").before(PricePrefix.getString());
  orderpage.find("#model-price > .price").text(FormatCurrency(PriceModel));
  orderpage.find("#shipping-price > .price").before(PricePrefix.getString());
  orderpage.find("#vat-price > .price").before(PricePrefix.getString());
  orderpage.find("#total-price > .price").before(PricePrefix.getString());
  
  orderpage.find("#preload").show();
}

///////////////////////////////////////////////////
// order form function
function CheckForm()
{
  var Regexes = { "email" : /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/ };
  orderpage.find(".invalid").each(function() 
  {
    $(this).parent().css("background-color", "white");
  });
  orderpage.find(".invalid").removeClass("invalid");
  
  orderpage.find(".required:visible").each(function () 
  {
    if (jQuery.trim($(this).val()) == "")
    {
      $(this).addClass("invalid");
    }
    else
    {
      var regex = Regexes[$(this).attr("name")];
      if (typeof regex != "undefined")
      {
        if (!($(this).val().match(regex)))
        {
          $(this).addClass("invalid");
        }
      }
    }
  });

  orderpage.find(".finished").removeClass("finished");
  orderpage.find("#check-success-msg").hide();
  orderpage.find("#check-failure-msg").hide();
  
  var emails = orderpage.find("input[name^=email]");
  if (emails.eq(0).val() != emails.eq(1).val())
  {
    emails.addClass("invalid");
  } 
  
  if (orderpage.find(".invalid").length > 0) 
  {
    orderpage.find(".invalid").each(function ()
    {
      $(this).parent().css("background-color", "orange");
    });
    orderpage.find("#check-failure-msg").show(500);
  }
  else
  {
    orderpage.find("#submit-form").removeAttr("disabled");
    orderpage.find("#check-form-div").addClass("finished");
    orderpage.find("#check-success-msg").show(500);
  }
  
  orderpage.find("#submit-failure-msg").hide();
  orderpage.find("#submit-success-msg").hide();
  
  return false;
}

function PrintForm()
{
  orderwindow.print();
  orderpage.find("#print-form-div").addClass("finished");
  return false;
}

function SubmitForm()
{
  var submitUrl = "submit/submit.pl"; //*****
  //var submitUrl = "http://www.watchcreator.com/devel/submit/submit.pl"; //*****
  //var submitUrl = "submit/nonsensesubmit.pl"; //*****
  
  //additional info for the mails
  var formHash = GetFormHash(orderpage.find("form"));
  orderpage.find("#check-success-msg").hide();
  orderpage.find("#check-failure-msg").hide();

  var addHash = {
    salutation : Salutation[formHash["gender"]].getString(),
    friendlygender : GenderTitle[formHash["gender"]].getInternalString(),
    modelprice : orderpage.find("#model-price").text(),
    shippingprice : orderpage.find("#shipping-price").text(),
    vatprice : orderpage.find("#vat-price").text(),
    totalprice : orderpage.find("#total-price").text()
  };
  
  orderpage.find("#additional").empty();
  orderpage.find("#additional").append(GetHiddenFormCode(addHash));

  //
  var submitHash = orderpage.find("form").serializeArray();
  jQuery.post(submitUrl, submitHash, SubmitSuccessCallback);
  var listener = $('<div id="listener" />');
  listener.ajaxError(SubmitFailureCallback);
  listener.hide();
  listener.appendTo($(document).find("body"));
  
  return false; // *** change to true only for debug. later remove action attr in form. *********
}

function SubmitSuccessCallback()
{
  $("#listener").remove();
  
  orderpage.find("#submit-form-div").addClass("finished");
  orderpage.find("#submit-failure-msg").hide();
  orderpage.find("#submit-success-msg").show(500);
}

function SubmitFailureCallback()
{
  $("#listener").remove();
  
  if (orderwindow == null)
  {
    alert("ajax fail");
    return;
  }
  
  orderpage.find(".finished").removeClass("finished");
  orderpage.find("#submit-success-msg").hide();
  orderpage.find("#submit-failure-msg").show(500);
}

///////////////////////////////////////////////
// info popups
function ShowShipping()
{
  CloseOverlayNow();
  CreateAjaxOverlay(ShippingTitle.getHtmlString(), _DefaultHash["basedir"] + "shipping.html", InitShipping);
}

function InitShipping()
{
  for (var i in Countries)
  {
    $(".overlay table").append($.template('<tr><td>${country}</td><td>${price}</td></tr>'), { country: Countries[i].getHtmlString(), price: PricePrefix.getHtmlString() + FormatCurrency(CountryPrices[i]) });
  }
  UpdateLanguage();
  $(".overlay tr:even").addClass("tableline");
}

function ShowDealerInfo()
{
  CloseOverlayNow();
  CreateAjaxOverlay(DealerInfoTitle.getHtmlString(), _DefaultHash["basedir"] + "dealerinfo.html", UpdateLanguage);
}

function ShowContact()
{

}

function ShowRetailerList()
{
  CloseOverlayNow();
  CreateAjaxOverlay(RetailerListTitle.getHtmlString(), _DefaultHash["basedir"] + "retailer-list.html", UpdateLanguage);
}

function ShowTerms()
{
  CloseOverlayNow();
  CreateAjaxOverlay(TermsTitle.getHtmlString(), _DefaultHash["basedir"] + "terms.html", InitTerms);
}

function InitTerms()
{
  $(".overlay h3").each(function(i)
  {
    var hash = { name : "term" + i.toString(), title : $(this).html() };
    $(this).before($.template('<a name="${name}" />'), hash);
    $(".overlay #index").append($.template('<div><a href="#${name}">${title}</a></div>'), hash);
  });
  
  UpdateLanguage();
}

function ShowImprint()
{
  CloseOverlayNow();
  CreateAjaxOverlay(ImprintTitle.getHtmlString(), "imprint/imprint.html #content", UpdateLanguage);
}

function ShowPrivacy()
{
  CloseOverlayNow();
  CreateAjaxOverlay(PrivacyTitle.getHtmlString(), "privacy/privacy.html #content", UpdateLanguage);
}

///////////////////////////////////////////////
// countries & shipping
function ChangeCountry()
{
  var index = -1;
  orderpage.find("option").each(function(i)
  {
    // if ($(this).attr("selected")) // seems not to work with older browser
    if ($(this).is(":selected"))
    {
      index = i;
      return false;
    }
  });
  
  if (index == -1) 
  {
    alert("Leider ist ein unerwarteter Fehler aufgetreten. Bitte stellen Sie sicher, dass Sie eine aktuelle Browserversion verwenden. Falls dieser Fehler erneut auftritt, kontaktieren Sie uns bitte.\n\nWe are sorry but an unexpected error occurred. Please make sure your browser version is up to date. If this error should persist, please kindly contact us.");
    return;
  }
  
  index--;
  
  //if (index == -1)
  if (index <= -1)
  {
    // no country chosen.
    orderpage.find("#shipping-price").parent().hide();
    orderpage.find("#total-price").parent().hide();
  }
  else
  {
    orderpage.find("#shipping-price > .price").text(FormatCurrency(CountryPrices[index]));
    orderpage.find("#total-price > .price").text(FormatCurrency(CountryPrices[index] + PriceModel));
    orderpage.find("#vat-price > .price").text(FormatCurrency((CountryPrices[index] + PriceModel) * 0.19 / 1.19));
    
    orderpage.find("#shipping-price").parent().show();
    orderpage.find("#total-price").parent().show();
  }
} 

////////////////////////////////////////////////
function CreateOverlay(title)
{
  CloseOverlay();
  
  $("#frame").append($.template('<div class="overlay"><div class="overlay-hl"><a href="" class="overlay-close">&nbsp;X&nbsp;</a>${title}</div><div class="overlay-cont"></div></div>'), { title: title});
  
  with ($(".overlay a"))
  {
    click(CloseOverlay);
    attr("title", CloseTooltip.getString());
  }
  
  UpdateLanguage();
  with ($(".overlay"))
  {
    hide(); 
    fadeIn(300, function() { $(this).dropShadow(); $(this).fadeTo(0, 0.95); });
  }
  
  return $(".overlay-cont");
}

function CreateAjaxOverlay(title, filename, callback)
{
  var overlay = CreateOverlay(title);
  overlay.load(filename, {}, callback);
  
  return overlay;
}

function CloseOverlay()
{
  $(".dropShadow").fadeOut(300, function() {$(this).remove(); });
  $(".overlay").fadeOut(300, function() {$(this).remove(); });
  return false;
}

function CloseOverlayNow()
{
  $(".dropShadow").remove(); 
  $(".overlay").remove(); 
  return false;
}

function CreatePopup(name, headTemplate, bodyTemplate, hash)
{
  var newwindow = window.open("", name);
  newwindow.document.write(htmlTemplate);
  newwindow.document.close();
  $(newwindow.document).find("head").append($.template(headTemplate), hash);
  $(newwindow.document).find("body").append($.template(bodyTemplate), hash);
  return newwindow;
}

function CreateAjaxPopup(name, filename, headTemplate, callback)
{
  var newwindow = window.open("", name);
  newwindow.document.write(htmlTemplate);
  newwindow.document.close();
  
  $(newwindow.document).find("body").load(filename, {}, callback);
  $(newwindow.document).find("head").append(headTemplate);

  return newwindow;
}
    
var htmlTemplate = '<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><head></head><body onload=""></body></html>';
var OrderFormHeadTemplate = '<title>Watch Creator – Create your own watch</title><link rel="stylesheet" type="text/css" href="files/form.css" />'; 

function FormatCurrency(number)
{
  var f = formatZahl(number, 2, true);
  /*if (f.substr(f.length - 2) == "00")
    return f.substr(0, f.length - 2) + "--";
  else*/
    return f;
}

function formatZahl(zahl, k, fix) { 
    if(!k) k = 0; 
    var neu = ''; 
    // Runden 
    var f = Math.pow(10, k); 
    zahl = '' + parseInt( zahl * f + (.5 * (zahl > 0 ? 1 : -1)) ) / f ; 
    // Komma ermittlen 
    var idx = zahl.indexOf('.'); 
    // fehlende Nullen einf?gen 
    if(fix) { 
         zahl += (idx == -1 ? '.' : '' ) 
         + f.toString().substring(1); 
    } 
    // Nachkommastellen ermittlen 
    idx = zahl.indexOf('.'); 
    if( idx == -1) idx = zahl.length; 
    else neu = Decimal.getString() + zahl.substr(idx + 1, k); 
  
    // Tausendertrennzeichen 
    while(idx > 0)    { 
        if(idx - 3 > 0) 
        neu = Thousands.getString() + zahl.substring( idx - 3, idx) + neu; 
        else 
        neu = zahl.substring(0, idx) + neu; 
        idx -= 3; 
    } 
    return neu; 
} 


