
Event.observe(window, 'load', function() {
  initExternalLinks();
  initPrintLinks();
  filterOptions();
  togglePlayer();
  setupDynamicForm();
  setupNewsletterForm();
  new DhtmlFeature('feature', 'window', 'pips', 7);
  new toolTip('tooltip', 'tooltip');
  new toolTip('footerTooltip', 'footerTooltip'); 
});

function initExternalLinks() {
  ($$('a[rel="external"]')).each(function(elm) {
    elm.onclick = function() {
      window.open(this.href);
      return false;
    };
  });
}

function initPrintLinks() {
  ($$('a[rel="print"]')).each(function(elm) {
    elm.onclick = function() {
      window.print();
      return false;
    };
  });
}


function filterOptions() {
  if($('filterOptions')!= null && $('filterBrands')!= null ) {
    var height = $('filterBrands').getHeight()
    var selected = [];
    var subOptions = [];

    $$('#filterOptions input[type=checkbox]').each(function(elm) {
      elm.checked = false;
      Event.observe(elm, 'click',
        function() {
          
          if(this.checked && !this.up('li').hasClassName('newCars')) {
            select(this);
          } else if(!this.checked && !this.up('li').hasClassName('newCars')) {
            unSelect(this);
          }


          if(this.up('li').hasClassName('newCars') && this.checked) {
            select(this);
            $('filterBrands').setStyle({
              height: '0px',
              display: 'block'
            });

            new Effect.Morph($('filterBrands'), {
              style: 'height: ' + height + 'px;',
              duration: 0.4
            });

            new Effect.Fade($('filterBrands'), {
              duration: 0.4,
              from: 0,
              to: 1
            });

          } else if ( this.up('li').hasClassName('newCars') && !this.checked ) {
            unSelect(this);
            new Effect.Morph($('filterBrands'), {
              style: 'height: 0px;',
              duration: 0.4
            });

            new Effect.Fade($('filterBrands'), {
              duration: 0.4,
              from: 1,
              to: 0
            });

          }
        });

    });

    $$('#filterBrands input[type=checkbox]').each(function(elm) {
      elm.checked = false;
      Event.observe(elm, 'click',
        function() {
          if (this.checked) {
           this.up('li').addClassName('selected');
            if(subOptions.size() == 0 ) {
              $$('#djtvArticle .newCars li').each(Element.hide);
              $$('#djtvArticle .newCars .' + this.id).each(Element.show);
              subOptions.push(this);
            } else {
              $$('#djtvArticle .newCars .' + this.id).each(Element.show);
              subOptions.push(this);
            }
          } else {
            this.up('li').removeClassName('selected');
            if(subOptions.size() == 1 ) {
              $$('#djtvArticle .newCars li').each(Element.show);
              subOptions.pop();
            } else {
              $$('#djtvArticle .' + this.id).each(Element.hide);
              subOptions.pop();
            }
          }
        });
    });


    function select(elm) {
      elm.up('li').addClassName('selected');
      if(selected.size() == 0 ) {
        $$('#djtvArticle > div').each(Element.hide);
        $$('#djtvArticle .' + elm.id).each(Element.show);
        selected.push(elm);
      } else {
        $$('#djtvArticle .' + elm.id).each(Element.show);
        selected.push(elm);
      }
    }

    function unSelect(elm) {
      elm.up('li').removeClassName('selected');
      if(selected.size() == 1 ) {
        $$('#djtvArticle > div').each(Element.show);
        selected.pop();
      } else {
        $$('#djtvArticle .' + elm.id).each(Element.hide);
        selected.pop();
      }
    }



  }
}


function togglePlayer(){
  if($('player') != null) {
		
    var thumb = $('player').select('.videoThumb')[0];
    var close = $('player').select('.btn')[0];
    var player = $('videoPlayer');
	
    $$('#player .videoThumb').each(function(elm) {
      elm.onclick = function() {
        new Effect.Morph($('player'), {
          style: 'height: 447px; width: 728px; margin-bottom: 20px;',
          duration: 0.5
        });
        close.setStyle({
          display: 'block',
          opacity: '0'
        });
        new Effect.Fade(thumb, {
          duration: 0.3,
          from: 1,
          to: 0
        });
        new Effect.Fade(close, {
          duration: 0.3,
          from: 0,
          to: 1
        });
        player.setStyle({
          display: 'block',
          opacity: '0'
        });
        new Effect.Fade(player, {
          duration: 0.3,
          from: 0,
          to: 1
        });
        return false;
      }
    });
		
    $$('#player .btn').each(function(elm) {
      elm.onclick = function() {
        new Effect.Morph($('player'), {
          style: 'height: 95px; width: 99px; margin-bottom: 2px;',
          duration: 0.4
        });
        thumb.setStyle({
          display: 'block',
          opacity: '0'
        });
        new Effect.Fade(player, {
          duration: 0.3,
          from: 1,
          to: 0
        });
        new Effect.Fade(thumb, {
          duration: 0.3,
          from: 0,
          to: 1,
          afterFinish: function() {
            thumb.setStyle({
              display: 'block'
            });
          }
        });
        new Effect.Fade(close, {
          duration: 0.3,
          from: 1,
          to: 0
        });
        return false;
      }
    });
  }
}


