var ie = (navigator.appName == "Microsoft Internet Explorer") ? true : false;

/* extend the date object to add a day-of-year method. */
Date.prototype.getDOY = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
}

function pageLoad(){
  /* Remove all empty text nodes from the dom tree. */
  RemoveTextNodes(document,true);

  Event.observe($('dsShowMe'), 'mouseover', rollover);
  Event.observe($('dsShowMe'), 'mouseout', rollover);
  Event.observe($('bbShowMe'), 'mouseover', rollover);
  Event.observe($('bbShowMe'), 'mouseout', rollover);
  Event.observe($('selectCity'), 'change', showPanels);
}

/* Hide any element */
function hide(elem) {
  elem = $(elem);
  if(! elem.hasClassName('invisible'))
    elem.addClassName('invisible');
}

/* Unhide an element */
function show(elem) {
  elem = $(elem);
  if(elem.hasClassName('invisible'))
    elem.removeClassName('invisible');
}

/* Toggle the highlighting on rollover items */
function rollover(e){
  if(navigator.userAgent.indexOf('Opera') >= 0) { return; }
  e = (typeof(event) == 'undefined') ? e : event;
  var elem = $(Event.element(e));
  if(elem.hasClassName('norm')) {
    elem.removeClassName('norm');
    elem.addClassName('over');
  }else{
    elem.removeClassName('over');
    elem.addClassName('norm');
  }
}

function showPanels(){
  if($('selectCity').selectedIndex == '0')
    hide('descriptionDiv');
  else show('descriptionDiv');
}

function showDS(){
  var city = $('selectCity').value;
  $('selectCity').selectedIndex = 0;
  hide('descriptionDiv');
  $('dsShowMe').removeClassName('over');
  $('dsShowMe').addClassName('norm');
  document.location = 'DailySpecials.php?city='+city;
}

function showBB(){
  var city = $('selectCity').value;
  $('selectCity').selectedIndex = 0;
  hide('descriptionDiv');
  document.location = 'BulletinBoard.php?city='+city;
}

function dbWrite(msg){
  var d = $('debug');
  if(msg == 'RESET'){
    d.innerHTML = '';
  }else if(msg == 'CLOSE'){
    d.innerHTML = '';
    hide(d);
  }else{
    show(d);
    msg = d.innerHTML+"<br />"+msg;
    if(msg.length > 400) msg = msg.substr(100);
    d.innerHTML = msg;
  }
}

function limitTA(e){
  e = (typeof(event) == 'undefined') ? e : event;
  var elem = $(Event.element(e));
  var limit;
  if(elem.id == 'bbAdBody') limit = 286;
  else limit = 175;
  if(elem.value.length > limit) {
    elem.value = elem.value.substr(0, limit);
  alert('Maximum of '+limit+' characters.');
  }else{
    preview(elem.id);
  }
}

function preview(e){
  if(typeof(e) == 'string'){
    elem = $(e);
  }else{
    e = (typeof(event) == 'undefined') ? e : event;
    var elem = $(Event.element(e));
  }
  if($(elem.id+'Cel'))
    $(elem.id+'Cel').innerHTML = elem.value;
}

function toggleType(e) {
  e = (typeof(event) == 'undefined') ? e : event;
  var elem = $(Event.element(e));
  var toShow = elem.value;
  var toHide = (toShow == 'DS') ? 'BB' : 'DS';
  hide(toHide);
  if(toShow == 'BB'){
    hide('dsEntries');
    hide('dsEntriesSub');
    hide('dsStartDateLabel');

    $('dsCategory').selectedIndex = 0;
    $('dsOfferType').selectedIndex = 0;
    $('dsAdDuration').selectedIndex = 0;
    $('dsStartDate').selectedIndex = 0;
    $('logoCB').checked=false;
    $('logoFile').clear();
    $('logoFile').disable();
    $('monTA').value=''; preview('monTA');
    $('tueTA').value=''; preview('tueTA');
    $('wedTA').value=''; preview('wedTA');
    $('thuTA').value=''; preview('thuTA');
    $('friTA').value=''; preview('friTA');
    $('satTA').value=''; preview('satTA');
    $('sunTA').value=''; preview('sunTA');

    show('bbEntries');
    show('bbEntriesSub');
    show('bbStartDateLabel');
    bbUpdate();
  }else{
    hide('bbEntries');
    hide('bbEntriesSub');
    hide('bbStartDateLabel');

    $('bbCategory').selectedIndex = 0;
    var index = $('bbStartMonth').selectedIndex;
    if(index != '') {
      $('bbStartMonth').selectedIndex = 0;
      $('bbStartDay'+index).selectedIndex = 0;
    }
    $('bbDuration').value = 0;

    show('dsEntries');
    show('dsEntriesSub');
    show('dsStartDateLabel');
    dsUpdate();
  }
  show(toShow);
  show('sendBtn');
  updatePrice();
}


