///////////////////////////////////////////////////////////////////////
// 
// JavaScript for Globex IXS Booking and Tracking Interface
// 2008, zeitform Internet Dienste
//
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// Global Ajax Settings
//////////////////////////////////////////////////////////////////////

// some globals see http://docs.jquery.com/Ajax_Events
$.ajaxSetup({
  type: "POST",
  dataType: "text",
  error: function(req, status, error){ 
      if (error) alert( "Error: " + error + " Status:" + status); 
    }
}); 

// preload images
jQuery.preloadImages = function() {
  for (var i = 0; i<arguments.length; i++) {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

// global loader
jQuery().ajaxStart(function() {
  if ($('#loading').length) {
    // show loader
    $('#loading').show();
  } else {
    // create loader
    $('#header').append('<div id="loading"><img width="16" height="16" alt="" src="images/ajax-loader.gif"/> Loading Data &hellip; Please Wait</div>');
  }
}).ajaxStop(function() {
    $('#loading').hide();
});


$(document).ready(function() {

  // hide help link
  $("li a[href=/help]").parent('li').hide();
  // hide classic link
  $('#classic').hide()
  //$("li a[href=supplier.asp]").parent('li').hide();

  $.preloadImages('images/ajax-loader.gif');

  // show ajax load on every submit
  $('form').submit(function() {
    if ($('#loading').length) {
      // show loader
      $('#loading').show();
    } else {
      // create loader
      $('#header').append('<div id="loading"><img width="16" height="16" alt="" src="images/ajax-loader.gif"/> Loading Data &hellip; Please Wait</div>');
    }
    return true;
  });
});

//////////////////////////////////////////////////////////////////////
// cookie functions
//////////////////////////////////////////////////////////////////////

// add cookie elements
function addCookieElement (cookie, value) {

  if ($.cookie(cookie) && $.cookie(cookie).length > 0) {
    var cook = $.cookie(cookie).split("|");
    var newcookie = new Array();
    for (var i=0; i < cook.length; i++) { 
      if (value != cook[i]) newcookie.push(cook[i]);
    }
    newcookie.push(value);
    $.cookie(cookie, newcookie.join("|"));
    //$.cookie(cookie, $.cookie(cookie) + '|' + value);
  } else {
    $.cookie(cookie, value);
  }
}

// remove cookie elements
function removeCookieElement (cookie, value) {

    var cook = $.cookie(cookie).split("|");
    var newcookie = new Array();
    for (var i=0; i < cook.length; i++) { 
      if (value != cook[i]) newcookie.push(cook[i]);
    }
    $.cookie(cookie, newcookie.join("|"));
}

//////////////////////////////////////////////////////////////////////
// Global helpers
//////////////////////////////////////////////////////////////////////
function ucfirst (str) {
    // Makes a string's first character uppercase  
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

//////////////////////////////////////////////////////////////////////
// Advanced tracking views
//////////////////////////////////////////////////////////////////////

function select_view(v) {
  if (v==1) {
    $('#customer_view').hide();
    $('#select_view').show();
  }
  if (v==2) {
    $('#select_view').hide();
    $('#customer_view').show();
  }
  $.cookie('view', v);
}

//////////////////////////////////////////////////////////////////////
// Advanced Search
//////////////////////////////////////////////////////////////////////

function advanced_search() {
  $('#advanced_search').toggle();
  if($('#advanced_search').is(':visible')) {
    $('#more_option').attr('src', 'images/icons/icn-down.png');
    $.cookie('advsearch','1');
  } else {
    $('#more_option').attr('src', 'images/icons/icn-right.png');
    $.cookie('advsearch','0');
  }

}

//////////////////////////////////////////////////////////////////////
// Loader for tree view
//////////////////////////////////////////////////////////////////////

function load_projects (id) {

  // check if rows are present
  if ($("tr.projectrow_" + id).length) {
    // remove rows
    $("tr.projectrow_" + id).remove();
    // toggle icon
    $("#rowimg_" + id).removeClass("active");
    $("#rowimg_" + id).addClass("inactive");

    // remove cookie
    removeCookieElement('cust_tree', id);

    return;
  }

  $.ajax({

     url: "ajax_projects.asp",
     data: "CUST_ID=" + id,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );
	// insert result
        $("#row_" + id).after(msg);

	// toggle icon
	$("#rowimg_" + id).removeClass("inactive");
	$("#rowimg_" + id).addClass("active");


	//if ( $('tr.customerrow').size() == 1 && $('tr.projectrow_' + id).size() == 1) {
	if ( $('tr.projectrow_' + id).size() == 1) {
	  var proj=$('tr.projectrow_' + id).get(0).id; //.attr("id");
	  proj = proj.replace(/^.+_/, "");
          //alert("1 " + id + " " +proj);
	  load_sites(id,proj);
	} else if ($.cookie('proj_tree')) { 
	  var cook = $.cookie('proj_tree').split("|"); 
	  for (var i=0; i < cook.length; i++) {
	    if (cook[i]>0) {
              //alert("2 " + id + " " +cook[i]);
	      load_sites(id,cook[i]);
	    }
	  }
	}
     }
   });

  addCookieElement('cust_tree', id);

}

function load_sites (id, proj) {

  // check if rows are present
  if ($("tr.siterow_" + proj).length) {
    // remove rows
    $("tr.siterow_" + proj).remove();
    // toggle icon
    $("#rowimg_" + id + "_" + proj).removeClass("active");
    $("#rowimg_" + id + "_" + proj).addClass("inactive");

    // remove cookie
    removeCookieElement('proj_tree', proj);

    return;
  }
  
  $.ajax({

     url: "ajax_sites.asp",
     data: "CUST_ID=" + id + "&PROJ_ID=" + proj,

     success: function(msg){

        if (msg == "Session expired") { 
          window.location.href="advancedlogin.asp?last=fail";
          return;
        }
            

        //alert( "Data: " + msg );
        // insert result
        $("#row_" + id + "_" + proj).after(msg);

        // toggle icon
        $("#rowimg_" + id + "_" + proj).removeClass("inactive");
        $("#rowimg_" + id + "_" + proj).addClass("active");

     }
   });

  addCookieElement('proj_tree', proj);
}

//////////////////////////////////////////////////////////////////////
// Loader for select view
//////////////////////////////////////////////////////////////////////

function load_projects_select () {

  if ($("tr.siterow").length) {
    // remove rows
    $("tr.siterow").remove();$('#step2row').removeClass('active');
  }

  var param = $('#step1').val().split("|");
  var attr = param[0];
  var id = param[1];
  //alert("proj "+attr);

  if (id.length == 0 || id == 0) { 
    //alert("none");
    $('#step2').html('<option value="0" selected="selected">Select Project</option>');
    $('#icons1').hide();
    $('#label1').show();
    $('#step2row').hide();

     $.cookie('cust_sel', null);
     $.cookie('proj_sel', null);

  } else {
    //alert(id);

    $.ajax({

       url: "ajax_projects.asp",
       data: "CUST_ID=" + id + "&view=1",

       success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );
	// insert result
        //$('#step2').replaceWith(msg);
        $('#step2').html(msg);
        $('#step2').prepend('<option value="0" selected="selected">Select Project</option>');



        $('#label1').hide();
	
        if (attr&2) {
          //alert(attr + " show");
	  $('#url1').attr('href', 'listview.asp?q=c&A_ID=' + id);
	  $('#url1').show();
	  $('#inactive1').hide();
	} else {
	  //alert(attr + " hide");
	  $('#url1').hide();
	  $('#inactive1').show();
	  }
	
        $('#icons1').show();
        $('#step2row').show();

        $('#icons2').hide();
        $('#label2').show();
	$('#docimg').hide();

        //alert($('#step2 option').size());
        if ( $('#step2 option').size() == 2 ) { 
          $('#step2').get(0).selectedIndex = 1; 
          load_sites_select();
	} else if ($.cookie('proj_sel')) { 
          //alert($.cookie('proj_sel'));
          for (i = 1; i < $('#step2 option').size(); ++i) {
	    var param = $('#step2 option').get(i).value.split("|");
            //var attr = param[0];
            var proj =param[1];
            if (proj == $.cookie('proj_sel')) {
              //alert('found');
              $('#step2')[0].selectedIndex = i; 
              load_sites_select();
	      break;
	    }	
	  }
	} else {
          $('#step2').get(0).selectedIndex = 0; 
	}

     }
   });

    $.cookie('cust_sel', id);

  }
}