function setupDynamicForm(selectedForm, anotherEmail) {
  var dynamicForm = $('dynamicForm');
  
  if(dynamicForm != null) {
    
    var feilds = dynamicForm.select('input, textarea');
    var errorFeilds = dynamicForm.select('.wwerr');
    selectedForm == undefined ? selectedForm = dynamicForm.className : dynamicForm.className = selectedForm
    $('dynamicForm_frm').value = selectedForm;

    dynamicForm.select('#formNav a').each(function(elm) {
      elm.onclick = function() {
        clearform();
        errorFeilds.each(Element.hide);
        var formType = this.up('li').className;
        selectedForm = formType;
        dynamicForm.className = formType;
        $('dynamicForm_frm').value = formType;
        return false;
      }
    });

    dynamicForm.select('input[type=reset]').each(function(elm) {
      elm.onclick = function() {
        clearform();
        return false;
      }
    });

    dynamicForm.select('#actionMessage a').each(function(elm) {
      elm.onclick = function() {
        dynamicForm.className = anotherEmail;
        $('dynamicForm_frm').value = anotherEmail;
        return false;
      }
    });

    Event.observe(dynamicForm, 'submit', function(e) {
      dynamicForm.request({
          parameters: {ajaxContext:'true'},
          onComplete: function(response) {
             dynamicForm.replace(response.responseText);
             $('actionMessage') != null ? setupDynamicForm('message', selectedForm) : setupDynamicForm(selectedForm)
          }
      });
      Event.stop(e); 
    });

    function clearform() {
      feilds.each(function(elm) {
        dynamicForm.select('input[type=text], textarea').each(function(elm){elm.value = '';});
        elm.checked = false;
    });
    
    }
  }
}


/* newsletter form */


function setupNewsletterForm() {
  if($('Newsletter') != null && $('footer') != null){
    var newsletter = $('Newsletter');

    Event.observe(newsletter, 'submit', function(e) {
    newsletter.request({
          parameters: {ajaxContext:'true'},
          onComplete: function(response) {
             var elm = new Element('div').update(response.responseText);
             $('newsletterField').clear();
             $('footer').className = elm.select('#footer')[0].className;
          }
      });
      Event.stop(e);
    });

    $$('#footer .result a, #footer .invalid a, #footer .error a').each(function(elm) {
      elm.onclick = function() {
        $('footer').className = '';
        return false;
      }
    });
  }
}

/* Home Page feature */


var DhtmlFeature = Class.create({
  initialize: function(featureId, windowId, pipsId, periodicalSlideTime) {
		
    if($(featureId) != null) {
      this.setupWindow(windowId);
      this.linkPipActions(pipsId);
      if(this.totalFeatures != this.totalPips) {
        throw ("Number of Pips does not match the number of features");
      }
			
      if(periodicalSlideTime != null && periodicalSlideTime != 0) {
        this.time = periodicalSlideTime;
        this.periodicalSlide(periodicalSlideTime);
      }
    }
		
  },
  setupWindow: function(window) {
	 	
    this.features = [];
    this.container = $(window).select('ul')[0];
    var position = 0;
		
    ($$('#' + window + ' li')).each(function(elm){
      elm.position = position;
      this.features.push(elm);
      position = position + elm.getWidth();
    }.bind(this));
		
    this.totalFeatures = this.features.size();
    $(this.container).setStyle({
      width: position + 'px'
    });
		
  },
  linkPipActions: function(pips) {
		
    this.pipList = $$('#' + pips + ' li');
    var selected = $$('#' + pips + ' .selected')[0];
    if(selected == undefined) {
      this.pipList[0].addClassName('selected');
      this.selected = this.pipList[0];
    } else {
      this.selected = selected;
    }
    this.totalPips = 0;
		
    ($$('#' + pips + ' li a')).each(function(elm, i){
      this.pipList[i].index = i;
      Event.observe(elm, 'mouseover', this.pipAction.bind(this));
      elm.onclick = function() {
        return true;
      }
      this.totalPips = i + 1;
    }.bind(this));
		
  },
  pipAction: function(e) {
		
    this.setSelected(Event.element(e).up('li').index);
    this.slideContent(this.features[Event.element(e).up('li').index].position);
		
    if (this.pe != null && this.pe != undefined) {
      this.pe.stop();
      this.periodicalSlide(this.time);
    }

  },
  periodicalSlide: function(time) {
		
    this.pe = new PeriodicalExecuter(function(pe) {
      var selectFeature = 0;
      if(this.selected.index + 1 != this.totalPips) {
        selectFeature = this.selected.index + 1;
      }
			
      this.slideContent(this.features[selectFeature].position);
      this.setSelected(selectFeature);
    }.bind(this), time);
		
  },
  slideContent: function(x) {
		
    if(this.myEffect != undefined){
      this.myEffect.cancel();
    }
    this.myEffect = new Effect.Move(this.container, {
      x: -x,
      y: 0,
      mode: 'absolute',
      duration: 0.5
    });
		
  },
  setSelected: function(index) {
		
    this.selected.removeClassName('selected');
    this.selected = this.pipList[index];
    this.pipList[index].addClassName('selected');
		
  }
});


