// index.php banner script 2011/08/09
var banners = {
  setup: function(items) {
    banners.current = 0;
    banners.items = items;
    banners.count = items.length;
    banners.link = $('#home_banner_link');
    banners.banner = $('#home_banner');
    $('div.home_banner_mitem').hover(
      function() { $(this).addClass('home_banner_mitem_hover'); },
      function() { $(this).removeClass('home_banner_mitem_hover'); }
    );
    
    banners.swap(0);
    banners.timer = setInterval(function(){ banners.swap(); },6000);
  },
  swap: function(n) {
    if (typeof n !== 'undefined' && n < banners.count) {
      clearInterval(banners.timer);
    } else { 
      n = (banners.current + 1) % banners.count;
    }
    banners.current = n;
    banners.banner.css('background-image','url('+banners.items[n].image+')');
    banners.link.unbind('click').click(function(){
      location.href = banners.items[n].link;
    });
  }
}

// turn urls in twitter posts into links
function make_twitter_links() {
  $('.mdi_tweet_text').each(function(){
    var html = $(this).text();
    html = html.replace(/(https?\:\/{2}[^\s]+)/,function(str, url){
      return '<a href="'+url+'" target="_blank">'+url+'</a>'
    });
    $(this).html(html)
  });
}

// teras page
function teras_guide(guide) {
  $('div.teras_guide_link').css('background-color','');
  $('div.teras_article').hide();
  $('div#teras_button_'+guide).css('background-color','#ddd');
  $('div#teras_brief_'+guide).show();
}

// image popup
function gallery(img,str) {
  var s = ""; 
  if (str != null && str != "") s = '<div style="margin: 5px;">'+str+'</div>';
  $("div#gallery_handle").html('') // first remove contents
    .append('<div class="gallery"><img src="'+img+'"/><br>'+s+'</div>') // create image
    .find('img').click(function(){ // make image click remove popup
      $("div#gallery_handle").html(''); // clear contents
    });
}


