mainSize=0;
$(function() { 	
	// Hide Background Pic(since JS is activated we can hide the background_img, let it load and resize and show it then (see changeWindowSize))
	$("#background_img").hide();
	
	// Create Superfish Menu
		$('ul.sf-menu').superfish({ 
			animation: {height:'show'},
			dropShadows:   false,
			disableHI:true,
			 speed:         300//00;   
		});	
	
	// Link Home Logo
		$("#logo").click(function(){
			self.location.href="index.html";
		});
	// Footer - Infoline under the socials
		orig_infotext=$("#footer_text").text();
		$("#socials a").hover(
		  function () {  
			$("#footer_text").text($(this).find("img").attr("alt"));
		  },
		  function () { 
			$("#footer_text").text(orig_infotext);
		  }
		);
	
	//Img Links
	// append div with links
		$(".img_link").hover(function(){
			// get image heights on mouseover
			imgWidth = $(this).find("img").width();
			imgHeight = $(this).find("img").height();
			// create overlay
			$(this).append('<div class="img_link_div"></div>');
			$(this).find(".img_link_div").width(imgWidth);
			$(this).find(".img_link_div").height(imgHeight);
			// create icon
			$(this).append('<div class="img_link_img"><img src="images/assets/img_link.png"></div>');
			// animate icon to fade in and move from 18px above the middle to the middle
			$($(this).find(".img_link_img").css("left",imgWidth/2-18));
			$($(this).find(".img_link_img").css("top",imgHeight/2-50));
			$(this).find(".img_link_img").animate({
				opacity: 0.75,
    			top: (imgHeight/2)-18
				},150);
		},function(){
			// kill overlay and icon on mouseout
			$(this).find(".img_link_div").remove();	
			$(this).find(".img_link_img").remove();	
		});	
	// append div for image previews	
		$(".img_view").hover(function(){
			// get image heights on mouseover
			imgWidth = $(this).find("img").width();
			imgHeight = $(this).find("img").height();
			// create overlay
			$(this).append('<div class="img_link_div"></div>');
			$(this).find(".img_link_div").width(imgWidth);
			$(this).find(".img_link_div").height(imgHeight);
			// create icon
			$(this).append('<div class="img_link_img"><img src="images/assets/img_view.png"></div>');
			$(this).find(".img_link_div").append('<div class="thumb_title">'+$(this).find("img").attr('title')+'</div>');
			// animate icon to fade in and move from top to the middle
			$($(this).find(".img_link_img").css("left",imgWidth/2-18));
			$($(this).find(".img_link_img").css("top",imgHeight/2-50));
			$(this).find(".img_link_img").animate({
				opacity: 0.75,
    			top: (imgHeight/2)-18
				},150);
			// create overlay for thumbtitle
			// animate title to fade in and move from top to the height of the title
			thumb_title_height=$(this).find(".thumb_title").height();
			$(this).find(".thumb_title").css({'top':-thumb_title_height});
			$(this).find(".thumb_title").width(imgWidth-10);
			$(this).find(".thumb_title").animate({
				opacity: 0.99,
    			top: 0
				},150);
		},function(){
			// kill overlay and icon on mouseout
			$(this).find(".img_link_div").remove();	
			$(this).find(".img_link_img").remove();	
		});	
	// append div for video previews	
		$(".video_view").hover(function(){
			// get image heights on mouseover
			imgWidth = $(this).find("img").width();
			imgHeight = $(this).find("img").height();
			// create overlay
			$(this).append('<div class="img_link_div"></div>');
			$(this).find(".img_link_div").width(imgWidth);
			$(this).find(".img_link_div").height(imgHeight);
			// create icon
			$(this).append('<div class="img_link_img"><img src="images/assets/video_view.png"></div>');
			// animate icon to fade in and move from top to the middle
			$($(this).find(".img_link_img").css("left",imgWidth/2-18));
			$($(this).find(".img_link_img").css("top",imgHeight/2-50));
			$(this).find(".img_link_img").animate({
				opacity: 0.75,
    			top: (imgHeight/2)-18
				},150);
		},function(){
			// kill overlay and icon on mouseout
			$(this).find(".img_link_div").remove();	
			$(this).find(".img_link_img").remove();	
		});
	
	// highlight the header of the blog cells
		$(".news_box").hover(function(){
			$(this).find(".news_box_header").addClass("news_box_header_hover");	
		},function(){
			$(this).find(".news_box_header").removeClass("news_box_header_hover");	
		});
	
	// Backbutton function goes one step back in history of the browser
		$("#back_button").click(function(){
			history.back();	
		});

	// Search Field Submit
		$('#searchSubmit').click(function(){
			$('#searchForm').submit();
		});

	// Input fields, Textareas default values
		// store default value in 
		$("input,textarea").each(function(){
			$(this).attr("alt",$(this).val());
		});
		// focus,blur restore Defaults or Not
		$("input,textarea").focus(function(){
			if($(this).val()==$(this).attr("alt")){
				$(this).val("");
			}
		});
		$("input,textarea").blur(function(){
			if($(this).val()==""){
				$(this).val($(this).attr("alt"));
			}	
		});
		
		
		// Enable Contact Form Send Button if all fields are filled (without defaults)
		$("#contactform input,textarea").keyup(function(){
				defaultValues=0; 
					$(".required").each(function(){
						if($(this).val()==$(this).attr("alt")||$(this).val()=="")
							defaultValues++;
					});
				if(!defaultValues && $("#email_address").val().match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i))
					$('#content input[type="submit"]').removeClass("disabledButton");
				else
					$('#content input[type="submit"]').addClass("disabledButton");
		});
	// Quotation module
		  var currentPosition = 0;
		  var quoteWidth = 255;
		  var quotes = $('.quote');
		  var numberOfQuotes = quotes.length;

		  // Remove scrollbar in JS
		  $('#quotesContainer').css('overflow', 'hidden');

		  // Wrap all .quotes with #quoteInner div
		  quotes
		  .wrapAll('<div id="quoteInner"></div>')
		  // Float left to display horizontally, readjust .quotes width
		  .css({
		    'float' : 'left',
		    'width' : quoteWidth
		  });

		  // Set #quoteInner width equal to total width of all quotes
		  $('#quoteInner').css('width', quoteWidth * numberOfQuotes);

		  // Create event listeners for .controls clicks
		  $('.control')
		    .bind('click', function(){
		    // Determine new position
		      currentPosition = ($(this).attr('id')=='quote_arrow')
		    ? currentPosition+1 : currentPosition-1;

		      // Hide / show controls
		      manageControls(currentPosition);
		      // Move quoteInner using margin-left
		      $('#quoteInner').animate({
		        'marginLeft' : quoteWidth*(-currentPosition)
		      });
		    });

		  function manageControls(position){

			if(position==numberOfQuotes)
				currentPosition=0;
		}
	// preload Image Function by Pogoking http://themeforest.net/forums/thread/wanted-jquery-image-loader/26301?page=2
	   $.fn.preloadImages = function(options){
			var defaults = {
				showSpeed: 500
        };

        var options = $.extend(defaults, options);

        return this.each(function(){
            var container = $(this);
            var image = container.find('img');

            $(image).css({ "visibility": "hidden", "opacity": "0" });
            $(image).bind('load error', function(){
                $(this).css({ "visibility": "visible" }).animate({ opacity:"1" }, {duration:options.showSpeed}).parent(container).removeClass('preload');
            }).each(function(){
                if(this.complete || ($.browser.msie && parseInt($.browser.version) == 6)) { $(this).trigger('load'); }
            });
        });
    }
	$("#blocks img").wrap('<span class="preload" />');
	
	$('.preload').preloadImages({
		showSpeed: 250//,   // length of fade-in animation, 500 is default
		//easing: 'easeOutQuad'   // optional easing, if you don't have any easing scripts - delete this option
	});	
	$("#content img").error(function () { 
    	$(this).attr("src","images/assets/loading.gif"); 
	});
	
	
	// contact form
        // As JavaScript is now present
        // we could safely set contact form to use AJAX
        $('#contactform').attr('action', '');
		
        // when 'Submit' button clicked
        $('#sendmail').click(function(){
			//Disable Contact Form submit if Submit/Send Button is disabled
		if(!$(this).hasClass("disabledButton")){
            var filterText = function(text){
                return text.toString()
                            .replace(/&/g, '&amp;')   // escape HTML characters
                            .replace(/>/g, '&gt;')
                            .replace(/</g, '&lt;')
                            .replace(/\"/g, '&quot')
            	            .replace(/\n/g, '\\n'); // fix multiline issues                                            
            };
                contact_name = filterText($('#first_name').val()+" "+$('#last_name').val()),  
	            contact_email = filterText($('#email_address').val()),    
	            contact_how = filterText($('#how_did_you').val()),      
	            contact_message = filterText($('#message').val().toString());     
            
            // check whether email is valid
	        /*if(!contact_email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i) || contact_email == defs.contact_email){
	            validMsg += '<li>' + defs.invalid_email + '</li>';
	        }*/
			var datastr = ('fromname=' + contact_name 
							+ '&mailfrom=' + contact_email 
							+ '&how=' + contact_how 
							+ '&msg=' + contact_message);
			// display sending information
			var origResponse_text = $('#response').text();
			$('#response_wrapper').css({"top":$("#blocks").position().top});
			$('#response_wrapper').show();
			$('#response').removeClass('response_success');
			$('#response')
	                .css('display', 'block')
	                .html("<img src='images/assets/contactloader_orange.gif'><br>We are sending...")
	                .fadeIn('slow');
                // try sending the message with no more than 5 seconds timeout
	            setTimeout(function(){
	                // AJAX script to do HTTP POST to /php/freshlr-mail.html 
                    // PHP script will then send a mail from your site's web server to your e-mail
                    $.ajax({
                        type: 'POST',
                        url: 'php/tiNY-mail.php',
                        data: datastr,
                        cache: false,
                        error: function(html){
                            $('#response')
                                .html(html)
                                .fadeIn('slow');
                            setTimeout(function(){
                                $('#response,#response_wrapper').fadeOut('slow');
                            }, 1500);
                        },
                        success: function(html){
							$('#response').addClass('response_success');
							$('#response')
                                .html(html)
                                .fadeIn('slow');
                            setTimeout(function(){
                                $('#response,#response_wrapper').fadeOut('slow');
								$("#contactform input,#contactform textarea").each(function(){
									$(this).val($(this).attr("alt"));
								});
								$('#content input[type="submit"]').addClass("disabledButton");
                            }, 1500);
                        }
                    });
	            }, 2000);
	        }
			
	        return false;
        });
		
});

