var RXOK;
var P;
var EDSTEP;

function set_base_p(newbaseP)
{
  P = newbaseP;
}
function base_p()
{
  return P;  
}
function set_ed_step( step )
{
  EDSTEP = step;
}

function test_rx(field, rx, matches, correction){
  var RX = new RegExp(rx);
  var searchresult = field.value.search(RX);

  if( (matches && searchresult == -1 ) ||
      (!matches && searchresult != -1)){

    //we've failed the test.

    //see if we have any correction code
    if(correction){
        
        var str = field.value;
        var old_value = str;
        eval(correction);
        field.value = str;
        if( field.onkeyup ){
            field.onkeyup();
        }
      
        if( str != old_value && field.onchange ){
            field.onchange();
        }

        if(f_tx_after_update)
        {
            f_tx_after_update();
        }

        // check again to see if correction resolved our issues..
        searchresult = field.value.search(RX);
        if( (matches && searchresult != -1 ) ||
            (!matches && searchresult == -1)){
            return true;
        }
    }
    return false;
  }
  
  return true;
}

function switch_regex_indicator( thing, mode ){

    var is_fld = thing.getAttribute('fid');
    var fld_id = thing.getAttribute('fid');
    var del_id = thing.getAttribute('delid');
    var ri_id;
    
    if( is_fld ){
        ri_id = 'i2field_' + fld_id + '_ri';
    }
    else{
        ri_id = 'txtfld_' + del_id + '_ri';
    }

    if(document.getElementById( ri_id ))
    {
        document.getElementById( ri_id ).className = 'regex_indicator regex_' + mode ;
    }

    var info = new Object();

    info.is_fld = is_fld;
    info.del_id = ( del_id || '' );
    info.fld_id = ( fld_id || '' );
    
    return info;
}

function regex_set_failure(thing){

    var info = switch_regex_indicator( thing, 'fail' );

    aj_sndReq('evaluateRXFail',
              '&delid=' + info.del_id +
              '&fld_id=' + info.fld_id +
              '&val=' + encodeUri(thing.value) + "&p=" + P);

    RXOK=false;
}
function regex_set_success(thing){

    var info = switch_regex_indicator( thing, 'ok' );

    if( info.is_fld ){
        document.getElementById( 'flderr_' + info.fld_id).innerHTML = '';
        document.getElementById( 'flderr_' + info.fld_id).display = 'none';
    }
    else{
        document.getElementById('txterr_' + info.del_id).innerHTML
            = '';
        document.getElementById('txterr_'+ info.del_id).style.display
            = 'none';
    }
}
function run_edit_checks(){
	var fields_to_check = document.getElementsByTagName('input');
  var i;
  RXOK=true;

  if( pause_ip_updates ){
      pause_ip_updates();
  }

  for (i = 0; i < fields_to_check.length; i++){
    formElement = fields_to_check[i];
    if( ! formElement ){ continue }
    if((formElement.nodeName=="INPUT"||
       formElement.nodeName=="SELECT" ||
       formElement.nodeName=="TEXTAREA")
       && ( formElement.getAttribute('petf') == 1 ||
            formElement.getAttribute('pef') )){
        plog( "considering " + formElement );
      if( formElement.getAttribute('petf')
          && formElement.getAttribute('eallowd') != 1
          && formElement.value.length == 0)
      {
        regex_set_failure(formElement)
      }
      else
      {
          if( formElement.getAttribute('petf') && 
              !(formElement.getAttribute('field') > 0) )
          {
              formElement.onblur();
          }
          else{
              if( formElement.onchange ){
                  formElement.onchange();
              }
          }
      }
      
    }
  }

  if( pause_ip_updates ){
      resume_ip_updates();
  }

  return RXOK;
}

