jQuery(function($) {
//dependent to /js/jquery.preloadCssImages.min.js
  $.preloadCssImages();

/*** Footer Carousel ***/
$.fn.carousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
  
    return this.each(function () {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = 1, // note: doesn't include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible);            


        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        if (($items.length % visible) != 0) {
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }

        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect
        
        // 3. Set the left position to the first 'real' item
        $wrapper.scrollLeft(singleWidth * visible);
        
        // 4. paging function
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 500, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                } 

                currentPage = page;
            });                
            
            return false;
        }
        
        $wrapper.after('<a class="prev">&lt;</a><a class="next">&gt;</a>');
        
        // 5. Bind to the forward and back buttons
        $('a.prev', this).click(function () {
            return gotoPage(currentPage - 1);                
        });
        
        $('a.next', this).click(function () {
            return gotoPage(currentPage + 1);
        });
        
        // create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });
    });  
};

// run function
$('.carousel').carousel();





/*** Image REEL ***/
	//Set Default State of each portfolio piece
	$(".paging").show();
	$(".paging a:first").addClass("active");
			
	//Get size of images, how many there are, then determin the size of the image reel.
	var imageWidth = $(".window").width();
	var imageSum = $(".image_reel img").size();
	var imageReelWidth = imageWidth * imageSum;
		
	//Adjust the image reel to its new size
	$(".image_reel").css({'width' : imageReelWidth});
	
	//Paging + Slider Function
	rotate = function(){	
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

		$(".paging a").removeClass('active'); //Remove all active class
		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
		
		//Slider Animation
		$(".image_reel").animate({ 
			left: -image_reelPosition
		}, 500 );
		
	}; 
	
	//Rotation + Timing Event
	rotateSwitch = function(){		
		play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
			$active = $('.paging a.active').next();
			if ( $active.length === 0) { //If paging reaches the end...
				$active = $('.paging a:first'); //go back to first
			}
			rotate(); //Trigger the paging and slider function
		}, 7000); //Timer speed in milliseconds (3 seconds)
	};
	
	rotateSwitch(); //Run function on launch
	
	//On Hover
	$(".image_reel a").hover(function() {
		clearInterval(play); //Stop the rotation
	}, function() {
		rotateSwitch(); //Resume rotation
	});	
	
	//On Click
	$(".paging a").click(function() {	
		$active = $(this); //Activate the clicked paging
		//Reset Timer
		clearInterval(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});	

	
	
	
/*** Main Navigation popup***/	
	//On Hover Over
function megaHoverOver(){
    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
    
    if ( $(this).find(".row").length > 0 ) { //If row exists...

        var biggestRow = 0;	

		/*
        $(this).find(".row").each(function() {	//for each row...
            $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if(rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });
		*/

        $(this).find(".sub").css({'width' :biggestRow}); //Set width
        $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

    } else {  //If row does not exist...
		/*
		$(this).calcSubWidth();  //Call function to calculate width of all ul's
        $(this).find(".sub").css({'width' : rowWidth}); //Set Width
		*/
    }
}
//On Hover Out
function megaHoverOut(){
  $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
      $(this).hide();  //after fading, hide it
  });
}

//Set custom configurations
var config = {
     sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
     interval: 100, // number = milliseconds for onMouseOver polling interval
     over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: megaHoverOut // function = onMouseOut callback (REQUIRED)
};