// function to fit content to window size
function changeWindowSize(orig_myHeight){
	// set footer
	if($(window).height()>orig_myHeight+55){
		$('#footer').css("position","absolute");
		$("#footer").css("bottom","0px");
		$("#background_pattern").height($(window).height());
	}
	else{
		$('#footer').css("position","relative");
		$("#footer").css("bottom","");
		$("#footer").css("margin-top","0px");
		$("#background_pattern").height($(document).height());
	}
	// resize background pic in proportion if surrounding DIV
	// is not of class "stretch"
	// define original width and height of the image
	var origImg = $("#background_img");
	var imgWidth = $(origImg).attr('width');
	var imgHeight = $(origImg).attr('height');
	// define image ratio
	var ratio = imgHeight/imgWidth;
	// get window sizes
	var winWidth = $(window).width();
	var winHeight = $(window).height();
	// if  not stretch resize with ratio
	if(!$("#background_pic").hasClass("stretch")){
		var winRatio = winHeight/winWidth;
		// resizing
		if (winRatio > ratio) {
			$(origImg).height(winHeight);
			$(origImg).width(winHeight / ratio);
		} 
		else {
			$(origImg).width(winWidth);
			$(origImg).height(winWidth * ratio);
		}
	}
	// else resize to stretch to the window dimensions
	else{
			$(origImg).height(winHeight);
			$(origImg).width(winWidth);
	}
	$("#background_img").fadeIn(900);
}

