// nav
function initPage() {
	/*initAutoScalingNav({
		menuId: "nav",
		sideClasses: true,
		spacing: 0
	});*/

}
// initOl
function initOl(){
	$('.ie6 #content .step-form ol li, .ie7 #content .step-form ol li, .ie8 #content .step-form ol li ').each(function(){
			var t  = this
			var txt =(++t.parentNode.IEcounter || (t.parentNode.IEcounter = 1));
			var f = false;
			if (t.childNodes.length) {
				for (var i=0;i<t.childNodes.length;i++) {
					if (typeof(t.childNodes[i].tagName) == 'string' && /^\\w+/.test(t.childNodes[i].tagName)) {
						f = true;
						break;
					}
				}
			}
			if (f) {
				t.before = document.createElement("before");
				t.before.appendChild(document.createTextNode(txt));
				t.insertBefore(t.before,t.getElementsByTagName('*')[0]);
			} else {
				document.createElement("before");
				t.insertAdjacentHTML('afterBegin','<before>' + txt  + ' </before>');
			}
			t.style.behavior= '';
		});

}
function initAutoScalingNav(o) {
	if (!o.menuId) o.menuId = "nav";
	if (!o.tag) o.tag = "a";
	if (!o.spacing) o.spacing = 0;
	if (!o.constant) o.constant = 0;
	if (!o.minPaddings) o.minPaddings = 0;
	if (!o.liHovering) o.liHovering = false;
	if (!o.sideClasses) o.sideClasses = false;
	if (!o.equalLinks) o.equalLinks = false;
	if (!o.flexible) o.flexible = false;
	var nav = document.getElementById(o.menuId);
	if(nav) {
		nav.className += " scaling-active";
		var lis = nav.getElementsByTagName("li");
		var asFl = [];
		var lisFl = [];
		var width = 0;
		for (var i=0, j=0; i<lis.length; i++) {
			if(lis[i].parentNode == nav) {
				var t = lis[i].getElementsByTagName(o.tag).item(0);
				asFl.push(t);
				asFl[j++].width = t.offsetWidth;
				lisFl.push(lis[i]);
				if(width < t.offsetWidth) width = t.offsetWidth;
			}
			if(o.liHovering) {
				lis[i].onmouseover = function() {
					this.className += " hover";
				}
				lis[i].onmouseout = function() {
					this.className = this.className.replace("hover", "");
				}
			}
		}
		var menuWidth = nav.clientWidth - asFl.length*o.spacing - o.constant;
		if(o.equalLinks && width * asFl.length < menuWidth) {
			for (var i=0; i<asFl.length; i++) {
				asFl[i].width = width;
			}
		}
		width = getItemsWidth(asFl);
		if(width < menuWidth) {
			var version = navigator.userAgent.toLowerCase();
			for (var i=0; getItemsWidth(asFl) < menuWidth; i++) {
				asFl[i].width++;
				if(!o.flexible) {
					asFl[i].style.width = asFl[i].width + "px";
				}
				if(i >= asFl.length-1) i=-1;
			}
			if(o.flexible) {
				for (var i=0; i<asFl.length; i++) {
					width = (asFl[i].width - o.spacing - o.constant/asFl.length)/menuWidth*100;
					if(i != asFl.length-1) {
						lisFl[i].style.width = width + "%";
					}
					else {
						if(navigator.appName.indexOf("Microsoft Internet Explorer") == -1 || version.indexOf("msie 8") != -1 || version.indexOf("msie 9") != -1)
							lisFl[i].style.width = width + "%";
					}
				}
			}
		}
		else if(o.minPaddings > 0) {
			for (var i=0; i<asFl.length; i++) {
				asFl[i].style.paddingLeft = o.minPaddings + "px";
				asFl[i].style.paddingRight = o.minPaddings + "px";
			}
		}
		if(o.sideClasses) {
			lisFl[0].className += " first-child";
			lisFl[0].getElementsByTagName(o.tag).item(0).className += " first-child-a";
			lisFl[lisFl.length-1].className += " last-child";
			lisFl[lisFl.length-1].getElementsByTagName(o.tag).item(0).className += " last-child-a";
		}
		nav.className += " scaling-ready";
	}
	function getItemsWidth(a) {
		var w = 0;
		for(var q=0; q<a.length; q++) {
			w += a[q].width;
		}
		return w;
	}
}
if (window.addEventListener)
	window.addEventListener("load", initPage, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPage);


// input

function hideFormText() {
	var _inputs = document.getElementsByTagName('input');
	var _txt = document.getElementsByTagName('textarea');
	var _value = [];

	if (_inputs) {
		for(var i=0; i<_inputs.length; i++) {
			if (_inputs[i].type == 'text' || _inputs[i].type == 'password') {

				_inputs[i].index = i;
				_value[i] = _inputs[i].value;

				
				
			}
		}
	}
	if (_txt) {
		for(var i=0; i<_txt.length; i++) {
			_txt[i].index = i;
			_value['txt'+i] = _txt[i].value;

			
			
		}
	}
}

