/**
 * Änderungen
 *
 * WER	 WANN	    WAS 
 * LAC  16.01.07  neues Produkt JPG
 * LAC  16.01.07  neues Produkt Situationskopie beglaubigt
 * LAC  12.02.07  neues Produkt DXF mit Rahmen
 *
 */

//// emulate indexOf property on array for browser that dont implement it
//if(!Array.indexOf){
//    Array.prototype.indexOf = function(obj){
//        for(var i=0; i<this.length; i++){
//            if(this[i]==obj){
//                return i;
//            }
//        }
//    }
//}

function catchKeyPress(e) {
  var el;
  if (window.event && window.event.srcElement)
      el = window.event.srcElement;
  if (e && e.target)
      el = e.target;
  if (!el) return;

  code = e.keyCode;
  srcname = el.id;

  // on enter, set order_submit_value to 1 so the action is caught by the geobestellungFormular plugin
  if(code == '13' && (srcname  == 'submit_confirm_login' || srcname == 'submit_confirm_passw')) {
    elt = xGetElementById('order_submit_value');
    elt.value = 1;
  }
}

// submit functions, depending of context
function submitOrder(e) {
  FormItemSelected();
}
// when user clic on button to reset the form
function resetOrder(e){
  elt = xGetElementById('order_reset_value');
  elt.value = 1;
  FormItemSelected();
}
// when user clic on button to calculate the price
function calculateOrder(e){
  productList = xGetElementById('order_article');
  selectedProduct = productList.options[productList.selectedIndex].value;
  if (selectedProduct == 'dxf_pro_gemeinde' || selectedProduct == 'itf_pro_gemeinde' || selectedProduct == 'shp_pro_gemeinde') {
  } else {
    //check if at least one feature exist
    for (var i=0;i<mainmap.layers.length;i++){
      if (mainmap.layers[i].id == 'drawing'){
        if (mainmap.layers[i].features.length <= 0){
          alert ('Veuillez dabord séléctionner des données (points 1 à 3)')
          return;
        }
      }
    }
  }
  elt = xGetElementById('order_calculate_value');
  elt.value = 1;
  FormItemSelected();
}
// when user clic on button for submitting order
function submitOrder2(e){
  // check is user is loged
  elt = xGetElementById('order_userlogged');
  if (elt.value == false){
    // user not loged, display warning message
    elt = xGetElementById('submit_confirm_contener');
    elt.style.position = 'absolute';
    elt.style.top = '150px';
    elt.style.left = '300px';
    elt.style.display = "block";
  } else {
    // user loged, submit order 
    submitOrderFinal();
  }
}
// when user clic on button on the confirm dialog box that appear when the user is not loged
function submitOrder3(e){
  // user is a registered user but not logged ? check if the login and passwrd fields are filled
  elt = xGetElementById('registered_user_yes');
  if (elt.checked){
    logelt = xGetElementById('submit_confirm_login');
    paselt = xGetElementById('submit_confirm_passw');
    if (logelt.value == '' || paselt.value == ''){
      alert('Login oder Passwort fehlt!');
      return;
    } else {
      // submit
      submitOrderFinal();
    }
  } else {
    // submit
    submitOrderFinal();
  }
}
// submiting form
function submitOrderFinal() {
  elt = xGetElementById('order_submit_value');
  elt.value = 1;
  FormItemSelected();
}
// close sumbit confirmation box
function cancelSubmit() {
  elt = xGetElementById('submit_confirm_contener');
  elt.style.display = 'none';
}
// display/hide login form block
function displayLogin(e) {
    var el;
    if (window.event && window.event.srcElement)
        el = window.event.srcElement;
    if (e && e.target)
        el = e.target;
    if (!el) return;

    elt = xGetElementById('submit_confirm_loginform');
    if (el.id == 'registered_user_yes'){
      // show login block
      elt.style.display = 'block';
      focusOn('submit_confirm_login');
    } else {
      // hide login block
      elt.style.display = 'none';
    }
}

