// -- IMPORTANT -- ///////////////////////////////////////
// No Smurfs were killed in the writing of this code.   //
//////////////////////////////////////////////////////////

// Handle all the FSCommand messages in a Flash movie.
function locationFlash_DoFSCommand(command, args) {
  var locationFlashObj = window.ie ? document.all.locationFlash : document.locationFlash;
  if (command == "evalJs") {
    var stateRegex = "(-?\\d)\\|([\\w\\s]+)";
    var nameRegex = "\\'[\\w_]+\\'";
    var cookieName = args.match(nameRegex)[0].replace(/'/g,'');
    var cookieVal = args.match(stateRegex)[0];
    if ($chk(cookieVal) && $chk(cookieName))
    {
      Cookie.set(cookieName, cookieVal, {path: '/', duration: 180});
      window.location.href = window.location.href;
    }
  }
}

//window.addEvent("domready", function() {
//});

function SetRegionCookie(cookieName, cookieValue, cookiePath, cookieDuration)
{
  if ($chk(cookieValue) && $chk(cookieName))
  {
    Cookie.set(cookieName, cookieValue, {path: '/', duration: 180});
    window.location.href = window.location.href;
  }
}

function setFocus(aForm){
  if (aForm.elements[0] != null) {
   var i;
   var max = aForm.length;
   for( i = 0; i < Math.min(4,aForm.elements.count); i++ ) {
    if (aForm.elements[ i ].type == "text" && !aForm.elements[ i ].disabled && !aForm.elements[ i ].readOnly ) {
      aForm.elements[ i ].focus();
      break;
    }
   }
  }
} 

// overrides the transitions on the built-in toolips
window.addEvent("domready", function() {

  if ($chk(document.forms[0]))
    setFocus(document.forms[0]);

  $$('.onesec').each(enableSubmit); // class '.onesec' displays none - for form buttons to stop early submit
  
    var tipsArray = [];
    // Use this to populate the tipsArray.
    // Will take any element that accepts a title attribute.
    $$("img").each(function(a) {
        if ($chk(a.getProperty("title")) && a.getProperty("title").test("::")) tipsArray.push(a);
    });
    var tips;
    tipsArray.each(function(item, index) {
        tips = new Tips(tipsArray[index], {
          initialize:function(){
            this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 250, wait: false}).set(0);
          },
          onShow: function(toolTip) {
            this.fx.start(1);
          },
          onHide: function(toolTip) {
            this.fx.start(0);
          }
        });
    });
    tips = null;
});

function addFlashData(obj) {
 
    // Each one of these is read in as obj.addVariable(name: value) by SWFObject
    var flashVars = new Hash({
        'baseUrl': '/Browse/',
        'easyProfessionalID': '1',
        'easyTradesID': '2',
        'easyRetailID': '3',
        'easyProfessionalName': 'Professional',
        'easyTradesName': 'Trade',
        'easyRetailName': 'Retail'
    });

    // Each one of these is read in as obj.addParam(name: value) by SWFObject
    var flashParams = new Hash({
        'wmode': 'transparent'
    });
    flashVars.each(function(value, key) {
        this.addVariable(key, value);
    }.bind(obj));
    flashParams.each(function(value, key) {
        this.addParam(key, value);
    }.bind(obj));
}

function enableSubmit(item, ix)
{
  item.removeClass('onesec');
}

// writes a countdown of characters in the passed in textbox to the passed in div
var TextBoxCounter = new Class({
  initialize: function(txtBox, cntDiv, maxCount) {
    if ($chk($(txtBox)) && $chk($(cntDiv))) {
      this.txt = $(txtBox);
      this.div = $(cntDiv);
      this.max = maxCount.toInt();
      this.txt.addEvent('keyup' , this.checkLength.bind(this));
      // and init it
      this.checkLength();
    }
  }

 ,checkLength: function() {
    var txt = this.txt.getProperty( 'value');
    if (txt.length >= this.max) { 
      this.txt.setProperty('value' , txt.slice(0, this.max));
      this.div.setText('all ' + this.max + ' chars used');
    } else {
      this.div.setText((txt.length) + ' of ' + this.max + ' chars used' );
    }
  }
});


