// ---------------------------------------------------------
// Slideshow Navigation
// ---------------------------------------------------------

function paginate(idx, slide){
    return '<li><a href="" title="">#</a></li>';
}

// ---------------------------------------------------------
// jQuery
// ---------------------------------------------------------

$(document).ready(function() {

    // ---------------------------------------------------------
    // Main Menu
    // ---------------------------------------------------------

    $('#menu-wrapper .menu').superfish();
	
    // ---------------------------------------------------------
    // Contact Form
    // ---------------------------------------------------------

    // contact us $ form validation
    $("#form-contactus").validate({

        submitHandler: function(form) {
			
			//Define URL to PHP mail file
			var url = $(form).attr("action");

			//Define data string
            var datastring = $(form).serialize();
			
			//Submit form
            $.ajax({
                type: "POST",
                url: url,
                data: datastring,
                success: function(data){
                    
                    // detect result
                	var response = $.parseJSON(data);
                	
                	if(response.result=='true')
                	{	
                		$("#error").hide();
						$(form).slideUp();
                    	$('#sent').fadeIn();
                    }
                    else
                    {
                    	// set message
						$("#error").find(".error-msg").html("<h4>We're sorry, we were unable to send your message due to the following reason:</h4>"+ response.message);
		                $("#error").slideDown();
                    }
                },
                error: function(data)
				{
					// detect result
                	var response = data.statusText;
                	
                	// set message
					$("#error").html("<h4>We're sorry</h4>We encountered a system error: " + response);
                	$("#error").slideDown();
	                
					return false;
				}
         	});
        }

    });
    
    // ---------------------------------------------------------
    // Passport Login
    // ---------------------------------------------------------

    // login passport $ form validation
    $("#form-login-passport").validate({

        submitHandler: function(form) {
			
			//Define URL to PHP mail file
			var url = $(form).attr("action");

			//Define data string
            var datastring = $(form).serialize();
			
			//Submit form
            $.ajax({
                type: "POST",
                url: url,
                data: datastring,
                success: function(data){
                    
                    // detect result
                	var response = $.parseJSON(data);
                	
                	if(response.result=='true')
                	{
                		window.location.href = response.url;
                	}
                	else
                	{
                    	// set message
						$("#error").find(".error-msg").html("<h4>Login error:</h4>"+ response.message);
		                $("#error").slideDown();
                    }
                    
                },
                error: function(data)
				{
					// detect result
                	var response = data.statusText;
                	
                	// set message
					$("#error").find(".error-msg").html("<h4>We're sorry</h4>We encountered a system error: " + response);
                	$("#error").slideDown();
	                
					return false;
				}
         	});
        }

    });
    
    // ---------------------------------------------------------
    // Avatar Views
    // ---------------------------------------------------------
	
	function avatarViewLoggedIn(passport)
	{
		$("#avatar-login").fadeOut("normal", 
			function() {
				$("#avatar-account").html(passport.email);
				$("#avatar-account,#avatar-logout").fadeIn(); 
			});
	}
	
	function avatarViewLoggedOut()
	{	
		$("#avatar-account,#avatar-logout").fadeOut("normal",
			function() {
				$("#avatar-login").fadeIn();					
			});
	}
	
    // ---------------------------------------------------------
    // Avatar Logout
    // ---------------------------------------------------------

    // avatar logout link
    $("#avatar-logout").click(function(){

		//Define URL to PHP
		var url = "/passports/call_logout/";

		//Submit
        $.ajax({
            type: "POST",
            url: url,
            async: false,
            success: function(data){
                
                // detect result
            	var response = $.parseJSON(data);
            	
            	if(response.result=='true')
            	{
            		// slide here
            		window.location.reload();
            	}
            	else
            	{
                	// set message
					$("#avatar-error").find(".error-msg").html("<h4>Login error:</h4>"+ response.message);
	                $("#avatar-error").slideDown();
                }
                
            },
            error: function(data)
			{
				// detect result
            	var response = data.statusText;
            	
            	// set message
				$("#avatar-error").html("<h4>We're sorry</h4>We encountered a system error: " + response);
            	$("#avatar-error").slideDown();
                
				return false;
			}
     	});
    });
    
    // ---------------------------------------------------------
    // Enrollment / Email Form
    // ---------------------------------------------------------
	
	$(".form-enroll,.form-email,.form-recoverpassword").each(function(){
		
		$(this).validate({
			
	        submitHandler: function(form) {
				
				//Define URL to PHP mail file
				var url = $(form).attr("action");
				
				//Define data string
	        	var datastring = $(form).serialize();
				
				//Define close handles
				var rel = $(form).attr("rel");
				
				$.ajax({
					type: "POST",
					url: url,
					data: datastring,
					success: function(data)
					{
						// detect result
	                	var response = $.parseJSON(data);
	                	
	                	if(response.result=='true')
	                	{	
		                	// set message : force trigger-sequence
							$("#error-" + rel).hide();
		                	$("#trigger-" + rel).hide();
							$("#slider-box-" + rel).slideUp(function(){
							$("#trigger-" + rel + ",#trigger-repeat-" + rel).closest(".trigger-box.trigger-collapse").slideDown('fast', function(){ $("#success-" + rel).fadeIn(); });
							});
							
		                	// avatar
		                	if(response.request=='enroll')
		                		avatarViewLoggedIn(response);
		                		
		                	return true;
		                }
	                	else
	                	{	
							// set message
							$("#error-" + rel).find(".error-msg").html("<h4>We're sorry, we encountered a problem:</h4>"+ response.message);
		                	$("#error-" + rel).slideDown();
							
							// reset captcha
	                		if($("#captcha-" + rel).length > 0)
		                		Recaptcha.reload();
	                		
	                		return false;
						}
	               	},
					error: function(data)
					{
						// detect result
	                	var response = data.statusText;
	                	
	                	// set message
						$("#error-" + rel).find(".error-msg").html("<h4>We're sorry</h4>We encountered a system error: " + response);
	                	$("#error-" + rel).slideDown();
		                
						// reset captcha
		                if($("#captcha-" + rel).length > 0)
		                	Recaptcha.reload();
						
						return false;
					}
				});
	
			}

    	}); // validate (end)
    
    });
    
    // ---------------------------------------------------------
    // Parts
    // ---------------------------------------------------------

   	$('.parts').each(function(){
		
		var part = $(this);    
		
		//Define URL to PHP mail file
		var url = part.attr("rel");
		
		//Submit get
        $.ajax({
            type: "POST",
            url: url,
            success: function(data){

                // detect result
            	var response = $.parseJSON(data);
				
            	if(response.result=='true')
            	{
            		part.html(unescape(response.html));
            	}
            	else
            	{
                	// set error message
                	part.html('<p>Check back soon!</p>');
                }
                
            },
            error: function(data) {
            
				// set error message
                part.html('<p>Check back soon!</p>');
				return false;
			}
     	}); // end ajax
	});

	// ---------------------------------------------------------
    // Call
    // ---------------------------------------------------------

   	$('.call').click(function(){
		
		var call = $(this);    
		
		//Define URL to PHP mail file
		var url = call.attr("href");
		var part = $('"' + call.attr("rel") + '"');
		
		//Submit get
        $.ajax({
            type: "POST",
            url: url,
            success: function(data){

                // detect result
            	var response = $.parseJSON(data);
				
            	if(response.result=='true')
            	{
            		part.html(unescape(response.html));
            	}
            	else
            	{
                	// set error message
                	part.html('<p>Check back soon!</p>');
                }
                
            },
            error: function(data) {
            
				// set error message
                part.html('<p>Check back soon!</p>');
				return false;
			}
     	}); // end ajax
	});
	       
    // ---------------------------------------------------------
	// Comments Form
	// ---------------------------------------------------------
	
	$("#commentform .comment-form-author input").addClass('required');
	$("#commentform .comment-form-email input").addClass('required');
	$("#commentform .comment-form-comment textarea").addClass('required');
	$("#commentform").validate();

    // ---------------------------------------------------------
    // Portfolio Thumbnail
    // ---------------------------------------------------------

    $('.portfolio-box a.thumb').each(function(){
        if(this.href.match(/\.(mp3|avi|wav|mov|flv?)$/i)){
            $(this).addClass('video');
        } else {
            $(this).addClass('image');
        }
    });

    $('.portfolio-box a').hover(function() {

        //Show darkenned hover over thumbnail image
        $(this).find('img').stop(true, true).animate({opacity:0.5},400);

    }, function() {

        //Hide darkenned hover over thumbnail image
        $(this).find('img').stop(true, true).animate({opacity:1},400);

    });

    // ---------------------------------------------------------
    // Wordpress Gallery Lightbox Integration
    // ---------------------------------------------------------

    $('.gallery-item a').each(function(){
        if(this.href.match(/\.(jpe?g|png|bmp|gif|tiff?)$/i)){
            $(this).attr('rel','lightbox[gallery]');
        }
    });
	
	// ---------------------------------------------------------
    // Default Field Focus
    // ---------------------------------------------------------

	$('.focus').focus();
	
    // ---------------------------------------------------------
    // Image Buttons
    // ---------------------------------------------------------

    $('.image-button').css({opacity:1});

    $('.image-button').hover(function() {

        $(this).stop(true, true).animate({opacity:.75},100);

    }, function() {

        $(this).stop(true, true).animate({opacity:1},100);

    });
	
	// ---------------------------------------------------------
    // Image Selectors
    // ---------------------------------------------------------

    $('.image-selector').css({opacity:.75});

    $('.image-selector').hover(function() {

        $(this).stop(true, true).animate({opacity:1},100);

    }, function() {

        $(this).stop(true, true).animate({opacity:.75},100);

    });

	// ---------------------------------------------------------
    // Print Triggers
    // ---------------------------------------------------------

	$('.print').click(function(){ window.print(); return false; });
	
	
    // ---------------------------------------------------------
    // Innititate Pretty Photo
    // ---------------------------------------------------------

    $("a[rel^='lightbox']").prettyPhoto({
            theme: 'light_square', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
            show_title: false
    });

    // ---------------------------------------------------------
    // Tabs
    // ---------------------------------------------------------

    $(".themeblvd-tabs").each(function(){

        $(this).find(".tab").hide();
        
        // detect active
        var activeMenu = $(this).find(".tab-menu li a.active");
        
        if(activeMenu.length > 0) {
        	activeMenu.show();
        	var activeTab = activeMenu.attr("href");
        	$(activeTab).show();
        } 
        else {
        	// no default set, so set first tab active
        	$(this).find(".tab-menu li:first a").addClass("active").show();
        	$(this).find(".tab:first").show();
		}
		
    });
	
    $(".themeblvd-tabs").each(function(){
		
        $(this).find(".tab-menu a").click(function() {

            $(this).parent().parent().find("a").removeClass("active");
            $(this).addClass("active");
            $(this).parent().parent().parent().parent().find(".tab").hide();
            var activeTab = $(this).attr("href");
            $(activeTab).fadeIn();
            return false;

        });

    });

    // ---------------------------------------------------------
    // Toggle
    // ---------------------------------------------------------

    $(".themeblvd-toggle").each(function(){

        $(this).find(".box").hide();

    });

    $(".themeblvd-toggle").each(function(){

        $(this).find(".trigger").click(function() {

            $(this).toggleClass("active").next().stop(true, true).slideToggle("slow");

            return false;

        });

    });
    
    // ---------------------------------------------------------
    // Slider
    // ---------------------------------------------------------

    $(".slider").each(function(){
		
		var slider = $(this);
		
		slider.find(".trigger").click(function() {
			
			var trigger = $(this);
			var rel = trigger.attr("rel");
			var delay = 0;
			
			// close all boxes
        	//$(".trigger").each(function(){
        		
        		// close slide boxes
        		/*var this_rel = $(this).attr("rel");
				if($("#success-" + this_rel).is(":hidden"))
	     	   		$(this).find(".trigger-close").click();*/
	     	//});
	     	
	     	// captcha
        	if($("#captcha-" + rel).length > 0) {
	            Recaptcha.destroy();
	  			Recaptcha.create("6Le27sISAAAAAJNnxjL-_IS-F_EhMWsXC0ixwWh8", "captcha-" + rel, {
		        	theme: "clean"
	        	});
	        	setTimeout(function(){$("#recaptcha_response_field").focus();},300);
	        	
	        	delay=150;
        	}
        	
	     	// delay for cleanup
	     	var cleanYN = false;
	     	slider.find(".slider-box,.success-box").each(function(){
	     		if($(this).is(":visible"))
	     			cleanYN = true;
	     	});
	     	
	     	if(cleanYN) 
	     		delay=400;
	     	
	     	// cleanup any boxes
	     	slider.find(".slider-box,.success-box,.error-box").slideUp('fast');
     		
     		// close collapsable trigger
        	var collapse = slider.find("#trigger-" + rel + ",#trigger-repeat-" + rel).closest(".trigger-box.trigger-collapse");
        	
        	var sequence = slider.find("#trigger-" + rel + ",#trigger-repeat-" + rel).closest(".trigger-box.trigger-collapse.trigger-sequence");
        	
        	var focus = $("#slider-box-" + rel).find(".trigger-focus");
			
        	
        	if(sequence.length > 0) {
				collapse.delay(delay).slideUp('fast', function() {
	     			// open this box
					slider.find("#slider-box-" + rel).slideDown('fast', function() {
						focus.focus();
					});
				});
			}
			else if(collapse.length > 0)
			{
				collapse.delay(delay).slideUp('fast');
			
				// open this box
				slider.find("#slider-box-" + rel).delay(delay).slideDown('fast', function() {
					focus.focus();
				});
			}
			else
			{
				// open this box
				slider.find("#slider-box-" + rel).delay(delay).slideDown('fast', function() {
					focus.focus();
				});
			}
			
			//alert(delay);
			
     		// return
        	return false;
        });
		
		
		slider.find(".trigger-close").click(function() {
        	var trigger = $(this);
			var rel = trigger.attr("rel");
			
			var collapse = slider.find("#trigger-" + rel + ",#trigger-repeat-" + rel).closest(".trigger-box.trigger-collapse");
        	
        	var sequence = slider.find("#trigger-" + rel + ",#trigger-repeat-" + rel).closest(".trigger-box.trigger-collapse.trigger-sequence");
        	
        	
        	if(sequence.length > 0) {
				// close this box
				slider.find("#slider-box-" + rel).slideUp('fast', function() {
					// collapse trigger box
    	    		collapse.slideDown('fast');
	    		});
			}
			else if(collapse.length > 0)
			{
				// close this box
    			slider.find("#slider-box-" + rel).slideUp('fast');
    			// collapse trigger box
    			collapse.slideDown('fast');
			}
			else
			{
				// close this box
    			slider.find("#slider-box-" + rel).slideUp('fast');
    		}
    		
    		// close error box
        	slider.find("#error-" + rel).slideUp('fast');
	    	
            return false;
        });

    });

}); // End DOM ready