// called from within the dhtml, switch the SIT scale options when the user change the format
function switchScale(format) {
  currentFormat = format;
  if (!scaleOrder[currentFormat])
    return;
  scaleList = xGetElementById('order_sit_scale');
  // remove existing options
  scaleList.options.length = 0;
  // create new options
  newScaleOptions = scaleOrder[currentFormat];
  newOption = '';
  for (i=0;i<(newScaleOptions.length/2);i++){
    var newOption = xCreateElement("option");
    var newAttr = document.createAttribute('value');
    newAttr.value = newScaleOptions[i*2];
    newOption.setAttributeNode(newAttr);
    var newVal = document.createTextNode(newScaleOptions[(i*2)+1]);
    newOption.appendChild(newVal);
    scaleList.appendChild(newOption);
  }
}

// main function for activation/deactivation of tools
// I know the name of this function is stupid, I will change it if i have time
var tmptool;
//function setDhtmlSitrotate(action){
function activateTool(action){
  switch (action) {
  case 'geo':
    productList = xGetElementById('order_article');
    selectedProduct = productList.options[productList.selectedIndex].value;
    // set product id in a temporary variable
    tmptool = selectedProduct;
    // check for mainmap availability
    checkMapExistence();
  break;
  case 'pdf':
    tmptool = 'pdf';
    checkMapExistence();
  break;
  case 'outline':
    // THIS DOSNT WORK!!!
  /*
    //get current layer
    currentLayer = mainmap.currentLayer.id;
    //set temporarily current layer
    mainmap.setCurrentLayer('drawing');
    if (mainmap) hideSitFeature();
    if (mainmap) hidePdfFeature();
    //reset current layer
    mainmap.setCurrentLayer(currentLayer);
    */
    tmptool = 'outline';
    checkMapExistence();
  break;
  }
}
// function checking existence of object mainmap, recursive call as long as the object is not set
// this is needed as IE sometimes call this function before the mainmap object is ready
function checkMapExistence() {
  try {
    mainmap
  } catch (e){
    setTimeout('checkMapExistence()',100);
    return;
  }
  switchTool(tmptool);
}
function checkMapExistence2() {
  try {
    mainmap
  } catch (e){
    setTimeout('checkMapExistence2()',100);
    return;
  }
  displayOrderFeature();
}
// activate/deactivate order selection tool and pdfrotate tool
function switchTool(tool) {
  productList = xGetElementById('order_article');
  selectedProduct = productList.options[productList.selectedIndex].value;

  switch (tool) {
    case 'sit':
    case 'sit_siae':
    case 'sitshop':
    case 'jpg':
    case 'sit_bg':
    case 'dxf_rahmen':
    case 'dxf_siae':
    case 'itf_siae':
      // if pdf tool is activated, hide it
      if (cw3_tools.indexOf('pdfrotate') > -1){
        hidePdfFeature();
      }
      // if sitrotate tool is activated, show it
      if (cw3_tools.indexOf('sitrotate') > -1){
        mainmap.sitrotate('map');
        setActiveToolButton('sitrotate');
      }  
    break;
    case 'dxf_ch':
    case 'dxf_ne':
    case 'geobat_ch':
    case 'geobat_ne':
    case 'geobat_nes':
    case 'itf_ne':
    case 'itf':
      // if pdf tool is activated, hide it
      if (cw3_tools.indexOf('pdfrotate') > -1){
        hidePdfFeature();
      }
      // if dxf_rect tool is activated, show it
      if (cw3_tools.indexOf('dxf_rect') > -1 || cw3_tools.indexOf('dxf_polygon') > -1 || cw3_tools.indexOf('dxf_move') > -1){
        mainmap.dxf_rect('map');  
        setActiveToolButton('dxf_rect');
      }  
    break;
    case 'pdf':
      // if sitrotate tool is activated, hide it
      if (selectedProduct == 'sit' || selectedProduct == 'sit_siae' || selectedProduct == 'sitshop' || selectedProduct == 'jpg' || selectedProduct == 'sit_bg' || selectedProduct == 'dxf_rahmen' || selectedProduct == 'dxf_siae' || selectedProduct == 'itf_siae'){
        hideSitFeature();
      }
      // if dxf_rect tool is activated, hide it
      if (selectedProduct == 'dxf_dm01' || selectedProduct == 'shp' || selectedProduct == 'itf'){
        hideDxfFeature();
      }
      // if pdf tool is activated, show it
      if (cw3_tools.indexOf('pdfrotate') > -1){
        mainmap.pdfrotate('map');
        setActiveToolButton('pdfrotate');
      }
    break;
    case 'outline':
      // if sitrotate tool is activated, hide it
      if (selectedProduct == 'sit' || selectedProduct == 'sit_siae' || selectedProduct == 'sitshop' || selectedProduct == 'jpg' || selectedProduct == 'sit_bg' || selectedProduct == 'dxf_rahmen' || selectedProduct == 'dxf_siae' || selectedProduct == 'itf_siae'){
        hideSitFeature();
      }
      // if dxf_rect tool is activated, hide it
      if (selectedProduct == 'dxf_dm01' || selectedProduct == 'shp' || selectedProduct == 'itf'){
        hideDxfFeature();
      }
      // if pdf tool is activated, hide it
      if (cw3_tools.indexOf('pdfrotate') > -1){
        hidePdfFeature();
      }
      // if outline tool is activated, show it (in this case, its just the layer that change)
      if (cw3_tools.indexOf('outline_point') > -1 || cw3_tools.indexOf('outline_line') > -1 || cw3_tools.indexOf('outline_rectangle') > -1 || cw3_tools.indexOf('outline_poly') > -1){
        mainmap.outline_point('map');
        setActiveToolButton('outline_point');
      }
    break;
  }
}

