/*
############################################################################
#
# Part of the Jones Soda site code
# Copyright (C) 2006-09 Damon Harper
# usrbin design + programming - http://usrbin.ca/
#
# This program is governed by the agreed upon license between Damon Harper
# d.b.a. usrbin design + programming, and AMG Media Inc.  This program may
# be modified for internal use but may not be sold or otherwise distributed
# without express written permission from the copyright holder.
#
############################################################################
*/

function isDef(o) {
  return typeof(o)!='undefined';
}
function isStr(o) {
  return typeof(o)=='string';
}
function isBool(o) {
  return typeof(o)=='boolean';
}

function getById(id) {
  if(!isStr(id))
    return id;
  if(document.getElementById)
    return document.getElementById(id);
  if(document.all)
    return document.all[id];
  return null;
}

function getByClass(classname, node, tag) {
  if(node==null)
    node=document;
  if(tag==null)
    tag='*';
  var elements=new Array();
  var idx=0;
  var e=node.getElementsByTagName(tag);
  var re=new RegExp("(^|\\s)"+classname+"(\\s|$)");
  for(var i=0; i<e.length; i++) {
    if(re.test(e[i].className)) {
      elements[idx]=e[i];
      idx++;
    }
  }
  return elements;
}

function getByTagName(tag, node) {
  if(node==null)
    node=document;
  return node.getElementsByTagName(tag);
}

function hasClass(node, classname) {
  var re=new RegExp("(^|\\s)"+classname+"(\\s|$)");
  return re.test(node.className);
}

function addClass(node, classname) {
  var re=new RegExp("(^|\\s)"+classname+"(\\s|$)");
  if(!re.test(node.className))
    node.className+=(node.className ? ' ' : '')+classname;
}

function delClass(node, classname) {
  var re=new RegExp("(^|\\s)"+classname+"(\\s|$)", 'g');
  if(node.className)
    node.className=node.className.replace(re, ' ').replace(/^\s+/, '').replace(/\s+$/, '').replace(/\s{2,}/, ' ');
}

function toggle_blocks() {
  var message='';
  var matchclass=new RegExp("^(show|hide)if(not)?-([^=\\s]+)=(\\S*)$");
  var blocks=getByClass("(show|hide)if(not)?-\\S+");
  for(var i=0; i<blocks.length; i++) {
    var show='undef';
    var classes=blocks[i].className.split(/\s+/);
    for(var j=0; j<classes.length; j++) {
      var matches=matchclass.exec(classes[j]);
      if(matches) {
        var type=matches[1];
        var want=matches[2] ? false : true;
        var control=matches[3];
        var value=matches[4];
        message+=control+' '+type+' '+value+'\n';
        if(show=='undef')
          show=type=='hide';
        var obj=getById(control);
        var button;
        if(obj && obj.tagName=='SELECT') { // workaround for IE
          if((obj.options[obj.selectedIndex].value==value)==want)
            show=type!='hide';
        } else if(button=getById(control+'='+value)) {
          if((button && button.checked)==want)
            show=type!='hide';
        } else if(obj) {
          if((obj.value==value)==want)
            show=type!='hide';
        }
      }
    }
    if(show && show!='undef')
      blocks[i].style.display=blocks[i].tagName=='SPAN' ? 'inline' : 'block';
    else
      blocks[i].style.display='none';
  }
}

(function($){
  $(document).ready(function() {
    toggle_blocks();
  });
})(jQuery);

function spinner(id, adjustment, min, max) {
  var node;
  if(node=getById(id)) {
    var val=parseInt(node.value);
    if(!val) val=0;
    val+=adjustment;
    if(val<min)
      val=min;
    else if(val>max)
      val=max;
    node.value=val;
  }
}

function please_wait(timeout, id) {
  if(!id)
    id='please-wait';
  if($('#'+id).length && !$('#blackout-mask').length) {
    var please_wait_function=function() {
      if(typeof document.body.style.maxHeight==="undefined") { //IE6
        $('body','html').css({height: '100%', width: '100%'});
        $('html').css('overflow', 'hidden');
        $('body').append('<iframe id="zoom-iefix"></iframe>');
      }
      $('body').append('<div id="blackout-mask"></div>');
      $('#'+id).css({display: 'block'});
    };
    if(timeout)
      window.setTimeout(please_wait_function, timeout);
    else
      please_wait_function();
  }
}

function focus_first_input() {
  $(document).ready(function() {
    document.forms['default'].elements[0].focus();
  });
}