//Also in order.js - Needs rationalising!
function apply_rx(rx, field, matches, correction_code)
{
  var str = field.value;
  var match = str.match(rx);

  if(str.length == 0){return true;}

  if ( str.length > 0 &&
      ((matches && ! match)
      || (!matches &&  match)))
  {
    if(correction_code.length > 0){
      try{
        eval(correction_code);
        field.value = str;

        // try again, but with no correction code:
        return apply_rx( rx, field, matches, '' );
      }
      catch(e){
        alert('Problem with correction code. Please contact technical support and quote code "EDIT_ORDER_RX1". :\n\r' + e);
        return false;
      }
    }
    else{
       return false;
    }
  }
  else {
     return true;
  }
}

function store_form(formid, variablename)
{
  eval("window." + variablename + " = new Object();");
  var toform = window.document.getElementById(formid);
  
  copyFormDataTo(toform, eval("window." + variablename));
}
function check_saved_form(formid, variablename)
{
  var variable = eval("window." + variablename);
  if(variable)
  {
    window.ed_doing_local_restore = true;
    copyFormDataFrom(window.document.getElementById(formid), variable);
    window.ed_doing_local_restore = false;
  }
}

function save_stuff(extra_params)
{
  var mods = window.mods;
  var mod_count = mods.length;
  var request_str = '&p=' + P;
  var missing = [];

  if(window.editor_store_me)
  {
    window.editor_store_me();
  }
  for(var i = 0; i < mod_count; i++)
  {
    var mod = mods[i];
    var variable = eval(mod);
    
    if(variable != undefined)
    {
      request_str += storedFormToQString( variable );      
    }
    else
    {
      missing.push(mod);     
    }
    
  }
  if(extra_params)
  {
    request_str += extra_params;
  }
  
  request_str += '&missing=' + encodeUri(missing.join(','));
  
  aj_sndReq('saveStuff', request_str);
}

function build_big_qs(options){
  var opts = options || {};
  var mods = window.mods;
  var mod_count = mods.length;
  var qs = '';
  if(window.editor_store_me)
  {
    window.editor_store_me();
  }
  
  for(var i = 0; i < mod_count; i++)
  {
    var mod = mods[i];
    var variable = eval(mod);
    
    if(variable)
    {
      qs += storedFormToQString(variable);
    }
  }

  if( window.ed_extra_big_qs_code )
  {
    qs += window.ed_extra_big_qs_code();
  }
  
  if(! opts.nopersist)
  {
    qs += '&p=' + P;
  }


    
  
  return qs;
}

function focus_form()
{
  var forms = document.getElementById('editor').getElementsByTagName('form');


  if(forms.length > 0)
  {
    var fels = forms[0].elements;
    

    for(var i=0; i < fels.length; i++)
    {
      if(fels[i].type != 'hidden' && fels[i].style.visibility != 'hidden' && fels[i].style.display != 'none'
         && fels[i].name && ! fels[i].disabled )
      {
        fels[i].focus();
        break;
      }
    }
  }
  
}
var uihttp;

// Bundle up all the fields and send a request for a new image
function update_image_preview(ono, options)
{
    var now = new Date();

    if( ! window.irq ){
        window.irq = {}    
    }

    window.irq.last_call = now;

    if( ! window.irq.running && ! window.irq.qcheck ){
        window.irq.running = true;
        window.irq.runtime = now;
        return _uip( ono, options )
    }
    else{
        if( ( now.valueOf() - window.irq.runtime.valueOf() ) > 35000  )
        {
            // timeout
            plog('irq: image req timeout');
            window.irq.running = false;
            if( window.irq.qcheck ){
                clearInterval(window.irq.qcheck);                
                window.irq.qcheck = false;
            }
            return update_image_preview( ono, options );
        }
        if( ! window.irq.qcheck ){

            window.irq.qcheck = 
                setInterval(
                    function(){
                        var inow = new Date();
                        var ms_since_lastreq = ( inow.valueOf() - 
                                                 window.irq.last_call.valueOf() );

                        if( ms_since_lastreq >= 1000 && ! window.irq.running ){

                            window.irq.running = false;
                            clearInterval(window.irq.qcheck);
                            window.irq.qcheck = false;
;                           return update_image_preview( ono, options );
                        }
                    },
                    1000
                );
        }
    
    }
}