function startNivo(){
	 /* Begin Nivo Slider JS
             ____  _     ___ ____  _____ ____  
            / ___|| |   |_ _|  _ \| ____|  _ \ 
            \___ \| |    | || | | |  _| | |_) |
             ___) | |___ | || |_| | |___|  _ < 
            |____/|_____|___|____/|_____|_| \_\
        
            */
               $('#slider').nivoSlider({
                    effect:'random', // Specify sets like: 'fold,fade,sliceDown'
                    slices:15, // For slice animations
                    boxCols: 8, // For box animations
                    boxRows: 4, // For box animations
                    animSpeed:500, // Slide transition speed
                    pauseTime:5000, // How long each slide will show
                    startSlide:0, // Set starting Slide (0 index)
                    directionNav:true, // Next & Prev navigation
                    directionNavHide:true, // Only show on hover
                    controlNav:true, // 1,2,3... navigation
                    controlNavThumbs:false, // Use thumbnails for Control Nav
                    controlNavThumbsFromRel:false, // Use image rel for thumbs
                    controlNavThumbsSearch: '.jpg', // Replace this with...
                    controlNavThumbsReplace: '_thumb.jpg', // ...this in thumb Image src
                    keyboardNav:true, // Use left & right arrows
                    pauseOnHover:true, // Stop animation while hovering
                    manualAdvance:false, // Force manual transitions
                    captionOpacity:1.0, // Universal caption opacity
                    prevText: 'Prev', // Prev directionNav text
                    nextText: 'Next', // Next directionNav text
                    beforeChange: function(){}, // Triggers before a slide transition
                    afterChange: function(){}, // Triggers after a slide transition
                    slideshowEnd: function(){}, // Triggers after all slides have been shown
                    lastSlide: function(){}, // Triggers when last slide is shown
                    afterLoad: function(){} // Triggers when slider has loaded
                });
            // End Nivo Slider	
}

function linkTo(link){
	self.location.href=link;
}

// special Window Load function for changing window sizes on reload/resize
$(window).load(function (){
	//startNivo if on page
	startNivo();
	// change layout to window size
	// orig size
	mainSize = ($("#main").height()+$("#footer").height());
	// bind function to window resize
	$(window).bind('resize', function() {
		changeWindowSize(mainSize);
	});
	// call one time for initial resizing
	changeWindowSize(mainSize);		
});