// zoom images
(function($) {
  $.fn.extend({
    zoom_image: function(zoom_src, zoom_width, zoom_height, o) {
      o=$.extend({
        link_text: 'Start order'
      }, o);
      if(zoom_src && zoom_width && zoom_height) {
        return this.each(function() {
          $(this).css({'cursor': 'pointer'});
          $(this).bind('click', function() {
            if(!$('#blackout-mask').length) {
              if(typeof document.body.style.maxHeight==="undefined") { //IE6
                $('body','html').css({height: '100%', width: '100%'});
                $('html').css('overflow', 'hidden');
                $('body').append('<iframe id="zoom-iefix"></iframe>');
              }
              $('body').append('<div id="blackout-mask"></div><div id="zoom-box"><div id="zoom-close"></div><img id="zoom-image" />'+(o.link_url ? '<a id="zoom-link"></a>' : '')+'</div>');
              $('#blackout-mask,#zoom-close').click(kill_zoom);
              if(o.link_url)
                $('#zoom-image').css({'cursor': 'pointer'}).click(function() {
                  document.location=o.link_url;
                });
              else
                $('#zoom-image').click(kill_zoom);
              $(document).bind('keydown', zoom_key);
            }
            $('#zoom-box').css({marginLeft: '-'+parseInt((zoom_width/2),10)+'px', width: zoom_width+'px'});
            if(!($.browser.msie && $.browser.version<7)) //non-IE6
              $('#zoom-box').css({marginTop: '-'+parseInt((zoom_height/2),10) + 'px'});
            $('#zoom-image').attr('src', zoom_src).css({
              width: zoom_width,
              height: zoom_height
            });
            if(o.link_url)
              $('#zoom-link').attr('href', o.link_url).attr('innerHTML', o.link_text);
            $('#zoom-close').attr('innerHTML', o.title ? o.title : '&nbsp;');
            $('#zoom-box').css({display: 'block'});
            function kill_zoom() {
              $('#zoom-box').fadeOut('fast', function(){
                $('#zoom-box,#blackout-mask,#zoom-iefix').trigger('unload').unbind().remove();
              });
              if(typeof document.body.style.maxHeight=="undefined") { //IE6
		$('body','html').css({height: 'auto', width: 'auto'});
		$('html').css({overflow: ''});
              }
              $(document).unbind('keydown', zoom_key);
              return false;
            }
            function zoom_key(e) {
              kill_zoom();
              return false;
            }
          });
        });
      }
    }
  });
})(jQuery);


/* ############################################################################
 * # frontend
 */

function toggle_image_source() {
  toggle_blocks();
  $('#image-source-file-input').attr('value', '');
}

function countlines(max_lines, max_chars, input, output_lines, output_chars) {
  $(document).ready(function(){
    input=$('#'+input);
    output_lines=$('#'+output_lines);
    output_chars=$('#'+output_chars);
    if(input.length && output_lines.length && output_chars.length) {
      var timeout_count_action=false;
      function count_action() {
        try {
          if(timeout_count_action) {
            clearTimeout(timeout_count_action);
            timeout_count_action=false;
          }
          var lines=0;
          var chars=0;
          var total_chars=0;
          for(var c=0; c<input.attr('value').length; c++) {
            var ch=input.attr('value').charCodeAt(c);
            if(ch==0x0a) {
              lines++;
              chars=0;
            } else if(ch!=0x0d) {
              chars++;
              total_chars++;
              if(chars>max_chars) {
                lines++;
                chars=0;
              }
            }
          }
          if(chars>0)
            lines++;
          var prefix=lines>max_lines ? '<span style="color: #ff0000;">' : '';
          var suffix=lines>max_lines ? '</span>' : '';
          $(input).get(0).countlines_error=lines>max_lines;
          output_lines.attr('innerHTML', prefix+lines+suffix);
          output_chars.attr('innerHTML', prefix+total_chars+suffix);
        } catch(e) {
        }
      }
      function count_action_timeout() {
        if(!timeout_count_action)
          timeout_count_action=setTimeout(count_action, 500);
      }
      count_action();
      input.bind('change', count_action);
      input.bind('blur', count_action);
      input.bind('keyup', count_action_timeout);
    }
  });
}

function add_flavour_input() {
  var n=0, node;
  do {
    node=getById('flavour'+n);
    if(node && node.style.display=='none') {
      node.style.display='block';
      n++;
      break;
    }
    n++;
  } while(node);
  if(!getById('flavour'+n))
    getById('flavour-more').style.display='none';
}

function recalculate_cases() {
  var total=0, n=0, node;
  do {
    node=getById('flavour'+n);
    if(node) {
      var add=parseInt(getById('cases'+n).value);
      if(add) total+=add;
    }
    n++;
  } while(node);
  getById('cases-total').innerHTML=total;
}

function frontend_setup(o) {
  o=$.extend({
    form: 'frontend-form',
    labeltext_input: 'labeltext',
    labeltext_count: true,
    labeltext_output_lines: 'lines',
    labeltext_output_chars: 'chars',
    labeltext_spellcheck: true
  }, o);
  $(document).ready(function() {
    var on_form_submit=function() {
      if(o.step_labeltext) {
        if(o.labeltext_count && $('#'+o.labeltext_input).get(0)['countlines_error']) {
          alert('Your label text is too long. Maximum is '+o.labeltext_lines+' lines of up to '+o.labeltext_chars+' characters each.');
          return false;
        }
        if(o.labeltext_spellcheck)
          sc_spellCheckers.resumeAll();
      }
      please_wait(1500);
      return true;
    };
    if($('#'+o.form).length)
      $('#'+o.form).submit(on_form_submit);
    if(o.step_image) {
      toggle_image_source();
    }
    if(o.step_labeltext) {
      if(o.labeltext_count)
        countlines(o.labeltext_lines, o.labeltext_chars, o.labeltext_input, o.labeltext_output_lines, o.labeltext_output_chars);
    }
    if(o.step_cases) {
      recalculate_cases();
    }
    if(o.step_bill_address)
      set_provinces('new-bill-country', 'new-bill-province');
    if(o.step_ship_address)
      set_provinces('new-ship-country', 'new-ship-province');
  });
}
