//This file contains a the drop down menu script, a script to fix the z-index issues that occur with the slider/navs in IE, and initializes the colorbox and innerfade script.

/*-----------------------------------------------------------------------------------

 	Mail enCrypt
 
-----------------------------------------------------------------------------------*/

    function UnCryptMailto( s )
    {
        var n = 0;
        var r = "";
        for( var i = 0; i < s.length; i++)
        {
            n = s.charCodeAt( i );
            if( n >= 8364 )
            {
                n = 128;
            }
            r += String.fromCharCode( n - 1 );
        }
        return r;
    }

    function linkTo_UnCryptMailto( s )
    {
        location.href=UnCryptMailto( s );
    }

	$(document).ready(function() {
	
/*-----------------------------------------------------------------------------------*/
/*	Home slides
/*-----------------------------------------------------------------------------------*/
	
		$(function(){
			$('#slides').slides({
				preload: true,
				generateNextPrev: false,
				preloadImage: 'images/colorbox/loading.gif',
				play: 5000,
				pause: 2500,
				hoverPause: true
			});
		});
	
		
/*-----------------------------------------------------------------------------------*/
/*	Home tricks news
/*-----------------------------------------------------------------------------------*/
	


	function tick(){
		$('#ticker_01 li:first').slideUp( function () { $(this).appendTo($('#ticker_01')).slideDown(); });
	}
	setInterval(function(){ tick () }, 5000);

/*
	function tick2(){
		$('#ticker_02 li:first').slideUp( function () { $(this).appendTo($('#ticker_02')).slideDown(); });
	}
	setInterval(function(){ tick2 () }, 3000);


	function tick3(){
		$('#ticker_03 li:first').animate({'opacity':0}, 200, function () { $(this).appendTo($('#ticker_03')).css('opacity', 1); });
	}
	setInterval(function(){ tick3 () }, 4000);	

	function tick4(){
		$('#ticker_04 li:first').slideUp( function () { $(this).appendTo($('#ticker_04')).slideDown(); });
	}


	
	// USE TWITTER DATA	

	 $.ajax ({
		 url: 'http://search.twitter.com/search.json',
		 data: 'q=%23javascript',
		 dataType: 'jsonp',
		 timeout: 10000,
		 success: function(data){
		 	if (!data.results){
		 		return false;
		 	}

		 	for( var i in data.results){
		 		var result = data.results[i];
		 		var $res = $("<li />");
		 		$res.append('<img src="' + result.profile_image_url + '" />');
		 		$res.append(result.text);

		 		console.log(data.results[i]);
		 		$res.appendTo($('#ticker_04'));
		 	}
			setInterval(function(){ tick4 () }, 4000);	

			$('#example_4').show();

		 }
		 
	});
*/

/*-----------------------------------------------------------------------------------*/
/*	     SCROLL TO TOP JAVASCRIPT
/*-----------------------------------------------------------------------------------*/
	// Scroll to top animation
	$('.scroll-top').click(function(){ 
		$('html, body').animate({scrollTop:0}, 600); return false; 
	});
	/*
$(document).ready(function($){
    $('a[href=#wrapper]').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
        && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({scrollTop: targetOffset}, 500);
                return false;
            }
        }
    });
});
*/

	
	
/*-----------------------------------------------------------------------------------*/
/*	Image Preload
/*-----------------------------------------------------------------------------------*/

	var speed = 50; //speed in ms
	$('.logo').animate({ opacity: 0 }, 0);
$('.introtexthome').animate({ opacity: 0 }, 0);
$('.box-c').animate({ opacity: 0 }, 0);
$('.banner').animate({ opacity: 0 }, 0);
$('.ticker').animate({ opacity: 0 }, 0);
$('.center h5').animate({ opacity: 0 }, 0);
$('#slides').animate({ opacity: 0 }, 0);
$('.portfolioitem').animate({ opacity: 0 }, 0);
	$('.topnav li').animate({ opacity: 0 }, 0);	
	$(window).load(function() {
	
		$(".scroll-pane img, #gallery-wrap img").hide();
		
		timer = setInterval(function(){
		
			$notLoaded = $(".scroll-pane img, #gallery-wrap img").not(".loaded");
			$notLoaded.eq(Math.floor(Math.random()*$notLoaded.length)).fadeIn().addClass("loaded");
			
			if ($notLoaded.length == 0) {
				clearInterval(timer);
			}
		}, speed);

		

		$('.logo').animate({ opacity: 1 }, 2000);
		$('.introtexthome').delay(500).animate({ opacity: 1 }, 1000);
		$('.ticker').delay(1000).animate({ opacity: 1 }, 1000)
		$('.banner').delay(500).animate({ opacity: 1 }, 1000)
		$('.box-c').delay(1000).animate({ opacity: 1 }, 1000);
		$('.center h5').delay(1100).animate({ opacity: 1 }, 1000);
		$('#slides').delay(1600).animate({ opacity: 1 }, 1000);	
						$('.portfolioitem').delay(1500).animate({ opacity: 1 }, 1000);

		$('.topnav li').animate({ opacity: 1 }, 1000);
	}); 

/*-----------------------------------------------------------------------------------*/
/*	Image Hover
/*-----------------------------------------------------------------------------------*/

	$('#gallery-wrap img, .imagelist a img, .gallery .thumb a img, .portfolioitem a img').hover( function() { 
		$(this).stop().animate({opacity : 0.5 }, 200);
	}, function () {
		$(this).stop().animate({opacity : 1 }, 200);
	});

});