// rounded image

$(document).ready(function(){
  $(".rounded-img, .rounded-img2").load(function() {
    $(this).wrap(function(){
      return '<span class="' + $(this).attr('class') + '" style="background:url(' + $(this).attr('src') + ') no-repeat center center; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px;" />';
    });
    $(this).css("opacity","0");
  });
	initOl();
	hideFormText();





  var $colorboxGalleries = $('#main .colorbox-gallery');
  if ($colorboxGalleries.length) {
      $colorboxGalleries.each(function(){
         var $this = $(this);
         if ($this.prop('tagName') === 'A') {
             $this.colorbox();
         } else {
             $this.find('a').colorbox();
         }
      });
  }
  
  //gym state select filter
  
  
  if($('.gym-state-select').length) {
   
        var $groups = $('select.stateLocation');
        //var $states = $('select.state');
        var groupArray = [];
        var locationsArray = [];
        
		/* $('option', $states).each(function(i) {
            locationsArray[$(this).attr('value')] = [];
        }); */
		
        $('optgroup', $groups).each(function(i) {
            label = $(this).attr('label');
			locationsArray[label] = []
			$('option', $(this)).each(function(j) {
				locationsArray[label][j] = {value : $(this).attr('value'), html :  $(this).html()};
			});
        });

	   $groups.change(function() {
			window.location = $(this).val();
	   });
      
      $('select.state').change(function(e){
          var state = $(this).val();
			$('.stateLocation').html('');
			$('<option>Please Select</option>').appendTo($('.stateLocation'));
          for(var i=0;i<locationsArray[state].length;i++){
			   //update dropdown with state dropdown
				$('<option value="'+locationsArray[state][i].value+'">'+locationsArray[state][i].html+'</option>').appendTo($('.stateLocation'));
		  }
       
      });
      
  }

  if ($('.gallery').length) {

      // init variables
      var $images_array = []; //image $object array
      var easing = 'easeInOutExpo'; // image ease
      var interval_time = 8000; //milliseconds
      var slide_time = 800; //milliseconds
      var $image_container = $('.gallery .image_container');
      var current_index = 0; //image counter
      var timer //timer interval
   
      //init
      function init(){
          setupGallery()
      }


      function setupGallery(){

          //images array
       
//        $('.gallery').height($('.gallery img').height())
          $('.gallery img').each(function(index){
              $images_array[index] = {$image_object:$(this), $link_object:null};

              //assign image x value
              var xVal = index*590 //width of the image
              $images_array[index].$image_object.css({'left':xVal})

          });

         //loop through link to attach object o images array
          $('.gallery li a').each(function(index){
              $images_array[index].$link_object = this;
          });


          $('.gallery li a').click(function(e){

                e.preventDefault()

              var index = $(this).parent().index() //index of in object in $images

                if(current_index != index){

                    showSlide(index);
                }

               

          });


          showSlide(current_index);

      }

      function showSlide(index){

            var xVal = "-"+$images_array[index].$image_object.css('left')
           
            $image_container.stop(true, true).animate({
              left: xVal

          },slide_time,easing);

          //loop through all buttons and find active button

           $('.gallery li a').each(function(i){
              if(index == i){
                
                $(this).addClass('selected');
                
              }else{
                $(this).removeClass('selected');
              }
          });


          current_index = index;

        clearInterval(timer)
        timer = setInterval ( showNextSlide, interval_time );


      };

      function showNextSlide() {
        current_index ++
        current_index = (current_index > $images_array.length-1) ? 0 : current_index;
        showSlide(current_index);
      }




      init();
  }

  //fix submit
  if($('#idFieldSet').length){

    $(".btn-submit").click(function(event){

        console.log($('input'))
       event.preventDefault();
       $('#idSubmit').trigger('click');
    })
}

  // --------------- timetable ----------------

  if($('#full-width .table').length){
		$('body').prepend('<div class="section"><div class="note-box hidden"><div class="bull">&nbsp;</div><div class="holder"><span class="rounded-img" style="background: url(images/img-note.gif) no-repeat scroll center center transparent; width: 152px; height: 152px;"><img class="rounded-img" width="152" height="152" src="images/img-note.gif" style="opacity: 0;" alt=""/></span><div class="text-box"><h3>[title]</h3><p>[description]</p></div></div></div></div>');
        var easing = 'easeOutExpo'; //  ease
        var timing = 1000;

      //ADD CLASS FILTERING

       
       
       
       //CLASS FILTERING FIX
       var timetable_array = []
       $('#full-width form').each(function(e){
           
           var $table = $(this).next();
           
           
           
           var class_array = []
           
            $('a',$table).parent().each(function(e){
               var title = $('.class-info h3',$(this)).html();

              class_array.push(title)
           })
           
           var classes = eliminateDuplicates(class_array)

           for(var i=0;i<classes.length;i++){
           $('select', $(this)).append(
                    $('<option></option>').val(i+2).html(classes[i]) //+2 because 0 is please select and 1 is select all classes
                );

           }
           
           timetable_array.push(class_array)
       });

       //PRINT FUNCTION
       

		$('.filter-form .item-btn').click(function(e){
			//we want to clone the element with styles
			/* var baseHref = document.getElementsByTagName('base')[0].href;
			var table = $(this).parent().parent().next();

			var currentClub = $('.section .heading h1').text()
			var currentClass = $(".filter-form select option:selected").text();
			currentClass = ('Please Select')?'All Classes':currentClass;
			var printArea = '<div class="hidden clear-print"><div class="print-area">';
			printArea += '<section class="section">';
			printArea += '<div id="print-header"><img src="'+baseHref+'images/logo.png" alt="Genesis Fitness Clubs"/></div>';
			printArea+= '<h1>'+currentClub+'</h1><br /><h2>'+currentClass+'</h2><br />';
			printArea += '</section>';
			printArea += '</div></div>';


			$('#full-width').append(printArea);
			table.clone().appendTo('.print-area section');

			$(".print-area section").printElement({
				overrideElementCSS:['css/print.css'],
				leaveOpen:true,
				printMode:'popup'
			});

			$(".clear-print").remove(); */
			window.print();
			e.preventDefault();
		});
       
		$(".filter-form select").change(function(){
           
			var selected = $("option:selected", this)

			var table =$(this).parent().parent().next();
            
           
          
			if(selected.val() > 1){
            

				//var found_objects =   $('#full-width .table td:contains("'+selected.text()+'")');


				$( 'td', table).each(function(e){

                 
					var title =$('.class-info h3',$(this)).html();
					if(title == selected.text()){
						$(this).stop(true,true).animate({
							opacity:1
						},600,easing)
					}else if(!$(this).hasClass('title')){
						$(this).stop(true,true).animate({
							opacity:0
						},600,easing)
					}
                 
				})

			}else if(selected.val() == 0){
				$('#full-width .table td').each(function(e){
					$(this).stop(true,true).animate({
						opacity:1
					},600,easing)
				});
			}
		});




       //ADD HOVER FUNCTION

        var easing = 'easeOutExpo'; //  ease
        var timing = 1000;
        var timer = null;
        var timeOut;
      $('#full-width .table a').parent().hover(function() {
            clearTimeout(timer);
            //check if visible
            if($(this).css('opacity') > 0){
               popupRollOver(this);
            }
            
        }, function() {
              popupRollOut(this);
        });
    
        $('.note-box').attr('disabled', true);

       $('#full-width .table a').click(function(e){
			e.preventDefault();
        })

      $('.note-box').removeClass('hidden');
      $('.note-box').stop(true, true).fadeOut(0.01,easing)

      function popupRollOver(scope) {
           
           var title = $('.class-info h3',$(scope)).html();
           var description = $('.class-info p',$(scope)).html();
           var img = $('.class-info img',$(scope)).attr('src');

          $('.note-box h3').html(title);
          $('.note-box p').html(description);

          $('.note-box span').remove()

            var imgSpan = '<span class="rounded-img" style="background: url('+img+') no-repeat scroll center center transparent; width: 152px; height: 152px;">'
            imgSpan+= ' <img class="rounded-img" width="152" height="152" alt="image description" src="i'+img+'" style="opacity: 0;">'
            imgSpan+='</span>'

            $('.note-box .holder').prepend(imgSpan);


             var x = $(scope).position().left - $('.note-box').width()/2 + 25
             var y = $(scope).position().top -  $('.note-box').height() - $(scope).height()-15



             $('.note-box').css({left:x,top:y-10});


            

          $('.note-box').stop(true, true).css({display:'block'}).animate({
              top:y,
              opacity:1
              

          },timing/2,easing,function(){
             
              
          });

        


      }
      function popupRollOut(scope){


        $('.note-box').stop(true, true).animate({
              opacity:0
              

          },timing/2,easing,function(){
              $(this).css({display : 'none'});
          });



      }

  }
  
  
  
  
  


  //timetable highlight fix

 if ($('#main .heading').length) {
   $timetable = $('#nav li a[href$="timetables-classes"]').parent();
   $timetable.addClass('active');


   }

    if($('#nav').length){
        resizeMenu($('#nav li a'), 982)
        $('#nav li a').each(function(e){
            if(e == $('#nav li a').length-1){
                width = eval($(this).css('width').split('px').join(''))+2
                $(this).css({'width':width})
            }
        })
        $('#nav li').css({visibility:'visible'})
    }



});

function resizeMenu($navItem, menuWidth){
    var sizeConcat = 0
    $navItem.each(function(e){
        sizeConcat += $(this).width()
    })

    var widthDif = ((menuWidth-(sizeConcat))/$navItem.length-1)

    $navItem.each(function(e){
       var itemWidth = Math.round(widthDif + $(this).width())
       $(this).css({'width': itemWidth +'px'});
    })
}


function eliminateDuplicates(arr) {
  var i,
      len=arr.length,
      out=[],
      obj={};

  for (i=0;i<len;i++) {
    obj[arr[i]]=0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}
