//function initPage()
//{
//	var inputs = document.getElementsByTagName("input");
//	for (var i=0; i<inputs.length; i++)  {
//		if (inputs[i].className == "submit")  {
//			inputs[i].onmouseover = function()
//			{
//			   this.src = this.src.replace(".gif", "-hover.gif");
//			}
//			inputs[i].onmouseout = function()
//			{
//				this.src = this.src.replace("-hover.gif", ".gif");
//			}
//		}
//	}
//}
//
//if (window.addEventListener)
//	window.addEventListener("load", initPage, false);
//else if (window.attachEvent)
//	window.attachEvent("onload", initPage);
//$(document).ready(function(){
//	$('input.file-input-area').each(function(){
//		var _el = $(this);
//		var _field = _el.parent().parent().find('input:text');
//		_field.attr('readOnly', true);
//		_el.css('opacity', 0);
//		_el.change(function(){
//			_field.val(this.value);
//		});
//	});
//});

$(function() {

  $('ul.tabset').superfish({
    'hoverClass': 'hover',
    'dropShadows': false,
    'autoArrows': false,
    'speed': 100,
    'delay': 400
  });
	
  /*
	 * Superfish hack as the hover state is not applied to the parent li element
	 * when it does not contain a submenu
	 */
  $('ul.tabset > li.nochild').hover(function() {
    $(this).parent('ul').children('li').removeClass('hover').children('ul').hide();
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  })

  $('ul.tabset ul').each(function() {
    $(this).children('li:last').addClass('last');
  });
	
  $('.advertise .ad-box a').click(function() {
    var link = $(this);
    var parent = link.parents('.ad-box:first');
    if(parent.size() > 0) {
      var trackerUrl = parent.data('tracker');
      if(trackerUrl) {
        $.get(trackerUrl, function(data) {			
          });
      }
    }
    window.open(this.href);
    return(false);
  })

  // iterate through each of the checkboxes with the toggler class and bind a click event to show
  // a related div with the suffix _toggle
  $('input[type=checkbox].toggler').each(function() {
    $(this).bind('click', function() {
      toggleRelatedElement($(this).attr('id'), this.checked);
    });

    toggleRelatedElement($(this).attr('id'), this.checked);
  });


  function toggleRelatedElement(triggerElementId, showhide) {
    var relatedElement = $('#' + triggerElementId + '_toggle');
    showhide ? relatedElement.show() : relatedElement.hide();
  }


  $('a[rel=external]').click(function() {
    window.open(this.href);
    return(false);
  });

  $('form.focusfirst input:first').focus();

  $('.has-other select').change(function() {
    var acompanyingOtherField = $('#' + this.id.replace(/id$/, '') + 'other');
    if(acompanyingOtherField.size() > 0) {
      if(this.options[this.selectedIndex].text.toLowerCase() == 'other') {
        acompanyingOtherField.parent('.form-item').show();
        acompanyingOtherField.focus();
      } else {
        acompanyingOtherField.parent('.form-item').hide();
      }
    }
	    
  }).trigger('change');


  slideGallery();
  /* large carousel - front page, stallions page */
  initGallery();
	

})


// a function to enable iframes to change the parents url
// @link http://av5.com/docs/changing-parent-window-s-url-from-iframe-content.html
function change_parent_url(url)
{
  document.location=url;
}


/*--- slide gallery ---*/
function slideGallery(){
  var change_speed = 300; //in ms
  $('.carusel').each(function(){
    var _hold = $(this);
    var btn_prev = _hold.find('a.btn-p');
    var btn_next = _hold.find('a.btn-n');
    var list_hold = _hold.find('div.thumbnails > ul');
    var _list = list_hold.children();
    var list_w = _list.length * _list.outerWidth();
    var hold_w = list_hold.parent().width();
    if(list_w > hold_w){
      var _step = _list.outerWidth();
      var _m = list_w;
      list_hold.append(_list.clone()).append(_list.clone());
      list_hold.css('left', -_m);
      btn_prev.click(function(){
        moveList(false);
        return false;
      });
      btn_next.click(function(){
        moveList(true);
        return false;
      });
    }
    else{
      btn_prev.hide();
      btn_next.hide();
    }
    var _flag = true;
    function moveList(_f){
      if(_flag){
        _flag = false;
        if(_f){
          if(_m + _step > list_w*3 - hold_w){
            _m -= list_w;
            list_hold.css('left', -_m);
          }
          _m += _step;
        }
        else{
          if(_m - _step < 0){
            _m += list_w;
            list_hold.css('left', -_m);
          }
          _m -= _step;
        }
        list_hold.animate({
          left: -_m
          }, change_speed, function(){
          _flag = true;
        });
      }
    }

  });
}


/*--- end slide gallery ---*/

/* -----------------------------*/
/* -------- Slideshow ----------*/
/* -----------------------------*/