// writes a countdown of characters in the passed in textbox to the passed in div
function ClientCheckABN(source, args){
  txtABN = $(source.id.replace('cvABN', 'txtABN'));
  var digitsSpacesOnlyRegex = '[^\\d\\s]+';
  //console.log(!txtABN.getValue().test(digitsSpacesOnlyRegex));
  //console.log(ValidateACNABN(txtABN.getValue()));
  args.IsValid = !txtABN.getValue().test(digitsSpacesOnlyRegex) && ValidateACNABN(txtABN.getValue());
}

function ValidateContact(eml, tel, mob, fax)
{
  return (eml != '') || (tel != '') || (mob != '') || (fax != '');
}

// returns true if the passed string is a valid ABN/ACN
function ValidateACNABN(txt)
{
  var ABN = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
  var ACN = [8, 7, 6, 5, 4, 3, 2,  1];
  var sum = 0, res = 0;
  var val = txt.replace(/[^\d]/g,''); // replace out any spaces or non-digits
  var digits = $A(val);
  digits.each(function(item,ix){ digits[ix] = item.toInt(); });
  var ret = false;
  switch (digits.length)
  {
    case 0:
      ret = true;
      break;
    case 9: // its an ACN - http://www.asic.gov.au/asic/asic.nsf/byheadline/Australian+Company+Number+(ACN)+Check+Digit?opendocument
      for (ix = 0; ix < digits.length; ix++)
        sum += ACN[ix] ? digits[ix] * ACN[ix] : 0;
      ret = (digits.getLast().toInt() === (10 - (sum % 10)));
      break;
    case 11: // its an ABN - http://www.ato.gov.au/businesses/content.asp?doc=/Content/13187.htm
      for (ix = 0; ix < digits.length; ix++)
        sum += ABN[ix] ? (ix == 0 ? digits[ix] - 1 : digits[ix]) * ABN[ix] : 0;
      ret = ((sum % 89) === 0);
      break;
    default:
      ret = false;
      break;
  }
  return ret;
}

// returns true is the passed strings make a valid austrlian postcode ala wikipedia 2007-Nov
function ValidatePostcode(postcode, state){

  if (!postcode.test(/[\d]{3,4}/))
    return false;

  retVal = false;
  
  postcode = postcode.toInt();
  state = state.toInt();
  
  switch (state) {
    case 1:
      retVal = (postcode >= 1000 && postcode <= 1999)
            || (postcode >= 2000 && postcode <= 2599)
            || (postcode >= 2620 && postcode <= 2898)
            || (postcode >= 2921 && postcode <= 2999)
            || postcode == 2611 || postcode == 3500 
            || postcode == 3585 || postcode == 3586 
            || postcode == 3644 || postcode == 3707;
      break;
    case 2:
      retVal = (postcode >= 4000 && postcode <= 4999)
            || (postcode >= 9000 && postcode <= 9999);
      break;
    case 3:
      retVal = (postcode >= 5000 && postcode <= 5999);
      break;
    case 4:
      retVal = (postcode >= 3000 && postcode <= 3999)
            || (postcode >= 8000 && postcode <= 8999);
      break;
    case 5:
      retVal = (postcode >= 6000 && postcode <= 6797)
            || (postcode >= 6800 && postcode <= 6999)
            || postcode ==  872;
      break;
    case 6:
      retVal = (postcode >=  800 && postcode <=  999)
            || postcode ==  872;
      break;
    case 7:
      retVal = (postcode >= 7000 && postcode <= 7999);
      break;
    case 8:
      retVal = (postcode >=  200 && postcode <=  299)
            || (postcode >= 2600 && postcode <= 2619)
            || (postcode >= 2900 && postcode <= 2920)
            || postcode == 2620;
      break;
  }
  return retVal;
}



var lastcolumn = "";
var isIE=window.clientInformation?true:false;
var isN4=document.layers?true:false;
var isN6=navigator.appName=="Netscape"&&parseInt(navigator.appVersion)>=5;
var isO5=navigator.userAgent.indexOf("Opera")!=-1&&parseInt(navigator.appVersion)>=4;
var ie=document.all!=null&&!isO5;

function hover(me) {
  if (me.className.indexOf("hover")>=0) {
    me.className = me.className.replace("hover","").replace(" hover","");
  } else {
    me.className = me.className + " hover";
  }
}