function bbUpdate() {
  var sourceAry = new Array(
    'city',
    'bbCategory',
    'businessName',
    'address',
    'phone',
    'bbAdTitle',
    'bbAdBody',
    'webAddress'
  );
  var targetAry = new Array(
    'bbCityCel',
    'bbCategoryCel',
    'bbBusinessNameCel',
    'bbAddressCel',
    'bbPhoneCel',
    'bbAdTitleCel',
    'bbAdBodyCel',
    'bbWebAddressCel'
  );

  sourceAry.each(function(item,i) {
    var source = $(item);
    var target = $(targetAry[i]);

    if(item == 'webAddress') {
      if($('webAddressCB').checked) {
        target.innerHTML = source.value;
        var url = $(item).value;
        $('bbWebAddressCel').href = url;
      }
    }else{
      target.innerHTML = source.value;
    }
  });
}

function dsUpdate() {
  var sourceAry = new Array(
    'city',
    'dsCategory',
    'businessName',
    'address',
    'dsOfferType',
    'webAddress',
    'phone',
    'monTA',
    'tueTA',
    'wedTA',
    'thuTA',
    'friTA',
    'satTA',
    'sunTA'
  );
  var targetAry = new Array(
    'cityCel',
    'dsCategoryCel',
    'businessNameCel',
    'addressCel',
    'dsOfferTypeCel',
    'webAddressCel',
    'phoneCel',
    'monTACel',
    'tueTACel',
    'wedTACel',
    'thuTACel',
    'friTACel',
    'satTACel',
    'sunTACel'
  );

  sourceAry.each(function(item,i) {
    var source = $(item);
    var target = $(targetAry[i]);
    var logoLine = "\n<img id=\"logoImg\" src=\"./images/logoHere.jpg\" alt=\"Logo Here\" />\n";

    if(item == 'webAddress') {
      if(!$('webAddress').disabled) {
        var url = $(item).value;
        target.innerHTML = '<a href="'+url+'">'+logoLine+"</a>\n";
        target.innerHTML = target.innerHTML + '<p><a href="'+url+'">(click to visit)</a></p>';
      }else{
        target.innerHTML = logoLine;
      }
    }else{
      target.innerHTML = source.value;
    }
  });
}


function updateAll() {
  dsUpdate();
  bbUpdate();
}

function enableURL(){
  var webAddress = $('webAddress');
  webAddress.disabled = !webAddress.disabled;
  updatePrice();
  pv();
}

function enableFile(){
  $('logoFile').disabled = !$('logoFile').disabled;
  $('logoFile').value = '';
}

function pv(){
  if(!$('DS').hasClassName('invisible')){
    dsUpdate();
  }else if(!$('BB').hasClassName('invisible')) {
    bbUpdate();
  }
}