function load_sites_select () {
 
  if ($("tr.siterow").length) {
    // remove rows
    $("tr.siterow").remove();$('#step2row').removeClass('active');
  }

  var param = $('#step2').val().split("|");
  var attr = param[0];
  var proj =param[1];
  //alert(v);
  //alert("site "+attr);
  param = $('#step1').val().split("|");
  var id = param[1];

  if (!proj || proj.length == 0 || proj == 0) { 
    //alert("none");

    $('#icons2').hide();
    $('#label2').show();
    $('#docimg').hide();

    $.cookie('proj_sel', null);

  } else {

    $.ajax({

       url: "ajax_sites.asp",
       data: "CUST_ID=" + id + "&PROJ_ID=" + proj + '&view=1',

       success: function(msg){
 
          if (msg == "Session expired") { 
	    window.location.href="advancedlogin.asp?last=fail";
	    return;
          }
	    
	  //alert( "Data: " + msg );
	  // insert result
          $("#step2row").after(msg);$('#step2row').addClass('active');
          $('#label2').hide();
          if (attr&1) {
            $('#url2book').attr('href', 'book.asp?prk_id=' + proj);
            $('#url2book').show();
            $('#inactive2book').hide();
	  } else {
            $('#url2book').hide();
            $('#inactive2book').show();
	  }
          if (attr&2) {
	    //alert(attr + " show");
            $('#url2track').attr('href', 'Listview.asp?q=p&A_ID=' + proj);
            $('#url2track').show();
            $('#inactive2track').hide();
	  } else {
	    //alert(attr + " hideshow");
            $('#url2track').hide();
            $('#inactive2track').show();
	  }
          if (attr&4) {
            $('#docimg').click( function() { proj_doc_list(id, proj, 1); } );
            $('#docimg').show();
	  } else {
            $('#docimg').hide();
          }

          if (attr&8) {
            $('#url2budget').attr('href', 'budget.asp?prk_id=' + proj);
            $('#url2budget').show();
            //$('#inactive2budget').hide();
	  } else {
            $('#url2budget').hide();
            //$('#inactive2budget').show();
	  }

          $('#url2stats').attr('href', 'stats_project.asp?prk_id=' + proj);
          $('#url2stats').show();
          $('#icons2').show();
     }
   });

    $.cookie('proj_sel', proj);

  }
}