//Drop Down Loader
$(function() {
	$("ul.topnav li span").hover(function() { //When trigger hovered over...
		
		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").stop().slideDown('fast').show('slow', function(){
			$(this).height("auto");
		}); //Drop down the subnav on click


		$(this).parent().hover(function() {
		}, function(){	
			$(this).parent().find("ul.subnav").stop().slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
		});

		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() { 
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});

});

//Fixes Z-Index Issues
//$(function() {
//	var zIndexNumber = 1000;
//	$('div').each(function() {
	//	$(this).css('zIndex', zIndexNumber);
	//	zIndexNumber -= 10;
	//});
//});


//Initializes the Innerfade Script	
$(function() {
	$('#slides').innerfade({
		speed: 1000,
		timeout: 3000,
		type: 'sequence',
		containerheight: '283px'
	});
});


//Initializes the Colorbox Script
$(function(){
    // Loads the call for the gallery
    $("a[rel='colorbox']").colorbox();
    $(".colorbox").colorbox();
    
    // Form
    var bind_form_events =function() {
        $("#fp_form").submit(function() {
            var fvalues = $("#fp_form").serialize();
            ajLoad("#cboxLoadedContent div:first", {
                type        : 'POST',
                url         : $("#fp_form").attr('action'),
                data        : fvalues,
                success     : bind_form_events
            });
            return false;
        });
    };
    $(".colorbox_form").colorbox({
        onComplete : bind_form_events
    });

    // ???
    $("#click").click(function(){ 
        $('#click').css({"background-color":"#f00", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here.");
        return false;
    });
});


// A "load" which uses our defaults and displays a loading image
function ajLoad(domnode, args) {
    if (!args) { args = {} };
    
    // Override success so that it replaces the data in the
    // domnode and then calls the original success; it also
    // animates the thing a bit to show change in the page
    var success = args.success;
    delete args.success;
    $.extend(args, {
        success  : function(data) {
            $(domnode).html(data);
            if (success) { success(data); }
        },
        dataType : 'html' // Always HTML
    });
    
    // Put a toaster in the div
    //$(domnode).html(that.toaster_html);
    
    delete args.noeffect;
    aj(args);
};

// Makes an Ajax HTML request with sensible defaults    
function aj(args, dataType) {
    // On some parameters we test against undefined as the caller might
    // pass null values on purpose
    $.ajax({
        type:       args.type || 'POST',
        dataType:   dataType,
        url:        args.url,
        data:       (args.data !== undefined ? args.data : null),
        timeout:    30000,
        success:    args.success,
        beforeSend: args.beforeSend,
        error:      (args.error !== undefined ? args.error : _ajError)
    });
};

function _ajError() {
    alert("Error in Ajax call.\n\nThis might be due to a network error. Please reload the page and try again.");
};