function validate(){
  /* ################################# Returning Customer With Valid ID ########################################### */
  if($('customerID')) {
    $pageType = 'DS';
    if($('customerID').value == '') {
      alert("You must provide your customer ID number.\nThis is the number that was provided to you when you purchased your advertising space.");
      return false;
    }

    if($('businessName').value == '') {
      alert("You must provide the name of your business.");
      return false;
    }

    if($('dsOfferType2').value == '') {
      alert('You must select a Type of Offer.\nThis is a general descriptor that helps users quickly see what you are offering.');
      return false;
    }
  }else{
  /* ########################################### New Customer #################################################### */
    if($('contactName').value == ''){
      alert('You must provide a contact name.\nThis is the name of the person we will attempt to contact should an issue arise.');
      return  false;
    }

    if($('city').value == ''){
      alert('You must choose a city.\nAds are displayed by city on our site.');
      return  false;
    }

    var phone = $('phone').value;
    if($('phone')) {
      if (phone == '') {
        alert("You must provide a phone number.\nThis is the number we will call should any issue arise.");
        return false;
      }else{
        var regex = /^(\([2-9]\d{2}\)|[2-9]\d{2}) *[-]{0,1} *\d{3} *[-]{0,1} *\d{4}$/;
        if(! regex.exec(phone)) {
          alert('The phone number you entered does not appear to be a valid number.');
          return  false;
        }
      }
    }

    var email1 = $('email1').value;
    var email2 = $('email2').value;
    if(email1 == '') {
      alert('You must provide an email address.\nThis is the email address to which your payment confirmation will be sent.\nRemember that both email addresses must be the same.');
      return false;
    }else if(email1 != email2) {
      alert('You must enter two identical email addresses.\nThis is the email address to which your payment confirmation will be sent.');
      return false;
    }else{
      regex = /^[0-9a-zA-Z]+([_.-][0-9a-zA-Z]+)*@[0-9a-zA-Z]+([_.-]{0,1}[0-9a-zA-Z]+)*[.]{1}[a-zA-Z]{2,4}$/;
      if(! regex.exec(email1)) {
        alert("The email address you entered does not appear to be a valid email address.");
        return false;
      }
    }

    if($('webAddressCB').checked){
      var webAddress = $('webAddress');
      if(webAddress.value == ''){
        alert('You indicated that you wanted to add a link to your ad,\nbut you did not provide a URL for the link.');
        return false;
      }else{
        var regex = /^http[s]{0,1}:\/\//;
        if(! regex.exec(webAddress.value)){
          var answer = confirm("The URL for your web address must begin with one of the following:\n http:// for a normal website\nor\nhttps:// for an SSL or encrypted website.\n\nWe can add 'http://' for you:\n\nhttp://"+webAddress.value+"\n\nIs this correct?");
          if(answer) webAddress.value = 'http://'+webAddress.value;
          else return false;
        }
      }
    }

    var radioDS = $('radioDS').checked;
    var radioBB = $('radioBB').checked;
    if((radioDS == false) && (radioBB == false)){
      alert('Do you want to purchase a Daily Special Ad or a Bulletin Board Ad.');
      return false;
    }else if(radioDS == true) {
  /* ########################################### DS Customer #################################################### */
      $pageType = 'DS';
      if($('logoCB').checked){
        var logoFile = $('logoFile');
        if(logoFile.value == ''){
          alert('You indicated that you wanted to upload a logo file,\nbut you did not provide the file.');
          return false;
        }
      }
      if($('fileError').value == "error"){
        alert("An error occurred while uploading your logo file.  Please ensure that your file is\na JPG file, and that it is less than 200K in size.");
      }
      if($('dsCategory').value == '') {
        alert('You must select a Daily Special Category.\nThis determines the section of our site in which your ad will be displayed.');
        return false;
      }
      if($('dsOfferType').value == '') {
        alert('You must select an Type of Offer.\nThis is a general descriptor that helps users quickly see what you are offering.');
        return false;
      }
      if($('dsStartDate').value == '') {
        alert('You must select an Ad Start Date.\nThis is the Monday on which your ad will first appear.');
        return false;
      }
      if($('dsAdDuration').value == '') {
        alert("You must choose your Ad Duration.\n This determines how long your account will remain active\nand how much it will cost.");
        return false;
      }
    }else{
  /* ########################################### BB Customer #################################################### */
      $pageType = 'BB';
      if($('bbCategory').value == '') {
        alert('You must select a Bulletin Board Category.\nThis determines the section of our site in which your ad will be displayed.');
        return false;
      }
      var bbStartMonth = $('bbStartMonth').value;
      var index = $('bbStartMonth').selectedIndex;
      var bbStartDay = $('bbStartDay'+index).value;
      if((bbStartMonth == '') || (bbStartDay == '')) {
        alert('You must select a month and a day for your Ad Start Date.\n.');
        return false;
      }else{
/*
        var months = new Array( 'Jan.', 'Feb.', 'Mar.', 'Apr.', 'May.', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.');
        var dateStr = $('date').value;
        var date = dateStr.split(':');
        var thisDay = date[0];
        var thisMonthNum = date[1];
        var thisYear = date[2]; thisYear++; thisYear--;
        var nextYear = thisYear+1;
        for(i=0; i<12; i++){ if(months[i] == bbStartMonth) break; }
        var startMonthNum = i;

        var today = new Date(thisYear,thisMonthNum,thisDay);
        var startDate = new Date(thisYear,startMonthNum,bbStartDay);

        var todayNum = today.getDOY();
        var startNum = startDate.getDOY();
        var diff = startNum - todayNum;

        if(diff < 0) {
          var bbStart = bbStartMonth+" "+bbStartDay;
          answer = confirm(bbStart+" has already passed.\nDid you mean "+bbStart+" of "+nextYear+'?');
          if(answer){
            thisYear++;
            nextYear++;
            var startDate = new Date(thisYear,startMonthNum,bbStartDay);
          }else return false;
        }
*/
      }

      var bbDuration = $('bbDuration').value;
      if(bbDuration == ''){
        alert("You must enter the duration of your Ad.\nThis is the number of days you want your add to run.");
        return false;
      }else{

      }
      if($('bbAdTitle').value == '') {
        alert('You must provide a title for your ad.\nThis is one of the first things users will look at on your ad.');
        return false;
      }
      if($('bbAdBody').value == '') {
        alert('You must provide the body of your ad.\nDescribe what you are offering in three lines or less.');
        return false;
      }
    }
  }

  /* ############################################ Check Specials for DS and update ############################# */
  if($pageType == 'DS'){
    valid = false;
    if($('monTA').value != '') valid = true;
    else if($('tueTA').value != '') valid = true;
    else if($('wedTA').value != '') valid = true;
    else if($('thuTA').value != '') valid = true;
    else if($('friTA').value != '') valid = true;
    else if($('satTA').value != '') valid = true;
    else if($('sunTA').value != '') valid = true;
    if(!valid){
      alert('You have not entered any specials. \nYou must enter a special for at least one day.');
      return valid;
    }
  }

  return true;
}