function displayOrderFeatureIni() {
  checkMapExistence2();
}
// activate tool
function displayOrderFeature() {
	MandateTypeList = xGetElementById('mandate_type');
	if(MandateTypeList.options[MandateTypeList.selectedIndex].value != '') {
	  productList = xGetElementById('order_article');
	  selectedProduct = productList.options[productList.selectedIndex].value;
	  /*
	  if (selectedProduct == 'dxf' && featureGeom && featureGeom != ''){
		mainmap.setCurrentLayer('drawing');
		var newFeature = new Feature(featureGeom);
		newFeature.id = mainmap.currentLayer.features.length + 1;
		mainmap.currentLayer.addFeature(newFeature);
		var aDisplay = mainmap.getDisplay('map');
		aDisplay.drawFeature(aDisplay.currentLayer, newFeature, _OFF, false); <- ???????????   
	  }
	  */
	  if (document.carto_form.js_folder_idx.value == 8 && selectedProduct != '') {
		activateTool('geo');
	  }
	  if (document.carto_form.js_folder_idx.value == 4) {
		activateTool('pdf');
	  }
	}
}

// deactivate the submit button
function deactivateSubmit() {
  elt = xGetElementById('order_submit');
  if (elt){
    elt.disabled = true;
  }
  elt = xGetElementById('order_submit_2');
  if (elt){
    elt.disabled = true;
  }
}

/* reset form on user logout */
function geoshopLogout() {
  setActiveToolButton('zoomin');
  $('fake_reset').name = 'logout';
  var el = $('order_reset_value');
  if (el && typeof(el) != 'undefined') {
    resetOrder();
  } else {
    FormItemSelected();
  }
}


// event listeners
function addOrderListener() {
  EventManager.Add(document.body, 'keydown', catchKeyPress, false);

  elt = xGetElementById('mandate_type');
  EventManager.Add(elt, 'change', submitOrder, false);
  elt = xGetElementById('order_article');
  EventManager.Add(elt, 'change', submitOrder, false);
  elt = xGetElementById('order_reset');
  EventManager.Add(elt, 'click', resetOrder, false);
  elt = xGetElementById('order_calculate');
  EventManager.Add(elt, 'click', calculateOrder, false);

  elt = xGetElementById('order_submit');
  if (elt){
      EventManager.Add(elt, 'click', submitOrder2, false);
  }
  elt = xGetElementById('order_submit_2');
  if (elt){
      EventManager.Add(elt, 'click', submitOrder2, false);
  }
  displayOrderFeatureIni();

  elt = xGetElementById('registered_user_yes');
  EventManager.Add(elt, 'click', displayLogin, false);
  elt = xGetElementById('registered_user_no');
  EventManager.Add(elt, 'click', displayLogin, false);
  elt = xGetElementById('order_submit_confirm');
  EventManager.Add(elt, 'click', submitOrder3, false);
  elt = xGetElementById('cancel_order_submit');
  EventManager.Add(elt, 'click', cancelSubmit, false);
}

EventManager.Add(window, 'load', addOrderListener, false);