$("ul#topnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
$("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations





/* 
	Skimax Base Object
	LM: 10-04-10 
*/
window.Skimax = (function ($, window, document, undefined) {

	jQuery.root = $(document);
	
	var uri = window.location.href,
		t = function (_s) { return $.trim(_s); },
		byId = function (_id) {return document.getElementById(_id);},
		$con = jQuery.root.find('#container'),
		$body = $(document.body);
	
	var E = {
	
		unloads : {			
			unload : function (e) {
				$con.addClass('hide');
			},			
			beforeunload : function (e) {
				$(this).unbind('unload');
				$con.addClass('hide');				
			}			
		},
		
		numeric : function (e) {
			if (t(this.value) === '') {return;}
			var label = t($(this).parent().siblings('td').text());
			if (!(/^[0-9,]+$/).test(t(this.value))) {
				this.value = '';
				if (label !== '') {
					alert('Please enter a numeric value for ' + label, 'warning');
				}
				else {
					alert('Please enter a numeric value', 'warning');
				}
			}
		}
							
	};
	
	
	var privates = {
	
		bodyClassHack : function () {
			var $body=$(document.body),browser=Ttow.Browser;
			/*@cc_on
			$body.addClass('ie');if(browser.msie6){$body.addClass('ie6 ie67 ie68 ie69');}
			else if(browser.msie7){$body.addClass('ie7 ie67 ie78 ie79');}
			else if(browser.msie8){$body.addClass('ie8 ie68 ie78 ie89');}
			else if(browser.msie9){$body.addClass('ie9');}
			return;@*/
			$body.addClass('not-ie');
			if(document.addEventListener){if(browser.mozilla){$body.addClass('moz');}
			else if(browser.chrome){$body.addClass('chrome');}
			else if(browser.safari){$body.addClass('safari');}
			else if(browser.opera){$body.addClass('opera');}
			else if(browser.ff2){$body.addClass('ff2');}}						
		},

		loadEvents : function () {
			privates.bodyClassHack();
			//window unload events //
			$.root.delegate("a[href^='http://'], a[href^='https://']", 'mousedown', function () {
				$(window).unbind('unload').unbind('beforeunload');
			});			
			$(window).bind({				
				'unload' :  E.unloads.unload,
				'beforeunload' : E.unloads.beforeunload
			});
			
			if (Ttow.Browser.msie8) {
					$('noscript').css('display', 'none');
			}
			
			$.root.delegate('input.numeric', 'blur', E.numeric);
			
			return this;
			
		},

		log : function (m) {
			if (window.console) {
				window.console.log(m);
			}
		},
		
		bodyClasses : function () {
			var B = Ttow.Browser;
			if (B.msie) {
				$body.addClass('ie');
			}
			if (B.msie6) {
				$body.addClass('ie6');
			}
			else if (B.msie7) {
				$body.addClass('ie7');
			}
			else if (B.msie8) {
				$body.addClass('ie8');
			}
			else if (B.msie9) {
				$body.addClass('ie9');
			}
			
			return this;
		}
		
	};

	return {
		init : function () {			
			privates.loadEvents()
					.bodyClasses();
		},
		
		uri : uri,
		$con : $con,
		
		Dialog : {
			formError : function (_msg, _notForm) {
				// <div id="form-error" class="redb hide"></div> //
				var $dialogCon = $('#form-error');
				if ($dialogCon.length <= 0) { return; }				
				if (_notForm === undefined) {
				    $dialogCon.html('').hide();
					_msg = _msg.replace('\n', ''); // under observation
					var warnings = _msg.split('-'),
						warLen = warnings.length,
						html = '';					
					html += '<p>';
					html += '<h4 class="notice">You need to fill in these fields:</h4><br />';
					//html += '<img src="'+PATHS.IMG+'error_button.gif" alt="" style="float: left"/>';		
					html += '<ul id="warning-list">';	
					for (var i=0; i<warLen; i++) {						
						if (t(warnings[i]) === '') {continue;}
						html += '<li>' + t(Ttow.Util.entities(warnings[i])) + '</li>';
					}
					html += '</ul>';
					html += '</p>';	
					$(document.body).Ttow(['scrollToMe']); 
					$dialogCon.html(html)
							  .slideDown();					
				}
				else {
					
				}				
			}
		},
		
		formFieldHighlight : function (_form) { 
			$(_form).find('input, textarea, select').bind({
				'focus' : function () {
					$(this).closest('tr').addClass('form-field-highlight');
				},
				
				'blur' : function () {
					$(this).closest('tr').removeClass('form-field-highlight');
				}
			});
		},
		
		byId : byId,

		checkEmail : function (_e) {
			return (/^[A-z0-9._]{2,}@[A-Za-z0-9]{2,}\.[a-z]{2,}(\.[a-z]{2,})?$/).test(t(_e));
		}	
	};

})(jQuery, window, document);


	
Skimax.init();


});