/* ToolTip */


var toolTip = Class.create({
  initialize: function(actionClass, containerId) {
    this.tipMarkup(containerId);
    this.linkTip(actionClass);
    
  },
  tipMarkup: function(containerId) {
    this.toolTip = new Element('span', {
      id: containerId,
      style: 'display: none'
    });
    $$('body')[0].insert({
      bottom: this.toolTip
    });
  },
  linkTip: function(actionClass){
    $$('.' + actionClass).each(function(elm){
      if (elm.title != '' && elm.title != null) {
        Event.observe(elm, 'mouseenter', this.showToolTip.bind(this));
        Event.observe(elm, 'mouseleave', this.hideToolTip.bind(this));
      }
    }.bind(this));
  },
  showToolTip: function(e) {
    
    elm = Event.element(e).up('a');
    if(elm == undefined) {
      elm = Event.element(e);
    } //IE bug fix
    this.toolTip.update(elm.title);
		
    Event.observe(elm, 'mousemove', function(e) {

      this.toolTip.setStyle({
        position: 'absolute',
        zindex: '300',
        top: Event.pointerY(e) + 'px',
        left: Event.pointerX(e) + 15 + 'px'
      });
			
    }.bind(this));
		
    this.toolTip.show();
  },
  hideToolTip: function() {
    this.toolTip.hide();
  }
});


/* Sifr */


var dj = {
  src: assetsPath + 'Gill_Sans.swf'
};
sIFR.activate(dj);
sIFR.replace(dj, {
  selector: '#section-home h2',
  css: '.sIFR-root { color: #0B2A75;font-weight: bold;letter-spacing: -1; }',
  transparent: true,
  forceSingleLine: true,
  tuneWidth: '10px'
});


/* Google Maps/Lightwindow */


var map = null;
var geocoder = null;
var address = null;
var addressd = null;



var myLightWindow = null;
function initLightWindow() {
  myLightWindow = new lightwindow({
    contentOffsetMargin: {
      width: 60
    },
    overlay: {
      opacity: 0.7,
      image: imagesPath + 'bg_lightwindow.png'
    },
    postProcess: function(link) {
      if($('map') != null) {
        if(link != undefined) {
          locationMap(link);
        }
      }

      if($('calculator') != null) {
        calculator();
      }
    }
  });
}

function calculator() {

  var monthly =  $('monthly');
  var total =  $('total');

  String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
  }

  Event.observe($('clear'), 'click', function() {
    updateRepayment(0, 0);
  });
  
  $('calculate').onclick = function() {
    var financed = $('cal_financed').value;
    var rate = $('cal_rate').value;
    var term = $('cal_term').value;

    if(isNaN(financed) || isNaN(rate) || isNaN(term) || financed.trim() == '' || rate.trim() == '' || term.trim() == '' ){
      alert('Please fill out all the fields correctly.');
      return null;
    }

    rate = (rate/100) / 12;

    var top = rate*financed;
    var bottom = (1-Math.pow((1+rate),(-term)));
    var Payments = top/bottom;

    updateRepayment(Payments.toFixed(2), (Payments*term).toFixed(2));

    return false;
  }

  function updateRepayment(monthlyAmt, totalAmt) {

    monthly.update('$' + monthlyAmt);
    total.update('$' + totalAmt);

    monthly.setStyle({'color': '#9dfd96'});
    total.setStyle({'color': '#9dfd96'});

    new Effect.Morph(monthly, {style: 'color: #fff;', duration: 0.6 });
    new Effect.Morph(total, {style: 'color: #fff;', duration: 0.6 });

  }
}

function locationMap(address) {

  var mapTypeSelected = $('btn_map');

  if (GBrowserIsCompatible()) {
    setupButtons();
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(-33.72671920,151.05000598), 15);
    geocoder = new GClientGeocoder();
    if (geocoder) {
      geocoder.getLatLng(
        address,
        function(point) {
          if (!point) {
            alert(address + " not found");
          } else {
            map.setCenter(point, 15);
            var marker = new GMarker(point);
            map.addOverlay(marker);
            marker.setImage(imagesPath + 'btn_marker.png');

          }
        }
        );
    }
  }

  function setupButtons() {
    $('btn_ZoomIn').onclick = function() {
      map.zoomIn();
      return false;
    }
    $('btn_ZoomOut').onclick = function() {
      map.zoomOut();
      return false;
    }

    $('btn_map').onclick = function() {
      map.setMapType(G_NORMAL_MAP);
      setSelected(this);
      return false;
    }

    $('btn_satellite').onclick = function() {
      map.setMapType(G_SATELLITE_MAP);
      setSelected(this);
      return false;
    }

    $('btn_hybrid').onclick = function() {
      map.setMapType(G_HYBRID_MAP);
      setSelected(this);
      return false;
    }
  }

  function setSelected(elm){
    mapTypeSelected.up('li').removeClassName('selected');
    elm.up('li').addClassName('selected');
    mapTypeSelected = elm;
  }

}