//////////////////////////////////////////////////////////////////////
// Loader for project documents
//////////////////////////////////////////////////////////////////////

function proj_doc_list (id, proj, check) {

  if ($('#projdocs_' + id + '_' + proj).length) {
    // remove list
    $('#projdocs_' + id + '_' + proj).remove();
    return;
  }

  $.ajax({

     url: "ajax_proj_docs.asp",
     data: "CUST_ID=" + id + "&PROJ_ID=" + proj,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );
        if (check) $("#docimg").after(msg)
        else $("#docimg_" + id + "_" + proj).after(msg);

     }
   });

}

//////////////////////////////////////////////////////////////////////
// Loader for active/requested/intended shipments
//////////////////////////////////////////////////////////////////////

var load_count = 0;

function load_shipments(ship, proj,autoload, nohome, o) {

  ship = ship || 'active';

  if (o)
    {
      show_loaded_shipments(ship, 0, o);
      return;
    }

  //alert(proj);
  // check if rows are present
  if ($("tr.ship_" + ship + "_" + proj).length) {
    // remove rows
    $("tr.ship_" + ship + "_" + proj).remove();
    // toggle icon
    $("#projshipimg_" + ship + "_" + proj).removeClass("active");
    $("#projshipimg_" + ship + "_" + proj).addClass("inactive");

    // remove cookie
    removeCookieElement(ship + '_ship', proj);

    if (!nohome) show_loaded_shipments(ship);

    return;
  }

  $.ajax({

     url: "ajax_" + ship + "_shipments.asp",
     data: "PRK_ID=" + proj,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}
	    

	//alert( "Data: " + msg );
	// insert result
        $("#projship_" + ship + "_" + proj).after(msg);


	// toggle icon
	$("#projshipimg_" + ship + "_" + proj).removeClass("inactive");
	$("#projshipimg_" + ship + "_" + proj).addClass("active");

	// add cluetip
	$('.ship_' + ship + "_" + proj + ' a.tooltip').cluetip({
	  arrows: false,
          dropShadow: false,
	  hoverIntent: false,
	      sticky: false, // fix alex
	  mouseOutClose: true,
          closePosition: 'title',
          ajaxSettings: { type: 'GET' },
          closeText: '&times;'
        });

     }
   });

  addCookieElement(ship + '_ship', proj);

  if (!autoload || $.cookie('home_view') == ship) {
    if (!nohome) show_loaded_shipments(ship);
  }
}

function show_loaded_shipments(ship,all,o) {
  // exit unless we are on home.asp
  //if (! location.href.match(/home/)) return;
  // show only open projects

  // load shipments
  if (($.cookie('home_view') != ship || $('#active_projects').size() == 0) && load_count == 0)
    {
      $("#col3_content").html('');
      load_count++;

      $.ajax({

	url: "ajax_home_" + ship + "_shipments.asp",
	success: function(msg){

	    if (msg == "Session expired") { 
	      window.location.href="advancedlogin.asp?last=fail";
	      return;
	    }
	    
	    // insert result
	    $("#col3_content").html(msg);

	// add cluetip
	$('#col3_content a.tooltip').cluetip({
	  arrows: false,
          dropShadow: false,
	  hoverIntent: false,
	  sticky: true,
	  mouseOutClose: true,
          closePosition: 'title',
          ajaxSettings: { type: 'GET' },
          closeText: '&times;'
        });

	    $.cookie('home_view', ship);
	    load_count = 0;
	    adjust_loaded_shipments(ship,all,o);

	    // ein/ausgrauen
	    $('.sidebar').addClass('sbinactive').removeClass('sbcurrent');
	    $('#sb_' + ship).removeClass('sbinactive').addClass('sbcurrent');;

	  }
	});
    }
  else
    {
      adjust_loaded_shipments(ship,all,o);
    }
}

function adjust_loaded_shipments(ship,all,o) {
  if (!all && ($.cookie(ship + '_ship') && $.cookie(ship + '_ship').length > 0)) {
    $('#project_headline div.projectlist').hide();
    var cook = $.cookie(ship + '_ship').split("|"); 
    var list = new Array();;
    for (var i=0; i < cook.length; i++) {
      if (cook[i]>0) {
	$('.proj_' + cook[i]).show(); 
	var e = $('#projshipimg_' + ship + "_" + cook[i] + ' span.filelist');
	if (e.html()) list.push("<strong>" + e.html() + "</strong>");
      }
    }
    $('#active_projects').html(ucfirst(ship) + " shipments for project" + (list.length > 1 ? "s" : "") + ': ' + list.join(', '));
  } else { // show all
    $('#project_headline div.projectlist').show();
    $('#active_projects').html("All " + ship + " shipments for all projects");
  }

  // close all
  $('.listview_more').hide();
  $('.listview_less').show();
  $('.projectlist').removeClass('sbinactive');

  // if expand shipment
  if (o) listview_more_details(o);
}


function collapse_sidebar(no) {

  if ($('#collapse' + no).is(':visible')) {
      $('#collapseicon' + no).attr('src', 'images/icons/icn-right.png');
      $('#collapse' + no).hide();
      $.cookie('collapse' + no, 1);
  } else {
      $('#collapseicon' + no).attr('src', 'images/icons/icn-down.png');
      $('#collapse' + no).show();
      $.cookie('collapse' + no, null);
  }
}

////////////////////////////////////////////////////////////