function initGallery(){
  /*
  if($('.home div.slideshow li').size() > 1) {
    jQuery('.home div.slideshow').slideshow({
      autoPlay:true,
      effect:'slideX',//fade, slideX, slideY
      switchTime:9000 //ms
    });
  }
  */
  jQuery('.stallions div.slideshow').slideshow({
    autoPlay:true,
    effect:'slideX',//fade, slideX, slideY
    switchTime:5000, //ms
    animSpeed: 500
  });
  
  
// Move buttons into position, slider seems to have issues when setting absolute positioning within .slider
/*
  $('.slideshow .prev').css("background-color", "#3366FF");
  $('.slideshow .prev').css("position", "absolute");
  $('.slideshow .prev').css("left", "0px");
  */
}
//create jQuery plugin
jQuery.fn.slideshow = function(options){
  return new slideshow(this, options);
}
//constructor
function slideshow(obj, options){
  this.init(obj,options)
}
//prototype
slideshow.prototype = {
  init:function(obj, options) {
    this.options = jQuery.extend({
      slides:'ul.slide >li',
      //nextBtn:'a.next',
      //prevBtn:'a.prev',
      nextBtn:'div.next',
      prevBtn:'div.prev',
      pagingHolder:'div.switcher',
      pagingTag:'li',
      createPaging:true,
      autoPlay:false,
      dynamicLoad:false,
      imgAttr:'alt',
      effect:'slideX',//fade, slideX, slideY,
      startSlide:false,
      switchTime:5000,
      animSpeed:2000
    },options);
		
    this.mainHolder = jQuery(obj);
    this.slides = jQuery(this.options.slides,this.mainHolder);		
    this.nextBtn = jQuery(this.options.nextBtn,this.mainHolder);
    this.prevBtn = jQuery(this.options.prevBtn,this.mainHolder);
    this.dynamicLoad = this.options.dynamicLoad;
    this.imgAttr = this.options.imgAttr;
    this.animSpeed = this.options.animSpeed;
    this.switchTime = this.options.switchTime;
    this.effect = this.options.effect;
    this.autoPlay = this.options.autoPlay;
    this.previous = -1;
    this.loadingFrame = 1;
    this.busy = false;
    this.direction = 1;
    this.timer;
    this.pagingArray = new Array;
    this.loadArray = new Array;
    this.preloader = new Array;
    this.slidesParent = this.slides.eq(0).parent();
    this.slideW = this.slidesParent.width();
    this.slideH = this.slidesParent.height();
		
    (function(){
      if (this.options.startSlide) this.current = this.options.startSlide
      else {
        var active = -1;
        for(var i = 0; i< this.slides.length-1; i++) {
          if (this.slides.eq(i).hasClass('active')) {
            active = i;
            break;						
          }
        }
        if (active != -1) this.current = active;
        else this.current = 0;
      }
    }).apply(this);
		
    this.initPaging();
    this.setStyles();
    this.bindEvents();
    this.showSlide();
  },
	
  initPaging:function(){
    var obj = this;
    this.pagingHolder = jQuery(this.options.pagingHolder,this.mainHolder);
		
    if (this.options.createPaging) {
      this.pagingHolder.each(function(i){
        var _this = jQuery(this);
        _this.empty();
        var list = jQuery('<ul>');
        for (var i = 0; i < obj.slides.length; i++) jQuery('<li><a href="#">' + (i + 1) + '</a></li>').appendTo(list);
        _this.append(list);
      });
    }
		
    this.paging = jQuery(this.options.pagingTag, this.pagingHolder);
    var ratio = Math.ceil(this.paging.length / this.slides.length);
    for (var i = 0; i < ratio; i++) {
      this.pagingArray.push(this.paging.slice(i*this.slides.length, (i*this.slides.length)+this.slides.length));
    }
  },
	
  setStyles:function(){
    //loader
    if (this.dynamicLoad) {
      this.loader = jQuery('<div class="loader">');
      this.loaderDiv = jQuery('<div>').appendTo(this.loader)
      this.loader.append(this.loaderDiv).appendTo(this.slidesParent);
    }
		
    //slides
    if (this.effect == 'fade') {
      this.slides.css({
        display:'none'
      });
      this.slides.eq(this.current).css({
        display:'block'
      });
    } else if (this.effect == 'slideX'){
      this.slides.css({
        display: 'none',
        left:-this.slideW
      });
      this.slides.eq(this.current).css({
        display:'block',
        left:0
      });
    } else if (this.effect == 'slideY'){
      this.slides.css({
        display:'none',
        top:-this.slideH
      });
      this.slides.eq(this.current).css({
        display:'block',
        top:0
      });
    }
  },
	
  bindEvents:function(){
    var obj = this;
    this.nextBtn.bind('click',function(){
      if (!obj.busy) obj.nextSlide();
      return false;
    });
		
    this.prevBtn.bind('click',function(){
      if (!obj.busy) obj.prevSlide();
      return false;
    });
		
    for (var i = 0; i < this.pagingArray.length; i++) {
      this.pagingArray[i].each(function(i){
        jQuery(this).bind('click',function(){
          if (i != obj.current && !obj.busy) {
            obj.previous = obj.current;
            obj.current = i;
            if (obj.previous > i) obj.direction = -1
            else obj.direction = 1;
            obj.showSlide();
          }
          return false;
        });
      });
    }
		
    if (this.dynamicLoad) this.loader.bind('click',function(){
      obj.abortLoading();
    });
  },
	
  nextSlide:function(){
    this.previous = this.current;
    if (this.current < this.slides.length-1) this.current++
    else this.current = 0;
    this.direction = 1;
    this.showSlide();
  },
	
  prevSlide:function(){
    this.previous = this.current;
    if (this.current > 0) this.current--
    else this.current = this.slides.length-1;
    this.direction = -1;
    this.showSlide();
  },
	
  showSlide:function(){
    var obj = this;
    var _current = this.current;
    this.busy = true;
    clearTimeout(this.timer);
		
    if (typeof this.loadArray[_current] != 'undefined' || !this.dynamicLoad) {
      //slide already loaded
      this.switchSlide();
		
    } else {
      //slide not loaded
      this.showLoading();
      var images = jQuery(this.dynamicLoad,this.slides.eq(this.current));
      if (images.length) {
        var counter = 0;
        images.each(function(){
          var preloader = new Image;
          obj.preloader.push(preloader);
          var img = jQuery(this);
          preloader.onload = function(){
            counter++;
            checkImages();
          }
          preloader.onerror = function(){
            //ignore errors
            counter++;
            checkImages();
          }
          preloader.src = img.attr(obj.imgAttr);
        });
				
        function checkImages(){
          if (counter == images.length) {
            images.each(function(){
              var img = jQuery(this);
              img.attr('src',img.attr(obj.imgAttr));
            });
            successLoad();
          }
        }
				
      } else successLoad();
    }
		
    function successLoad(){
      obj.loadArray[_current] = 1;
      obj.hideLoading();
      obj.switchSlide();
    }
  },
	
  switchSlide:function(){
    var obj = this;
		
    if (this.previous != -1) {
      var nextSlide = this.slides.eq(this.current);
      var prevSlide = this.slides.eq(this.previous);
			
      if (this.effect == 'fade') {
        nextSlide.css({
          display:'block',
          opacity:0
        }).animate({
          opacity:1
        },this.animSpeed,function(){
          jQuery(this).css({
            opacity:'auto'
          });
        });
        prevSlide.animate({
          opacity:0
        },this.animSpeed,callback);
      } else if (this.effect == 'slideX'){
        nextSlide.css({
          display:'block',
          left:this.slideW*this.direction
        }).animate({
          left:0
        },this.animSpeed);
        prevSlide.animate({
          left:-this.slideW*this.direction
        },this.animSpeed+10,callback);
      } else if (this.effect == 'slideY'){
        nextSlide.css({
          display:'block',
          top:this.slideH*this.direction
        }).animate({
          top:0
        },this.animSpeed);
        prevSlide.animate({
          top:-this.slideH*this.direction
        },this.animSpeed+10,callback);
      }
    } else {
      if (this.autoPlay) this.startAutoPlay();
      this.busy = false;
    }
		
    this.refreshStatus();
		
    function callback(){
      prevSlide.css({
        display:'none'
      });
      if (obj.autoPlay) obj.startAutoPlay();
      obj.busy = false;
    }
  },
	
  refreshStatus:function(){
    for (var i = 0; i < this.pagingArray.length;i++) {
      this.pagingArray[i].eq(this.previous).removeClass('active');
      this.pagingArray[i].eq(this.current).addClass('active');
    }
    this.slides.eq(this.previous).removeClass('active');
    this.slides.eq(this.current).addClass('active');
  },
	
  showLoading:function(){
    var obj = this;
    this.loader.show();
    clearInterval(this.loadingTimer);
    obj.loadingTimer = setInterval(animateLoading, 66);
		
    function animateLoading(){
      obj.loaderDiv.css('top', obj.loadingFrame * -40);
      obj.loadingFrame = (obj.loadingFrame + 1) % 12;
    }
  },
	
  hideLoading:function(){
    this.loader.hide();
    clearInterval(this.loadingTimer);
  },
	
  abortLoading:function(){
    this.busy = false;
    this.hideLoading();
    this.current = this.previous;
    for (var i = 0; i < this.preloader.length; i++) {
      this.preloader[i].onload = null;
      this.preloader[i].onerror = null;
    }
    if (this.autoPlay) this.startAutoPlay();
  },
	
  startAutoPlay:function(){
    var obj = this;
    clearTimeout(obj.timer);
    obj.timer = setTimeout(function(){
      obj.nextSlide();
    },obj.switchTime);
  }
}