//Twitter Widget
(function(jQuery) {
	/*
		jquery.twitter.js v1.5
		Last updated: 08 July 2009

		Created by Damien du Toit
		http://coda.co.za/blog/2008/10/26/jquery-plugin-for-twitter

		Licensed under a Creative Commons Attribution-Non-Commercial 3.0 Unported License
		http://creativecommons.org/licenses/by-nc/3.0/
	*/

	jQuery.fn.getTwitter = function(options) {

		jQuery.fn.getTwitter.defaults = {
			userName: null,
			numTweets: 5,
			loaderText: "Loading tweets...",
			slideIn: true,
			slideDuration: 750,
			showHeading: true,
			headingText: "Latest Tweets",
			showProfileLink: true,
			showTimestamp: true
		};

		var o = jQuery.extend({}, jQuery.fn.getTwitter.defaults, options);

		return this.each(function() {
			var c = jQuery(this);

			// hide container element, remove alternative content, and add class
			c.hide().empty().addClass("twitted");

			// add heading to container element
			if (o.showHeading) {
				c.append("<h2>"+o.headingText+"</h2>");
			}

			// add twitter list to container element
			var twitterListHTML = "<ul id=\"twitter_update_list\"><li></li></ul>";
			c.append(twitterListHTML);

			var tl = jQuery("#twitter_update_list");

			// hide twitter list
			tl.hide();

			// add preLoader to container element
			var preLoaderHTML = jQuery("<p class=\"preLoader\">"+o.loaderText+"</p>");
			c.append(preLoaderHTML);

			// add Twitter profile link to container element
			if (o.showProfileLink) {
				var profileLinkHTML = "<p class=\"profileLink\"><a href=\"http://twitter.com/"+o.userName+"\">http://twitter.com/"+o.userName+"</a></p>";
				c.append(profileLinkHTML);
			}

			// show container element
			c.show();

			jQuery.getScript("https://twitter.com/javascripts/blogger.js");
			jQuery.getScript("https://twitter.com/statuses/user_timeline/"+o.userName+".json?callback=twitterCallback2&count="+o.numTweets, function() {
				// remove preLoader from container element
				jQuery(preLoaderHTML).remove();

				// remove timestamp and move to title of list item
				if (!o.showTimestamp) {
					tl.find("li").each(function() {
						var timestampHTML = jQuery(this).children("a");
						var timestamp = timestampHTML.html();
						timestampHTML.remove();
						jQuery(this).attr("title", timestamp);
					});
				}

				// show twitter list
				if (o.slideIn) {
					// a fix for the jQuery slide effect
					// Hat-tip: http://blog.pengoworks.com/index.cfm/2009/4/21/Fixing-jQuerys-slideDown-effect-ie-Jumpy-Animation
					var tlHeight = tl.data("originalHeight");

					// get the original height
					if (!tlHeight) {
						tlHeight = tl.show().height();
						tl.data("originalHeight", tlHeight);
						tl.hide().css({height: 0});
					}

					tl.show().animate({height: tlHeight}, o.slideDuration);
				}
				else {
					tl.show();
				}

				// add unique class to first list item
				tl.find("li:first").addClass("firstTweet");

				// add unique class to last list item
				tl.find("li:last").addClass("lastTweet");
			});
		});
	};
})(jQuery);