function show_waybill_tracking() {

  // params
  var a = $('#waybill-tracking').val();

  // load waybill result
  if (load_count == 0)
    {
      $("#col3_content").html('');
      load_count++;

      $.ajax({

	url: "ajax_home_waybill_tracking.asp",
        data: "a=" + a,
	success: function(msg){

	    if (msg == "Session expired") { 
	      window.location.href="advancedlogin.asp?last=fail";
	      return;
	    }
	    
	    // insert result
	    $("#col3_content").html(msg);

	// add cluetip
	$('#col3_content a.tooltip').cluetip({
	  arrows: false,
          dropShadow: false,
	  hoverIntent: false,
	  sticky: true,
	  mouseOutClose: true,
          closePosition: 'title',
          ajaxSettings: { type: 'GET' },
          closeText: '&times;'
        });

	    $.cookie('home_view', 'waybill');
	    load_count = 0;

	    // ein/ausgrauen
	    $('.sidebar').addClass('sbinactive').removeClass('sbcurrent');
	    $('#sb_search').removeClass('sbinactive').addClass('sbcurrent');;

	  }
	});
    }
  return false; // do not submit form
}

function show_search_results(e) {

  // param
  var params = $(':input', $(e)).serialize(); // e is form

  // load search result
  if (load_count == 0)
    {
      $("#col3_content").html('');
      load_count++;

      $.ajax({

	url: "ajax_home_search_results.asp",
        data: params,
	success: function(msg){

	    if (msg == "Session expired") { 
	      window.location.href="advancedlogin.asp?last=fail";
	      return;
	    }
	    
	    // insert result
	    $("#col3_content").html(msg);

	// add cluetip
	$('#col3_content a.tooltip').cluetip({
	  arrows: false,
          dropShadow: false,
	  hoverIntent: false,
	  sticky: true,
	  mouseOutClose: true,
          closePosition: 'title',
          ajaxSettings: { type: 'GET' },
          closeText: '&times;'
        });

	    $.cookie('home_view', 'search');
	    load_count = 0;

	    // ein/ausgrauen
	    $('.sidebar').addClass('sbinactive').removeClass('sbcurrent');
	    $('#sb_search').removeClass('sbinactive').addClass('sbcurrent');;

	  }
	});
    }
  return false; // do not submit form
}


//////////////////////////////////////////////////////////////////////
// Loader for listview more/less details
//////////////////////////////////////////////////////////////////////

function listview_more_details(id) {

  // close all
  $('.listview_more').hide();
  $('.listview_less').show();

  $('#listview_less_' + id + ',#listview_less_button_' + id).hide();
  $('#listview_more_' + id).show();

  $.scrollTo($('#listview_more_' + id).parent(), 500, { top:'100px' });

  // set inactive class
  $('.projectlist').addClass('sbinactive');
  $('#listview_more_' + id).parents('.projectlist').removeClass('sbinactive');

}
function listview_less_details(id) {

  $('#listview_less_' + id + ',#listview_less_button_' + id).show();
  $('#listview_more_' + id).hide();

  // unset inactive class
  $('.projectlist').removeClass('sbinactive');

}

//////////////////////////////////////////////////////////////////////
// Loader for site statistics
//////////////////////////////////////////////////////////////////////

function load_stats_details (prk, a) {

  $.ajax({

     url: "ajax_stats_project.asp",
     data: "prk_id=" + prk + "&A_ID=" + a,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

        $("#site-details").html(msg).show();

	// add cluetip
	$('#site-details a.tooltip').cluetip({
	  arrows: false,
          dropShadow: false,
	  hoverIntent: false,
	  sticky: true,
	  mouseOutClose: true,
          closePosition: 'title',
          ajaxSettings: { type: 'GET' },
          closeText: '&times;'
        });

     }
   });

}

//////////////////////////////////////////////////////////////////////
// Helpers for booking wizard (show/hide next button)
//////////////////////////////////////////////////////////////////////

function next_step_hide () {
  //$('#next_step').hide();
  //console.log('hide');
  if ($('#next_step').attr('src')) {
    var im = $('#next_step').attr('src').replace(/cont\.png/, 'cont-bt.png');
    var step = (im.match(/step(\d)-cont/))[1];

    $('#next_step').attr('src', im);
    // click me
    $('#next_step').unbind( "click" ).click( function() { missing_input(); return false; } );
  }
  
}
function next_step_show () {
  //console.log('show');
  //$('#next_step').show();
  if ($('#next_step').attr('src')) {
    var im = $('#next_step').attr('src').replace(/cont-bt\.png/, 'cont.png');
    $('#next_step').attr('src', im);
    $('#next_step').unbind( "click" ).click( function() { return true; } );
  }
}

function missing_input (step) {

  var step = ($('#next_step').attr('src').match(/step(\d)-cont/))[1];

  var missing = 
    [
    {
      "prk_id": 'Project',
      "mm_id_species": 'Material',
      "mm_id_packaging": 'Packaging'
    },
    {
      "from": 'Pickup Address',
      "to": 'Delivery Address',
      "contactfrom": 'Pickup Contact',
      "contactto": 'Delivery Contact'
    },
    {
      "number_total": 'Packaging'
    },
    {
      "etd_date_from": 'Pickup Date'
      //"etd_time_from": 'Pickup Time (from)',
      //"etd_time_to": 'Pickup Time (to)'
    }
    ];

  var error = [];
  for (var p in missing[step-1]) {
    if (! ($('#' + p).val() && $('#' + p).val().length > 0 && $('#' + p).val() != 0)) {
      //console.log('not ok: ' + p + ' -> ' + missing[step-1][p]);
      error.push(missing[step-1][p]);
    }

  }

  if (error.length > 0) {
    alert('Sorry, your form is incomplete.\n\nYou are missing:\n' + error.join(', '));
    return false;
  }
  //console.log('2missing: ' + error.join(', '));
  return false;
}