function _uip( ono, options ){
  var imgload;
  var tid;
  var inputs = document.getElementsByTagName('input');
  imgload = new Image();

  var design_prefix = '/design/';
  var store_request = new Array('o=' + ono,
                                'png=1',
                                'applymods=1',
                                'saneidx=1',
                                'store=1');

  if(document.getElementById('image_loading_message'))
  {
    document.getElementById('image_loading_message').style.display = 'block';
  }

  if( window.editor_store_me && window.editor_store_me != 'undefined' ){
      editor_store_me()
   }
    
  var qs = '';

  if( window.ip_prefix ){
      var i;
      for( i = 0; i< window.ip_prefix.length; i++ ){
          var param = window.ip_prefix[i];
          qs += '&' + encodeUri( param.key ) + '=' +  encodeUri( param.val );
      }
  }
  if( window.ip_auth ){
      qs += '&auth=' + window.ip_auth;
  }  
  qs += build_big_qs( {"nopersist": 1} );

  if(options && options.gfxoverride)
  {
    var ovr = options.gfxoverride;
    var gfxno, value;
    while( (gfxno = ovr.shift()) && (value = ovr.shift()) )
    {
        store_request.push('gel_' +  gfxno + '=' + value);
    }
  }
 if( options && options.gs
      || window.ip_std_options && window.ip_std_options.gs )
  {
      store_request.push( 'force_engine=ghost' );
  }
  store_request.push(qs);

  if(uihttp)
  {
    uihttp.abort();
    uihttp = false;
  }
  
  uihttp = ip_createRequestObject();
  uihttp.open('POST', design_prefix, true);
  uihttp.onreadystatechange = function(){

    if(uihttp.readyState == 4){

      var xmldoc = uihttp.responseXML;
      if(!xmldoc) return;
      if(!uihttp.responseText) return;
       
      var success = xmldoc.getElementsByTagName('result');
      var token = xmldoc.getElementsByTagName('token');

      if( (success.length != 1 || aj_extract_content( success[0] ) != 'success')
          || (token.length != 1 || ! aj_extract_content(token[0]).match(/\d+/)) )
      {
        alert("Sorry, there's been an error making your image preview. Please try again later.\r\nContact technical support if this error persists." + uihttp.responseText);
        if(document.getElementById('image_loading_message'))
        {
          document.getElementById('image_loading_message').style.display =
            'none';
        }
          window.irq.running = false;
          uihttp = false;
      }
      else
      {
          var surl = design_prefix + '?png=1&stored=' +
          aj_extract_content(token[0]) + '&o=' + ono;;
          if( options && options.gs
              || window.ip_std_options && window.ip_std_options.gs )
          {
              surl += '&force_engine=ghost';
          }
          if( window.ip_auth ){
              surl += '&auth=' + window.ip_auth;
          }
          imgload.src = surl;
        tid = setInterval(function (){
              
            if(imgload.complete)
            {
              clearInterval(tid);
              var pageImage;
              
              if( ! options || !options.img)
              {
                pageImage = document.getElementById("image_preview");
              }
              else
              {
                pageImage = options.img;
              }
              pageImage.src = imgload.src;              
              
              if(pageImage.ownerDocument.getElementById('image_loading_message'))
              {
                pageImage.ownerDocument.getElementById('image_loading_message').style.display='none';
              }

                window.irq.running = false;
                
            }
          }, 1 );
      }     
    }
    
  };
  uihttp.setRequestHeader('Content-Type',
                          'application/x-www-form-urlencoded; charset=UTF-8');
  uihttp.send(store_request.join('&'));
}

function before_leave()
{
  if(window.editor_leave_js)
  {
    return window.editor_leave_js();    
  }
  return;  
}


function check_step()
{
  document.getElementById('feedbackgap').innerHTML = '';
  
  if(window.editor_check_js)
  {
    for(var i=0; i < window.editor_check_js.length; i++)
    {      
      if(!window.editor_check_js[i]())
      {
        var pb;
        
        if((pb = document.getElementById('b_placeorderbutton'))
          && pb.disabled)
        {
          pb.disabled = false;
        }
        
        return false;
      }
    }
  }
  
  return true;  
}