function setup_teras_config() {
  // configuration form
  // singleton
  var tcfg = {
    cgi_path: 'teras_rfq_form.php',
    
    // define fields
    title: 'Teras Tn1000p Portable SAN/NAS',
    lists: {},
    
    // clear the form values
    clear_form: function() {
      tcfg.dom['tcfg_contact_name'].val('');
      tcfg.dom['tcfg_contact_org'].val('');
      tcfg.dom['tcfg_contact_phone'].val('');
      tcfg.dom['tcfg_contact_email'].val('');
      tcfg.dom['tcfg_contact_application'][0].selectedIndex = 0;
      tcfg.dom['tcfg_contact_comments'].val('');
      tcfg.dom['tcfg_contact_newsletter'].attr('checked',false);
      tcfg.dom['tcfg_contact_reseller'].attr('checked',false);
      tcfg.dom['tcfg_base_system'][0].selectedIndex = 0;
      tcfg.dom['tcfg_storage_drives'][0].selectedIndex = 0;
      tcfg.dom['tcfg_extra_drives'][0].selectedIndex = 0;
      tcfg.dom['tcfg_io_devices'][0].selectedIndex = 0;
      tcfg.dom['tcfg_os_drives'][0].selectedIndex = 0;
      tcfg.dom['tcfg_operating_system'][0].selectedIndex = 0;
      tcfg.dom['tcfg_accessories'][0].selectedIndex = 0;
      tcfg.dom['tcfg_warranty'][0].selectedIndex = 0;
    },
    
    // html element handling
    ids: [  // element id list to be turned into handles
      // parts selection and display
      'tcfg_base_system', 'tcfg_base_system_button',  'tcfg_base_system_list',
      'tcfg_storage_drives', 'tcfg_storage_drives_button', 'tcfg_storage_drives_list',
      'tcfg_extra_drives', 'tcfg_extra_drives_button', 'tcfg_extra_drives_list',
      'tcfg_io_devices', 'tcfg_io_devices_button', 'tcfg_io_devices_list',
      'tcfg_os_drives', 'tcfg_os_drives_button', 'tcfg_os_drives_list',
      'tcfg_operating_system', 'tcfg_operating_system_button', 'tcfg_operating_system_list',
      'tcfg_accessories', 'tcfg_accessories_button', 'tcfg_accessories_list',
      'tcfg_warranty', 'tcfg_warranty_button', 'tcfg_warranty_list',
      // contact form
      'tcfg_contact_name', 'tcfg_contact_org', 'tcfg_contact_phone',
      'tcfg_contact_email', 'tcfg_contact_application', 'tcfg_contact_comments',
      'tcfg_contact_newsletter', 'tcfg_contact_reseller',
      'tcfg_contact_send_button', 'tcfg_contact_reset_button'
    ],
    classes: [ 'tcfg_parts_select', 'tcfg_contact_form', 'tcfg_config_sheet' ],
    
    // bootstrap methods
    setup: function(title, parts) {
      tcfg.title = title;
      tcfg.lists = parts;
      tcfg.setup_config();
      tcfg.setup_dom();
      tcfg.setup_form();
      tcfg.setup_binds();
      tcfg.show_config();
    },
    
    // setup the config object
    setup_config: function() {
      tcfg.counter = 0;
      tcfg.config = {};
      for (var id in tcfg.lists) { tcfg.config[id] = {}; }
    },
    
    // retrieve all of the DOM handles
    setup_dom: function() {
      tcfg.dom = {};
      for (var i=0, cnt=tcfg.ids.length; i < cnt; i++) {
        tcfg.dom[tcfg.ids[i]] = $('#'+tcfg.ids[i]);
      }
      for (var i=0, cnt=tcfg.classes.length; i < cnt; i++) {
        tcfg.dom[tcfg.classes[i]] = $('.'+tcfg.classes[i]);
      }
    },
    
    // populate form fields
    setup_form: function() {
      for (var id in tcfg.lists) {
        var section = tcfg.lists[id];
        var options = '';
        for (var i=0, cnt=section.options.length; i < cnt; i++) {
          options += '<option value="'+i+'">'+section.options[i]+'</option>';
        }
        tcfg.dom[id].html(options);
      }
    },
    
    // create event handlers
    setup_binds: function() {
      // click buttons to add to config sheet
      tcfg.dom['tcfg_parts_select'].delegate('button','click',function(){
        var button_id = $(this).attr('id');
        var select_id = button_id.substring(0, button_id.length - 7); // trim "_button"
        tcfg.select_part(select_id);
      });
      
      // On change, same effect as select
      tcfg.dom['tcfg_parts_select'].delegate('select','change',function(){
        var select_id = $(this).attr('id');
        if (!tcfg.lists[select_id].multiple) tcfg.select_part(select_id);
      });
      
      // submit button
      tcfg.dom['tcfg_contact_send_button'].click(tcfg.submit);
      
      // reset button
      tcfg.dom['tcfg_contact_reset_button'].click(tcfg.reset);
    },
    
    // form methods
    // select a part, takes the id of the part select box
    select_part: function(id) {
      if (!id || !tcfg.dom[id]) return false;
      var puid = tcfg.counter++;
      var select = tcfg.dom[id];
      var item = tcfg.lists[id].options[select.val()];
      var list = tcfg.dom[id + '_list'];
      // only one selection allowed, so clear it every time
      if (!tcfg.lists[id].multiple) { 
        tcfg.config[id] = {};
      } else if (tcfg.lists[id].limit && tcfg.count(tcfg.config[id]) === tcfg.lists[id].limit) {
        return;
      }
      // multiple selections allowed
      tcfg.config[id][puid] = item;
      tcfg.show_config();
    },
    
    // remove a part from the configuration
    remove_part: function(id, puid) {
      if (tcfg.config[id] && tcfg.config[id][puid]) {
        delete tcfg.config[id][puid];
        tcfg.show_config();
      }
    },
    
    // create a list to show the chosen configuration
    show_config: function() {
      for (var id in tcfg.lists) {
        var list = tcfg.dom[id+'_list'];
        var list_items = '';
        for (var opt in tcfg.config[id]) {
          var remove_link = '<a class="tcfg_remove" href="javascript:tcfg.remove_part(\''+id+'\','+opt+')" title="Remove this item">(X)</a>';
          list_items += '<li>'+tcfg.config[id][opt]+' '+remove_link+'</li>';
        }
        if (list_items === '') {
          if (tcfg.lists[id].required) {
            list_items = '<li><span style="color: #888; font-style: italic">(Please select one of the options above)</span></li>';
          } else {
            list_items = '<li><span style="color: #888; font-style: italic">(Not required)</span></li>';
          }
        }
        list.html('').html(list_items);
      }
    },
    
    // get the text body of the config sheet
    get_config_sheet: function() {
      var indent = '  ';
      var text = tcfg.title + "\n\n";
      for (var id in tcfg.config) {
        text += indent + tcfg.lists[id].title + "\n";
        for (var opt in tcfg.config[id]) {
          text += indent + indent + tcfg.config[id][opt] + "\n";
        }
        text += "\n";
      }
      return text;
    },
    
    // parse the whole form
    get_full_form: function() {
      // get form values
      var form = {
        'title': tcfg.title,
        'name': tcfg.dom['tcfg_contact_name'].val(),
        'organization': tcfg.dom['tcfg_contact_org'].val(),
        'phone': tcfg.dom['tcfg_contact_phone'].val(),
        'email': tcfg.dom['tcfg_contact_email'].val(),
        'application': tcfg.dom['tcfg_contact_application'].val(),
        'comments': tcfg.dom['tcfg_contact_comments'].val(),
        'newsletter': tcfg.dom['tcfg_contact_newsletter'].is(':checked') ? 'yes' : 'no',
        'reseller': tcfg.dom['tcfg_contact_reseller'].is(':checked') ? 'yes' : 'no'
      }
      
      var errors = '';
      // make a list of validation issues for the contact form
      if (form['name'] === '') { 
        errors += "- Please enter your name\n";
      }
      if (!( /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(form['email']) )) {
        errors += "- Please enter a valid e-mail address\n";
      }
      // make a list of validation issues for the parts list
      for (var opt in tcfg.lists) {
        if (tcfg.lists[opt].required && tcfg.is_empty(tcfg.config[opt])) {
          errors += "- "+tcfg.lists[opt].title+"\n";
        }
      }
      // stop the submission
      if (errors !== '') {
        alert("Please provide the information below:\n" + errors + "\n");
        return false;
      }
      
      // add system config
      form['config'] = tcfg.get_config_sheet();
      
      // confirm submission
      var ok = confirm("Are you sure you want to send this request?");
      return ok ? form : false;
    },
    
    // form submit button
    submit: function(){
      var rfq = tcfg.get_full_form();
      if (rfq === false) return;
      post_data = JSON.stringify({ 'rfq': rfq });
      
      // raw JSON POST
      $.ajax({
        type: "POST",
        url: tcfg.cgi_path,
        data: post_data,
        success: tcfg.message_sent,
        error: tcfg.message_failed,
        dataType: "json",
        contentType: "application/json",
        processData: false
      });
    },
    
    // submit messages
    success_message: 'The RFQ has been submitted, thank you!',
    fail_message: "We're sorry, but the RFQ could not be submitted.\n"+
                  "Please call or e-mail us directly, instead.\n"+
                  "We apologize for the inconvenience.",
    message_sent: function(data) {
      if (data['response'] === 'OK') alert(tcfg.success_message);
      else alert(tcfg.fail_message + "\n\nError: " + data['response']);
    },
    message_failed: function() {
      alert(tcfg.fail_message);
    },
    
    // form reset button
    reset: function(){
      tcfg.setup_config();
      tcfg.clear_form();
      tcfg.show_config();
    },
    
    // small utility functions
    is_empty: function(obj) { 
      if (obj == false || typeof obj !== 'object') return true; 
      for (var i in obj) return false; 
      return true;
    },
    // count obj properties
    count: function(obj) { var i=0; for (var x in obj) if (obj.hasOwnProperty(x)) i++; return i; }
  }
  
  // set this as a global
  window.tcfg = tcfg;
}

$(function(){
  
  // ie7 hack workaround z-index bug, re-index all divs
  var divs = document.getElementsByTagName('div');
  var len = divs.length; var n = 1000 + len;
  for (var i=0; i < len; i++) { divs[i].style.zIndex = n--; }

});