//////////////////////////////////////////////////////////////////////
// Loaders for booking wizard
//////////////////////////////////////////////////////////////////////

function submit_project () { 

  next_step_hide(); // no way out

  e = $('#prk_id').val()
  if (! e) { return; }

  // load material
  $.ajax({

     url: "ajax_book_material.asp",
     data: "PROJ_ID=" + e,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );
        $('#mm_id_species').html(msg);
        //$('#mm_id_species')[0].selectedIndex = 0; // will work this way...
        $('#mm_id_species').prepend('<option value="0" selected="selected">Please select material</option>');

	// ie6 s**cks - the following code is for ie6 only
	if ($('#mm_id_species').get(0).selectedIndex > 0) {
          submit_material();
	  //alert($('#mm_id_species').get(0).selectedIndex);
	}

	// tuwas
	if (e>0) { $('#prk_id').removeClass('tuwas'); }
        else { $('#prk_id').addClass('tuwas'); next_step_hide(); }

	// select the only entry if so
        if ( $('#mm_id_species option').size() == 2 ) { 
          $('#mm_id_species').get(0).selectedIndex = 1; 
          submit_material();
	} else {
          $('#mm_id_species').get(0).selectedIndex = 0; 
	  $('#mm_id_species').addClass('tuwas');
	}

	$('#mm_id_packaging').html('');

     }
   });

  // load project documents
    $.ajax({

     url: "ajax_book_documents.asp",
     data: "PROJ_ID=" + e,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );

	if (msg.length > 0)
	  {
	    $('#project_documents').html(msg);
	    $('#project_documents_container').show();
	  }
	else
	  {
	    $('#project_documents_container').hide();
	  }

     }
   });

}

function submit_material () {

  next_step_hide(); // no way out

  id = $('#prk_id').val();
  if (! id) { return; }  

  e = $('#mm_id_species').val();
  if (! e) { return; }

  $.ajax({

     url: "ajax_book_packaging.asp",
     data: "PROJ_ID=" + id + "&MM_ID_SPECIES=" + e,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );
        $('#mm_id_packaging').html(msg);
        //$('#mm_id_species')[0].selectedIndex = 0; // will work this way...
        $('#mm_id_packaging').prepend('<option value="0" selected="selected">Please select packaging</option>');


	// tuwas
	$('#mm_id_species').removeClass('tuwas');

	// select the only entry if so
        if ( $('#mm_id_packaging option').size() == 2 ) { 
          $('#mm_id_packaging').get(0).selectedIndex = 1; 
          submit_packaging();
	} else {
          $('#mm_id_packaging').get(0).selectedIndex = 0; 
	  $('#mm_id_packaging').addClass('tuwas');
	}

     }
   });
}

function submit_packaging () {
  //alert("form complete - would submit now");
  $('#mm_id_packaging').removeClass('tuwas');
  next_step_show();
}


function submit_site (type, prk) {

  next_step_hide(); // no way out

  if (type == "from") {
    id = $('#from').val();
  } else {
    id = $('#to').val();
  }

  // get site
  $.ajax({

     url: "ajax_view_site.asp",
     data: "SITE_ID=" + id + "&PRK_ID=" + prk,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

        if (type == "from") {
          $('#pickup_from').html(msg);
	  $('#from').removeClass('tuwas');
	} else {
	  $('#delivery_to').html(msg);
	   $('#to').removeClass('tuwas');
	}

     }
   });

  // empty site - empty handover
  if (! id || id == 0) { 

    if (type == "from") {
      $('#contactfrom').html('');
    } else {
      $('#contactto').html('');
    }
    submit_handover(type,prk); // empty details id any
    return; 
  }  

  $.ajax({

     url: "ajax_book_handover.asp",
     data: "SITE_ID=" + id + "&PRK_ID=" + prk,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

        if (type == "from") {
          $('#contactfrom').html(msg);
          $('#contactfrom').prepend('<option value="0" selected="selected">Please select handover contact</option>');
	  // pre-select if only one
	  //alert($('#contactfrom option').size());
	  if ( $('#contactfrom option').size() == 2 ) { 
	    $('#contactfrom').get(0).selectedIndex = 1; 
	    submit_handover(type,prk);
	  } else {
	    $('#contactfrom').get(0).selectedIndex = 0; 
            $('#contactfrom').addClass('tuwas');
	    submit_handover(type);
	  }

	} else {

	  $('#contactto').html(msg);
          $('#contactto').prepend('<option value="0" selected="selected">Please select handover contact</option>');

	  // pre-select if only one
	  //alert($('#contactto option').size());
	  if ( $('#contactto option').size() == 2 ) { 
	    $('#contactto').get(0).selectedIndex = 1; 
	    submit_handover(type,prk);
	  } else {
	    $('#contactto').get(0).selectedIndex = 0; 
	    $('#contactto').addClass('tuwas');
	    submit_handover(type);
	  }
	  
	}
	
     }
   });
}