function error_feedback(err)
{
    _feedback( err, 'error' );
}

function info_feedback( msg )
{
    _feedback( msg, 'feedback' );
}

function _feedback( msg, className){
    var fbg;
    var new_fb_div = document.createElement('div');
    new_fb_div.className = className;
    new_fb_div.innerHTML = msg;
    if( (fbg = document.getElementById('feedbackgap') ) && fbg.appendChild)
    {
        fbg.appendChild( new_fb_div );
    }
    return true;
}


function add_check_js(check_callback)
{
  if(!window.editor_check_js)
  {
    window.editor_check_js = [check_callback];
  }
  else
  {
    window.editor_check_js.push(check_callback);
  }
}
function get_extra_args()
{
  if(!window.editor_extra_args)
  {
    return '';    
  }
  else
  {
    return  window.editor_extra_args();
  }  
}


function goto_step(step, extra_args, back, params)
{
  before_leave();
  if(back || check_step())
  {
    var more_args = '';

    // currently we assume args are forward only...
    if(!back) 
    {
      more_args = get_extra_args();
    }
    if(window.editor_store_me)
    {
      window.editor_store_me();
      window.editor_last_store_me = window.editor_store_me;
    }

    if( params && params.build_qs )
    {
      more_args += build_big_qs();
    }
    
//    window.editor_store_me = false;
    if( window.ie_stage_style )
    {
      window.ie_stage_style.cssText = ''
    }
    
    var go = function(){ aj_sndReq(step, '&p=' + P + (extra_args || '') +
                                   more_args);}

    if( window.before_step_ajax ){
        window.after_bsa = go;
        window.before_step_ajax();
        return;
    }

    go();
  }
}

function ask_step( step, params )
{
  var extrastuff = '';
  
  if(params && params.args)
  {
    extrastuff += params.args;
  }
  if( params && params.form_to_qs ){
      extrastuff += formToQSById( params.form_to_qs )
  }
  
  aj_sndReq( step, '&p=' + P + extrastuff );
}

function ask_this_step( params )
{
  ask_step( EDSTEP, params );
}

function plugin_request( pluginid, params )
{
    if( ! params ){ params  = {} }

    if(window.editor_store_me)
    {
      window.editor_store_me();
      window.editor_last_store_me = window.editor_store_me;
    }

    aj_sndReq( 'editor:plugin', '&p=' + P 
               + '&pluginid=' + pluginid  + (
                   params.params ? params.params : '' )
              + ( params.formToQS ? formToQSById( params.formToQS )
                                  : '' 
                ));
}

function update_gfx_select(newgfx, extra)
{
  var selecta = document.getElementById('gfx_picker_frame');
  var old_selected, gel;

  if(old_selected = document.getElementById(selecta.getAttribute('selected_gfx_id')))
  {
    
    old_selected.className
      =  old_selected.className.replace(' gfx_selected', '');
  }
  
  if(gel = document.getElementById('gel_' + selecta.getAttribute('gel_id')))
  {
    //single image mode
    gel.value =  newgfx.getAttribute('path');

    if(gel_var = document.getElementById('gel_variation_' +
                                         selecta.getAttribute('gel_id')))
    {
      gel_var.value = newgfx.getAttribute('var');
    }

    if( editor_store_me ){ editor_store_me() }
  }

  newgfx.className += ' gfx_selected';
  selecta.setAttribute('selected_gfx_id', newgfx.id);
}