function createAdLoad(){
  RemoveTextNodes(document,true);
  Event.observe($('bbStartMonth'), 'change', setPullDown);
  pv();
}

function setPullDown(){
  var bbStartMonth = $('bbStartMonth');
  var bbIndex = bbStartMonth.selectedIndex;
  if(bbIndex == 1)      { 
    $('bbStartDay2').selectedIndex = 0;
    $('bbStartDay3').selectedIndex = 0;
    hide('bbStartDay2'); 
    hide('bbStartDay3');}
  else if(bbIndex == 2) { 
    $('bbStartDay1').selectedIndex = 0;
    $('bbStartDay3').selectedIndex = 0;
    hide('bbStartDay1'); 
    hide('bbStartDay3');}
  else                  { 
    $('bbStartDay1').selectedIndex = 0;
    $('bbStartDay2').selectedIndex = 0;
    hide('bbStartDay1'); 
    hide('bbStartDay2');}
  show('bbStartDay'+bbIndex);
}

function updatePrice(){
  var price;
  var duration;
  var discount;
  if(!$('dsEntries').hasClassName('invisible')){
    duration = $('dsAdDuration').value;
    price = $('dsAdDuration').value * 95.00;
    if(duration >= 6){ 
      price = price - (price*.1);
    }
    if(!$('webAddress').disabled) price += 15.00;
    show('totalPrice');
  }else if (!$('bbEntries').hasClassName('invisible')) {
    duration = $('bbDuration').value;
    if(duration > 31) price = duration * 2.50;
    else if((duration > 27) && (duration <= 31)) price = 75.00;
    else if((duration > 20) && (duration <= 27)) price = duration * 2.8571;
    else if((duration > 13) && (duration <= 20)) price = duration * 3.2142;
    else if((duration > 6) && (duration <= 13)) price = duration * 4.00;
    else price = duration * 5.00;
    show('totalPrice');
  }else{
    price=0.00;
    hide('totalPrice');
  }
  price = Math.round(price * 100)/100;
  var totalPrice = $('totalPrice');
  totalPrice.innerHTML = 'Your total advertising cost is <strong>$'+price+'</strong>.';
  $('priceField').value = price;
}

function resetFileError(){
  $('fileError').value = '';
}