function submit_handover (type,prk) {

  next_step_hide(); // no way out

  var id;
  var site;
  if (type == "from") {
    id = $('#contactfrom').val();
    site = $('#from').val();
  } else {
    id = $('#contactto').val();
    site = $('#to').val();
  }
  //if (! id) { return; }  

  $.ajax({

     url: "ajax_view_handover.asp",
     data: "SITE_ID=" + site + "&CONTACT_ID=" + id + "&PRK_ID=" + prk,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

        if (type == "from") {
          $('#handover_from').html(msg);
	  if (id>0) { $('#contactfrom').removeClass('tuwas'); }
	  else { $('#contactfrom').addClass('tuwas'); }
	} else {
	  $('#handover_to').html(msg);
	  if (id>0) { $('#contactto').removeClass('tuwas'); }
	  else { $('#contactto').addClass('tuwas'); }
	}

     }
   });

  // check if complete
  if ($('#contactfrom').val() > 0 && $('#contactto').val() > 0) {
    //alert("form complete - would submit now");
    next_step_show();
  }

}

function submit_service (prk) {

  //$('#next_step').hide(); // no way out

  mmid = $('#mm_id_service').val();

  // do something if prk or mmid is missing

  $.ajax({

     url: "ajax_book_service.asp",
     data: "PRK_ID=" + prk + "&MM_ID=" + mmid,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	$('#mm_packaging').html(msg);
	calc();
     }
   });

  $.ajax({

     url: "ajax_book_addservice.asp",
     data: "PRK_ID=" + prk + "&MM_ID=" + mmid,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	$('#additional_services').html(msg);

     }
   });
  

}
//////////////////////////////////////////////////////////////////////
// edit site/handover forms
//////////////////////////////////////////////////////////////////////

function edit_site (type, prk, new_site) { // pickup or delivery, new or edit

  var id;
  if (new_site == "new") {
    id = 0;
  } else if (type == "from") {
    id = $('#from').val();
  } else {
    id = $('#to').val();
  }

  $.ajax({

     url: "ajax_edit_site.asp",
     data: "SITE_ID=" + id + "&PRK_ID=" + prk + "&ROLE=" + type,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );
        if (type == "from") {
          $('#pickup_from').html(msg);
	} else {
	  $('#delivery_to').html(msg);
	}
     }
   });

}

function save_site (type, prk, id) {

  // hide submit button
  //$('#submit_' + type).hide();

  var params;
  if (type == "from") {
    var params = $('#pickup_from :input').serialize();
  } else {
    var params = $('#delivery_to :input').serialize();
  }

  $.ajax({

     url: "ajax_save_site.asp",
     data: "SITE_ID=" + id + "&PRK_ID=" + prk + "&TYPE=" + type + "&" + params,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );
        if (type == "from") {
          $('#pickup_from').html(msg);
          $('#from').removeClass('tuwas');
	} else {
	  $('#delivery_to').html(msg);
          $('#to').removeClass('tuwas');
	}

        // form again
        //$('#submit_' + type).show();

	// add/modify select option
        var n = $('#saved_site_no_' + type).html();
	var t = $('#saved_site_text_' + type).html();
	var opt = $('#' + type + ' option');
        var modified = 0;

	// change existing
	for (var i = 1; i < opt.size(); ++i) {
	  if (n == opt.get(i).value) {
	    opt.get(i).text = t;
	    modified = 1;
	    break;
	    //alert(n + '->' + opt.get(i).value);
	  }
	}
	// add new
	if (n && !modified) {
	  $('#' + type).append('<option selected="selected" value="' + n + '">' + t + '</option>');
	  if (type == "from") {
	    $('#contactfrom').html('');
	  } else {
	    $('#contactto').html('');
	  }
	  submit_handover(type,prk); // empty details id any
	}

     }
   });

}

function edit_handover (type, prk, new_site) { // pickup or delivery, new or edit

  var id;
  var site;
  if (type == "from") {
    site = $('#from').val();	
  } else {
    site = $('#to').val();  
  }
  
  if (new_site == "new") {
    id = 0;
  } else if (type == "from") {
    id = $('#contactfrom').val();
  } else {
    id = $('#contactto').val();
  }

  $.ajax({

     url: "ajax_edit_handover.asp",
     data: "SITE_ID=" + site + "&CONTACT_ID=" + id + "&PRK_ID=" + prk + "&ROLE=" + type,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	// alert( "Data: " + msg );
        if (type == "from") {
          $('#handover_from').html(msg);
	} else {
	  $('#handover_to').html(msg);
	}
     }
   });

}

function save_handover (type, prk, id, site) {

  // hide submit button
  //$('#submit_' + type).hide();
  var params;
  if (type == "from") {
    var params = $('#handover_from :input').serialize();
  } else {
    var params = $('#handover_to :input').serialize();
  }

  $.ajax({

     url: "ajax_save_handover.asp",
     data: "SITE_ID=" + site + "&CONTACT_ID=" + id + "&PRK_ID=" + prk + "&TYPE=" + type + "&" + params,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );
        if (type == "from") {
          $('#handover_from').html(msg);
	  $('#contactfrom').removeClass('tuwas');
	} else {
	  $('#handover_to').html(msg);
	  $('#contactto').removeClass('tuwas');
	}

        // form again
        //$('#submit_' + type).show();


	// add/modify select option
        var n = $('#saved_handover_no_' + type).html();
	var t = $('#saved_handover_text_' + type).html();
	var opt = $('#contact' + type + ' option');
        var modified = 0;

	// change existing
	for (var i = 1; i < opt.size(); ++i) {
	  if (n == opt.get(i).value) {
	    opt.get(i).text = t;
	    modified = 1;
	    break;
	    //alert(n + '->' + opt.get(i).value);
	  }
	}
	// add new
	if (n && !modified) {
	  $('#contact' + type).append('<option selected="selected" value="' + n + '">' + t + '</option>');
	  
	}
        //alert(n + '|' + t);
	// check if complete
	if ($('#contactfrom').val() > 0 && $('#contactto').val() > 0) {
	  //alert("form complete - would submit now");
	  next_step_show();
	}

     }
   });
}