function update_tx_field_focus(tx, options)
{
  var current = document.getElementById('text_fields').currentSelected;
  var diy_panel = document.getElementById('diy_panel');
  var id = tx.getAttribute('delid');

  // this will have to pick up hints from template if we go more dymamic.
  // in which case this func. should become dynamic or embedded in the layout
  tx.parentNode.parentNode.className += ' selected';
  document.getElementById('text_fields').currentSelected = tx;

  if(current)
  {
    current.parentNode.parentNode.className = current.parentNode.parentNode.className.replace('selected', '');
  }

  
  if( diy_panel && (current != tx || (options && options.forced) ))
  {

    var dat = document.getElementById('texel_diy_data_' + id);
    if(dat){
        var diy_fields = dat.getElementsByTagName('input');
        qs = new Array();

        qs.push('txfld=' + id);
    
        for(var i=0; i<diy_fields.length; i++)
        {
            var el = diy_fields[i];
            qs.push(el.name + '=' + encodeUri(el.value));
        }
        var guts;
	
        if((guts = document.getElementById('diy_panel_guts'))){
            guts.innerHTML = 'Loading...';
        }
        if( diy_panel.style.display != 'block' )
        {
            diy_panel.style.display = 'block';      
        }
        aj_sndReq('editor:EditFrame', '&p=' + P + '&diy_req=update_diy_pane&' + qs.join('&'));
    }
    else{
        // no dat means no DIY for this field!
        diy_panel.style.display = 'none';      
    }
  }
}

function update_attribute_field(control, tx, att, callback)
{
  var id = tx.getAttribute('delid');
  
  var fld = document.getElementById('txtfld_' + att + '_' + id);
  if(fld)
  {
    fld.value = callback(control, fld, tx);
    if( f_tx_after_update )
    {
      f_tx_after_update();
    }
  }
  else
  {
    throw("Print evolved editor couldn't find attribute field for " + att);
  }
}

function tx_toggle_func(control, field, txtfld, applet_callback){
  var val = (field.value == 1 ? 0 : 1);
  var name = control.getAttribute('name');
  var oldClass = val ? name : name + '_selected';
  var newClass = val ? name + '_selected' : name;
  
  do_tx_field(txtfld, applet_callback, val ? -1 : 0);
  control.className = control.className.replace(oldClass, newClass);
  
  return val;
}
function tx_select_palette_func(control, field, txtfld, callback)
{
  var val = control.getAttribute("save_val");
  var app_val = control.getAttribute("app_val");
  var siblings = control.parentNode.childNodes;

  for(var i=0; i<siblings.length; i++)
  {
    var sibling = siblings[i];
    if(sibling == control){continue;}
    
    sibling.className = sibling.className.replace(" palette_selected", "");
  }
  control.className += " palette_selected";
  
  do_tx_field(txtfld, callback, app_val);

  return val;
}

function tx_toggle_composite(control, field, txtfld, applet_callback){
  var siblings = control.parentNode.childNodes;
  var name = control.getAttribute('name');
    
  for(var i=0; i<siblings.length; i++)
  {
    var sibling = siblings[i];
    var sibName = sibling.getAttribute('name');

    if(sibling == control){ continue;}
    
    sibling.className = sibling.className.replace(new RegExp( sibName + '_selected$'), sibName);
  }
  control.className = control.className.replace(new RegExp(name + '$'), name + '_selected');
  
  do_tx_field(txtfld, applet_callback, control.getAttribute('value'));
  return control.getAttribute('value');
}

function order_receipt_email_change()
{
  var ore = document.getElementById( 'EMAIL' );
  var receipt_checkbox = document.getElementById( 'order_receipt_checkbox' );
  
  if ( ore.value.length > 0  ) 
  {
    receipt_checkbox.disabled = false;
    if ( receipt_checkbox.unchecked_by_js ) 
    {
      receipt_checkbox.checked = true;
      receipt_checkbox.unchecked_by_js = false;
    }
   }
  else
  {
    receipt_checkbox.disabled = true;
    if( receipt_checkbox.checked )
    {
      receipt_checkbox.checked = false;
      receipt_checkbox.unchecked_by_js = true;
    }
  }
}

function ed_add_mod( mod )
{
  for( var i = 0; i < window.mods.length ; i++ ){
    if( window.mods[i] == mod ){
      return  
    }
  }
  return window.mods.push( mod );
}