//////////////////////////////////////////////////////////////////////
// calculate total packaging (booking)
//////////////////////////////////////////////////////////////////////

function calc () {
  //alert("calc");
  var total=0;
  $("input.calculate").each(function (i) { total += parseInt(this.value) || 0; });
  $("#number_total").val(total);
  if (total>0) next_step_show()
  else next_step_hide();
}

//////////////////////////////////////////////////////////////////////
// show send password dialog
//////////////////////////////////////////////////////////////////////

function sendpassword () {
  $('.sendpassword').toggle();
}

//////////////////////////////////////////////////////////////////////
// date and time picker (booking)
//////////////////////////////////////////////////////////////////////

function update_slider (no,which,e) {
  //alert(e);
  //$("#timeslider" + no).sliderMoveTo(40,null,1,false,1);
  var v = e.value;
  if (v.match(/^\d?\d:\d\d$/)) {
    var t = v.split(":");
    //alert(t[0] + ':' + t[1]);
    var num = parseInt(2 * (parseInt(t[0]) + parseInt(t[1]) / 60));
    //alert(num);
    $('#timeslider' + no).sliderMoveTo(num, null, null, null, which);
    $('#slider'+no+ (which?'b':'a')).val(num);
  } else {
    e.value='';
  }
}

function format_time(e) {
  var h = parseInt(e / 2);
  var m = (e - 2 * h) * 30;
  var d = ((h<10) ? '0' + h : h) + ":" + ((m<10) ? '0' + m : m);
  return d;
}

function create_slider(no) {
  // this requires a patched version of ui.slider.js (moveto for multiple sliders)
  // see bug 1938:  http://dev.jquery.com/ticket/1938
  $('#timeslider' + no).slider({ 
        steps: 48,
	//minValue: 0,
	//maxValue: 48,
	min: 0,
	max: 48,
        range: true,
        startValue: $('#slider'+no+'a').val(), // moveto only works once (see below)
	//startValue: [ $('#slider'+no+'a').val(), $('#slider'+no+'b').val() ],
	slide: function(e,ui) { 
                     
	  $("#timestart" + no).val(format_time($('#timeslider' + no).slider('value', 0))); 
	  $("#timeend" + no).val(format_time($('#timeslider' + no).slider('value', 1))); 
	  $('#slider'+no+'a').val($('#timeslider' + no).slider('value', 0));
	  $('#slider'+no+'b').val($('#timeslider' + no).slider('value', 1));
          // show alert if to - from < 4 hrs
	  if (ui.range < 3.9) $('#timeerror' + no).show() 
	  else $('#timeerror' + no).hide() 
      }
  });

  // move to initial position - moveto only works once (see below)
  //$('#timeslider' + no).slider("moveTo", $('#slider'+no+'a').val(), 0);
  $('#timeslider' + no).slider("moveTo", $('#slider'+no+'b').val(), 1);
  $("#timestart" + no).val(format_time($('#slider'+no+'a').val())); 
  $("#timeend" + no).val(format_time($('#slider'+no+'b').val())); 
}

function create_datepicker(id) {

  $(id).datepicker({
        showOn: 'button',
	minDate: +1,//start_date,
	buttonText: 'Calendar',
	buttonImageOnly: true, 
	buttonImage: 'images/icons/icn-calendar.png',
	firstDay: 1,
	dateFormat: 'yy-mm-dd',
	speed: ''
        //onSelect: function(dateText) { if ($('#pickupdate').val() ) $('#next_step').show(); } 
    });
}

//////////////////////////////////////////////////////////////////////
// send personal message
//////////////////////////////////////////////////////////////////////

function send_message () {

  var params = $('#sendmsgform').serialize();

  //alert(params);

  $.ajax({

     url: "ajax_send_msg.asp",
     data: params,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

        //if (type == "from") {
        //  $('#handover_from').html(msg);
	//} else {
	//  $('#handover_to').html(msg);
	//}

	//alert(msg);
        $('#sendmsg').hide();
	$('#sendmsgresult').html(msg).show();
	

     }
   });

  return false;

}

//////////////////////////////////////////////////////////////////////
// show/hide budget details
//////////////////////////////////////////////////////////////////////

function show_budget_details (e) {
  var t = $(e).parent().next().next('tr.more');
  if ($(t).is(':visible')) {
    $('img' ,e).attr('src', 'images/icons/icn-right.png');
  } else {
    $('img' ,e).attr('src', 'images/icons/icn-down.png');
  }
  $(t).toggle();
}

//////////////////////////////////////////////////////////////////////
// edit supplier/contacts
//////////////////////////////////////////////////////////////////////

function edit_supplier (sup_id) { 

  $.ajax({

     url: "ajax_edit_supplier.asp",
     data: "SUP_ID=" + sup_id,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	//alert( "Data: " + msg );
        $('#supplier').html(msg);
     }
   });

}

function save_supplier (sup_id, cancel) {

  // hide submit button
  //$('#submit_' + type).hide();

  var params = $('#supplier :input').serialize();
  var org_name = $('#supplier :input[name=company_name]').val(); // need below
  //alert(org_name);

  if (cancel) {
    params = "cancel=yes";
  }

  $.ajax({

     url: "ajax_save_supplier.asp",
     data: "SUP_ID=" + sup_id + "&" + params,

     success: function(msg){

        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}

	$('#supplier').html(msg);

	// update name in select list
        $('#form_sup_id option').each(function() {
	  if ($(this).val() == sup_id) {
	    $(this).html(org_name);
          }
	});
        //alert(sup_id);

     }
   });

}

// does not work
// function crop_images () {
//   $('div.imgcrop img').each( function() { 
//     //var w = this.width;
//     var w = $(this).width();
//     var l = parseInt((w-100)/2);
//     alert(w + " - " + l);
//     if (l > 0) $(this).css('left','-' + l + 'px'); 
//   });
// }

function show_contact (cont_id,sup_id) {
 
   if ($("tr.contactdetails").length) {
     // remove rows
     $("tr.contactdetails").remove();
     $("#contacts span.contact_role").show();
     $("#contacts span.contact_edit").hide();
     $('#contacts tr').removeClass('strong');
   }

   $.ajax({
       
     url: "ajax_view_contact.asp",
     data: "CONT_ID=" + cont_id + "&SUP_ID=" + sup_id,

     success: function(msg){
 
	 if (msg == "Session expired") { 
	   window.location.href="advancedlogin.asp?last=fail";
	   return;
	 }
	    
	 //alert( "Data: " + msg );

	 // insert result
	 $('#contact_' + cont_id).after(msg);
	 $('#contact_' + cont_id).addClass('strong');
	 if ($('#edit_' + cont_id).size()) {
	   $('#role_' + cont_id).hide();
	   $('#edit_' + cont_id).show();
	 }
	 //crop_images();
      }
    });
}

function edit_contact (cont_id,sup_id) {
 
   $.ajax({
       
     url: "ajax_edit_contact.asp",
     data: "CONT_ID=" + cont_id + "&SUP_ID=" + sup_id,

     success: function(msg){
 
	 if (msg == "Session expired") { 
	   window.location.href="advancedlogin.asp?last=fail";
	   return;
	 }
	    
	 //alert( "Data: " + msg );
	 // insert result
	 if ( cont_id ) {
	   $('#contact_' + cont_id).next('.contactdetails').replaceWith(msg);
	 } else {
	   // new contact
           $("tr.contactdetails").remove();
	   $("#contacts span.contact_role").show();
	   $("#contacts span.contact_edit").hide();
	   $('#contacts tr').removeClass('strong');
	   $('#contact_lastrow').before(msg);
	 }

	 //$('#contact_' + cont_id).addClass('strong');
	 //if ($('#edit_' + cont_id).size()) {
	 //  $('#role_' + cont_id).hide();
	 //  $('#edit_' + cont_id).show();
	 //}

      }
    });

}

function save_contact_success (cont_id,msg) {
        if (msg == "Session expired") { 
	  window.location.href="advancedlogin.asp?last=fail";
	  return;
	}
        //alert(msg);
	//alert($(msg).children('tbody').children('tr').html());
	if ( cont_id ) {
	  $('#contact_' + cont_id).next('.contactdetails').replaceWith($(msg).children('tbody').children('tr'));
	 } else {
	   // new contact
           $("tr.contactdetails").remove();
	   $("#contacts span.contact_role").show();
	   $("#contacts span.contact_edit").hide();
	   $('#contacts tr').removeClass('strong');
	   $('#contact_lastrow').before($(msg).children('tbody').children('tr'));
	 }
}


// function save_contact (cont_id,sup_id,cancel) {
 
//   var params = $('#contacts :input').serialize();

//   if (cancel) {
//     params = "cancel=yes";
//   }

//    $('#contactsf').ajaxSubmit({

//       url: "ajax_save_contact.asp",
//       data: "CONT_ID=" + cont_id + "&SUP_ID=" + sup_id + "&" + params,

//       success: function(msg){

//          if (msg == "Session expired") { 
//  	  window.location.href="advancedlogin.asp?last=fail";
//  	  return;
//  	}

//  	 if ( cont_id ) {
//  	   $('#contact_' + cont_id).next('.contactdetails').replaceWith(msg);
//  	 } else {
//  	   // new contact
//             $("tr.contactdetails").remove();
//  	   $("#contacts span.contact_role").show();
//  	   $("#contacts span.contact_edit").hide();
//  	   $('#contacts tr').removeClass('strong');
//  	   $('#contact_lastrow').before(msg);
//  	 }

//       }
//     });

//    $.ajax({

//       url: "ajax_save_contact.asp",
//       data: "CONT_ID=" + cont_id + "&SUP_ID=" + sup_id + "&" + params,

//       success: function(msg){
//          if (msg == "Session expired") { 
//  	  window.location.href="advancedlogin.asp?last=fail";
//  	  return;
//  	}

//  	 if ( cont_id ) {
//  	   $('#contact_' + cont_id).next('.contactdetails').replaceWith(msg);
//  	 } else {
//  	   // new contact
//             $("tr.contactdetails").remove();
//  	   $("#contacts span.contact_role").show();
//  	   $("#contacts span.contact_edit").hide();
//  	   $('#contacts tr').removeClass('strong');
//  	   $('#contact_lastrow').before(msg);
//  	 }

//       }
//     });

// }

// fin



